100 lines
3.1 KiB
PHP
100 lines
3.1 KiB
PHP
<?php
|
||
|
||
namespace app\api\controller;
|
||
|
||
use think\Controller;
|
||
use think\Db;
|
||
use think\Log;
|
||
|
||
class Wechat extends Controller
|
||
{
|
||
|
||
private $appId = 'wx0f0c0c0c0c0c0c0c';
|
||
private $appSecret = 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx';
|
||
|
||
/**
|
||
* 核心:用code换取openid的方法
|
||
* @param string $code 微信回调带来的code
|
||
* @return string|bool 成功返回openid,失败返回false
|
||
*/
|
||
private function exchangeCodeForOpenId()
|
||
{
|
||
$code = input('code', 0);
|
||
|
||
// 构建请求URL
|
||
$url = "https://api.weixin.qq.com/sns/oauth2/access_token?" .
|
||
"appid={$this->appId}&" .
|
||
"secret={$this->appSecret}&" .
|
||
"code={$code}&" .
|
||
"grant_type=authorization_code";
|
||
|
||
Log::info('[微信授权] 请求微信接口URL:' . $url);
|
||
|
||
// 发送请求
|
||
$ch = curl_init();
|
||
curl_setopt($ch, CURLOPT_URL, $url);
|
||
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
|
||
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
|
||
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
|
||
curl_setopt($ch, CURLOPT_TIMEOUT, 10);
|
||
|
||
$response = curl_exec($ch);
|
||
$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
|
||
|
||
if (curl_errno($ch)) {
|
||
Log::error('[微信授权] 请求失败:' . curl_error($ch));
|
||
curl_close($ch);
|
||
return ['code' => 0, 'msg' => '[微信授权] 请求失败:' . curl_error($ch), 'data' => null];
|
||
}
|
||
|
||
curl_close($ch);
|
||
|
||
Log::info('[微信授权] 微信返回原始数据:' . $response);
|
||
|
||
// 解析返回的JSON
|
||
$data = json_decode($response, true);
|
||
|
||
if (empty($data) || isset($data['errcode'])) {
|
||
Log::error('[微信授权] 解析失败或返回错误', $data);
|
||
return false;
|
||
return ['code' => 0, 'msg' => '[微信授权] 解析失败或返回错误', 'data' => null];
|
||
}
|
||
|
||
// 成功获取到openid
|
||
return ['code' => 1, 'msg' => '获取成功', 'data' => ['openid' => $data['openid']]];
|
||
}
|
||
|
||
|
||
/*
|
||
* 获取用户信息
|
||
* @param string $user_code 用户的user_code
|
||
* @return array|bool 成功返回用户信息,失败返回false
|
||
*/
|
||
public function getUserInfo($user_code)
|
||
{
|
||
$user_info = db::name('user')
|
||
->field('id user_id,nickname,avatar,mobile')
|
||
->where(['u.user_code' => $user_code,'u.status' => ['<>',0]])->find();
|
||
if(!$user_info){
|
||
return ['code' => 0, 'msg' => '用户不存在或已注销', 'data' => null];
|
||
}
|
||
return ['code' => 1, 'msg' => '获取成功', 'data' => $user_info];
|
||
}
|
||
|
||
|
||
/*
|
||
* 可充值的金额
|
||
* @param string $user_code 用户的user_code
|
||
* @return array|bool 充值金额,失败返回false
|
||
*/
|
||
public function getRechargeMoney($user_code)
|
||
{
|
||
$money_coin = [
|
||
['coin' => '1', 'money' => '0.10'],
|
||
['coin' => '60', 'money' => '6.00'],
|
||
['coin' => '1000', 'money' => '100.00'],
|
||
];
|
||
return ['code' => 1, 'msg' => '获取成功', 'data' => $money_coin];
|
||
}
|
||
|
||
} |