Files
yusheng-php/application/api/controller/Wechat.php

104 lines
3.0 KiB
PHP
Raw Normal View History

2026-01-23 11:39:09 +08:00
<?php
namespace app\api\controller;
use think\Controller;
use think\Db;
use think\Log;
class Wechat extends Controller
{
2026-01-26 10:10:30 +08:00
private string $appId = 'wx0f0c0c0c0c0c0c0c';
private string $appSecret = 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx';
2026-01-23 12:00:08 +08:00
2026-01-26 10:06:51 +08:00
/*
2026-01-23 11:39:09 +08:00
* 核心用code换取openid的方法
* @param string $code 微信回调带来的code
* @return string|bool 成功返回openid失败返回false
*/
2026-01-26 10:10:30 +08:00
public function exchangeOpenId()
2026-01-23 11:39:09 +08:00
{
$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);
2026-01-26 10:10:30 +08:00
return V(0, '[微信授权] 请求失败:' . curl_error($ch));
2026-01-23 11:39:09 +08:00
}
curl_close($ch);
Log::info('[微信授权] 微信返回原始数据:' . $response);
// 解析返回的JSON
$data = json_decode($response, true);
if (empty($data) || isset($data['errcode'])) {
2026-01-26 10:16:57 +08:00
Log::error('[微信授权] 解析失败或返回错误'.json_encode($data));
2026-01-23 11:39:09 +08:00
return false;
2026-01-26 10:10:30 +08:00
return V(1, '[微信授权] 解析失败或返回错误');
2026-01-23 11:39:09 +08:00
}
// 成功获取到openid
2026-01-26 10:21:58 +08:00
return V(1, '获取成功', $data['openid']);
2026-01-23 11:39:09 +08:00
}
/*
* 获取用户信息
* @param string $user_code 用户的user_code
* @return array|bool 成功返回用户信息失败返回false
*/
2026-01-26 09:56:52 +08:00
public function getUserInfo()
2026-01-23 11:39:09 +08:00
{
2026-01-26 09:56:52 +08:00
$user_code = input('user_code', 0);
2026-01-23 11:39:09 +08:00
$user_info = db::name('user')
2026-01-26 10:04:47 +08:00
->field('id user_id,nickname,avatar,mobile,user_code')
2026-01-26 10:00:41 +08:00
->where(['user_code' => $user_code,'status' => ['<>',0]])->find();
2026-01-23 11:39:09 +08:00
if(!$user_info){
return ['code' => 0, 'msg' => '用户不存在或已注销', 'data' => null];
}
2026-01-26 09:56:52 +08:00
return V(1, '获取成功', $user_info);
2026-01-23 11:39:09 +08:00
}
/*
* 可充值的金额
* @param string $user_code 用户的user_code
* @return array|bool 充值金额失败返回false
*/
2026-01-26 09:56:52 +08:00
public function getRechargeMoney()
2026-01-23 11:39:09 +08:00
{
$money_coin = [
['coin' => '1', 'money' => '0.10'],
['coin' => '60', 'money' => '6.00'],
['coin' => '1000', 'money' => '100.00'],
];
2026-01-26 09:56:52 +08:00
return V(1, '获取成功', $money_coin);
2026-01-23 11:39:09 +08:00
}
}