文件
yjyf/server/application/common/library/WxLogin.php
MiAn 0370cb9bd6 feat: 新增师傅入驻审核与接单状态联动功能
- 新增师傅资质审核模块及权限
- 未审核通过的师傅默认禁用接单状态
- 新增售后退款申诉功能与相关界面
- 新增用户钱包管理及充值功能
- 更新服务定价矩阵相关数据库结构
- 修复微信支付证书验证问题
2026-11-17 10:28:01 +08:00

268 行
11 KiB
PHP

此文件含有模棱两可的 Unicode 字符

此文件含有可能会与其他字符混淆的 Unicode 字符。 如果您是想特意这样的,可以安全地忽略该警告。 使用 Escape 按钮显示他们。

<?php
namespace app\common\library;
use think\Db;
/**
* 微信登录
* - jscode2session:小程序 code 换 openid
* - provision:按 openid 落库(fa_user + fa_user_wechat),幂等
*/
class WxLogin
{
/**
* 小程序 code 换取 session
* @return array|false 成功返回 ['openid'=>..,'session_key'=>..,'unionid'=>..]
*/
public static function jscode2session($code)
{
$appid = trim((string)\think\Env::get('wechat.appid', ''));
$secret = trim((string)\think\Env::get('wechat.secret', ''));
if ($appid === '' || $secret === '') {
return ['error' => '微信登录参数未配置完整(请检查 server/.env 的 wechat.appid 与 wechat.secret)', 'errcode' => -1001];
}
$code = trim((string)$code);
if ($code === '') {
return ['error' => '缺少微信登录临时凭证 code,请在微信小程序内重新打开重试', 'errcode' => -1002];
}
$url = 'https://api.weixin.qq.com/sns/jscode2session?appid=' . urlencode($appid)
. '&secret=' . urlencode($secret)
. '&js_code=' . urlencode($code)
. '&grant_type=authorization_code';
$sslOpts = ['verify_peer' => true, 'verify_peer_name' => true];
$caFile = dirname(__DIR__, 3) . DIRECTORY_SEPARATOR . 'addons' . DIRECTORY_SEPARATOR . 'epay' . DIRECTORY_SEPARATOR . 'certs' . DIRECTORY_SEPARATOR . 'cacert.pem';
if (@is_file($caFile)) {
$sslOpts['cafile'] = $caFile;
} elseif (@is_file('D:/Softwares/Git/usr/ssl/certs/ca-bundle.crt')) {
$sslOpts['cafile'] = 'D:/Softwares/Git/usr/ssl/certs/ca-bundle.crt';
}
$ctx = stream_context_create([
'http' => ['timeout' => 8, 'ignore_errors' => true],
'ssl' => $sslOpts,
]);
$resp = @file_get_contents($url, false, $ctx);
if ($resp === false) {
$lastErr = error_get_last();
$errHint = !empty($lastErr['message']) ? $lastErr['message'] : '网络超时或 SSL 证书校验失败';
\think\Log::error('[WxLogin::jscode2session] HTTP请求失败: ' . $errHint);
return ['error' => '连接微信授权接口失败(请检查服务器外网HTTPS与CA根证书配置)', 'errcode' => -1003];
}
$wx = json_decode($resp, true);
if (!is_array($wx) || empty($wx['openid'])) {
$ec = isset($wx['errcode']) ? (int)$wx['errcode'] : -1004;
$em = isset($wx['errmsg']) ? (string)$wx['errmsg'] : '接口返回报文无效';
$hint = [
-1 => '微信登录服务暂时繁忙,请稍后重试',
40029 => '微信临时登录凭证 code 无效或小程序 AppID 与服务端配置不一致(服务端配置为:' . $appid . ')',
40125 => '微信小程序密钥 appsecret 配置错误,请检查 server/.env 的 [wechat] secret',
40163 => '微信登录凭证 code 已被使用过一次,请重新点击操作获取新授权',
41002 => '请求缺少小程序 AppID 参数',
41004 => '请求缺少小程序密钥 appsecret 参数',
45011 => '微信登录请求过于频繁触发限流,请稍后再试',
40226 => '该微信账号触发微信安全风控拦截,暂时无法授权登录',
];
$msg = isset($hint[$ec]) ? $hint[$ec] : ('微信授权登录校验未通过(微信错误码:' . $ec . '),请核对小程序 AppID/Secret 配置或重试');
\think\Log::error("[WxLogin::jscode2session] errcode={$ec}, errmsg={$em}");
return ['error' => $msg, 'errcode' => $ec];
}
return $wx;
}
/**
* 按 openid 落库(幂等)
* @return array ['user_id' => int, 'is_new' => 0|1]
*/
public static function provision($openid, $unionid = '', $sessionKey = '', $nickname = '', $avatar = '')
{
$openid = (string)$openid;
$bind = Db::name('user_wechat')->where('openid', $openid)->find();
$userId = $bind ? (int)$bind['user_id'] : 0;
// 绑定记录存在但用户已被删除 → 重建
if ($userId > 0 && !Db::name('user')->where('id', $userId)->find()) {
$userId = 0;
}
$isNew = 0;
if ($userId === 0) {
$isNew = 1;
$userId = Db::name('user')->insertGetId([
'group_id' => 1,
'username' => 'wx' . substr(md5($openid), 0, 10),
'nickname' => $nickname !== '' ? mb_substr($nickname, 0, 20) : ('用户' . substr($openid, -4)),
'avatar' => $avatar,
'status' => 'normal',
'jointime' => time(),
'createtime' => time(),
'updatetime' => time(),
]);
}
$data = [
'user_id' => $userId,
'openid' => $openid,
'unionid' => (string)$unionid,
'session_key' => (string)$sessionKey,
'updatetime' => time(),
];
if ($nickname !== '') {
$data['nickname'] = mb_substr($nickname, 0, 64);
}
if ($avatar !== '') {
$data['avatar'] = $avatar;
}
if ($bind) {
Db::name('user_wechat')->where('id', $bind['id'])->update($data);
} else {
$data['createtime'] = time();
Db::name('user_wechat')->insert($data);
}
$userUpdate = ['updatetime' => time()];
if ($nickname !== '') {
$userUpdate['nickname'] = mb_substr($nickname, 0, 20);
}
if ($avatar !== '') {
$userUpdate['avatar'] = $avatar;
}
Db::name('user')->where('id', $userId)->update($userUpdate);
return ['user_id' => $userId, 'is_new' => $isNew];
}
/**
* 获取微信 access_token (带缓存)
*/
public static function getAccessToken()
{
$cached = \think\Cache::get('wechat_access_token');
if ($cached) {
return $cached;
}
$appid = \think\Env::get('wechat.appid');
$secret = \think\Env::get('wechat.secret');
if (!$appid || !$secret) {
return ['error' => '微信配置缺失'];
}
$url = 'https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=' . $appid . '&secret=' . $secret;
$ctx = stream_context_create(['http' => ['timeout' => 8, 'ignore_errors' => true]]);
$resp = @file_get_contents($url, false, $ctx);
if ($resp === false) {
return ['error' => '微信服务不可达'];
}
$data = json_decode($resp, true);
if (empty($data['access_token'])) {
return ['error' => isset($data['errmsg']) ? $data['errmsg'] : '获取 access_token 失败', 'errcode' => isset($data['errcode']) ? $data['errcode'] : 0];
}
$token = $data['access_token'];
$expire = isset($data['expires_in']) ? max(60, (int)$data['expires_in'] - 200) : 6000;
\think\Cache::set('wechat_access_token', $token, $expire);
return $token;
}
/**
* 通过手机号快速验证 code 换取用户真实手机号
*/
public static function getPhoneNumber($code)
{
$token = self::getAccessToken();
if (is_array($token) && isset($token['error'])) {
return $token;
}
$url = 'https://api.weixin.qq.com/wxa/business/getuserphonenumber?access_token=' . $token;
$body = json_encode(['code' => (string)$code]);
$ctx = stream_context_create([
'http' => [
'method' => 'POST',
'header' => "Content-Type: application/json\r\n",
'content' => $body,
'timeout' => 8,
'ignore_errors' => true
]
]);
$resp = @file_get_contents($url, false, $ctx);
if ($resp === false) {
return ['error' => '网络超时,获取手机号失败'];
}
$data = json_decode($resp, true);
if (empty($data) || !isset($data['errcode']) || (int)$data['errcode'] !== 0 || empty($data['phone_info'])) {
$ec = isset($data['errcode']) ? (int)$data['errcode'] : -1;
$em = isset($data['errmsg']) ? $data['errmsg'] : '换取手机号失败';
if ($ec === 40001 || $ec === 42001) {
\think\Cache::rm('wechat_access_token');
}
return ['error' => $em, 'errcode' => $ec];
}
return $data['phone_info'];
}
/**
* 按手机号结合 openid 注册或登录(幂等合并)
*/
public static function provisionWithMobile($mobile, $openid = '', $unionid = '', $sessionKey = '')
{
$mobile = trim((string)$mobile);
$openid = trim((string)$openid);
$userId = 0;
$isNew = 0;
// 1. 优先按手机号匹配已存在用户
$existUser = Db::name('user')->where('mobile', $mobile)->find();
if ($existUser) {
$userId = (int)$existUser['id'];
}
// 2. 若手机号未查到,但有 openid,检查 user_wechat 是否已有用户
if ($userId === 0 && $openid !== '') {
$bind = Db::name('user_wechat')->where('openid', $openid)->find();
if ($bind && Db::name('user')->where('id', $bind['user_id'])->find()) {
$userId = (int)$bind['user_id'];
Db::name('user')->where('id', $userId)->update(['mobile' => $mobile, 'updatetime' => time()]);
}
}
// 3. 用户完全不存在,则注册新用户
if ($userId === 0) {
$isNew = 1;
$userId = Db::name('user')->insertGetId([
'group_id' => 1,
'username' => 'wx_' . $mobile,
'mobile' => $mobile,
'nickname' => '用户' . substr($mobile, -4),
'avatar' => '',
'status' => 'normal',
'jointime' => time(),
'createtime' => time(),
'updatetime' => time(),
]);
}
// 4. 若有 openid,建立或更新关联
if ($openid !== '') {
$bind = Db::name('user_wechat')->where('openid', $openid)->find();
$bindData = [
'user_id' => $userId,
'openid' => $openid,
'unionid' => (string)$unionid,
'session_key' => (string)$sessionKey,
'updatetime' => time(),
];
if ($bind) {
Db::name('user_wechat')->where('id', $bind['id'])->update($bindData);
} else {
$bindData['createtime'] = time();
Db::name('user_wechat')->insert($bindData);
}
}
return ['user_id' => $userId, 'is_new' => $isNew];
}
}