- epay插件配置:在config.php/config.html中增加微信支付公钥ID、APIv3密钥、回调根域名、转账场景ID等完整字段 - WxPayV3Service:读取微信支付配置时优先从epay插件读取,保留site配置兜底降级能力 - WxLogin与Wxpay:更新配置读取与错误提示说明 - site.php与SQL:系统配置聚焦维护用户端与师傅端小程序AppID与Secret,避免配置分散冲突
449 行
18 KiB
PHP
449 行
18 KiB
PHP
<?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 getMiniAppConfig($side = 'user')
|
||
{
|
||
$side = $side === 'master' ? 'master' : 'user';
|
||
if ($side === 'master') {
|
||
return [
|
||
'appid' => trim((string)\think\Config::get('site.wechat_master_appid')),
|
||
'secret' => trim((string)\think\Config::get('site.wechat_master_secret')),
|
||
];
|
||
}
|
||
return [
|
||
'appid' => trim((string)\think\Config::get('site.wechat_user_appid')),
|
||
'secret' => trim((string)\think\Config::get('site.wechat_user_secret')),
|
||
];
|
||
}
|
||
|
||
public static function jscode2session($code, $side = 'user')
|
||
{
|
||
$side = $side === 'master' ? 'master' : 'user';
|
||
$cfg = self::getMiniAppConfig($side);
|
||
$appid = $cfg['appid'];
|
||
$secret = $cfg['secret'];
|
||
if ($appid === '' || $secret === '') {
|
||
$label = $side === 'master' ? '师傅端' : '用户端';
|
||
return ['error' => "{$label}微信登录参数未配置完整(请在后台「常规管理 -> 系统配置 -> 小程序配置」填写 AppID 与 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 (按端独立缓存,防止双小程序互相覆盖)
|
||
* @param string $side user|master
|
||
*/
|
||
public static function getAccessToken($side = 'user')
|
||
{
|
||
$side = $side === 'master' ? 'master' : 'user';
|
||
$cacheKey = 'wechat_access_token_' . $side;
|
||
$cached = \think\Cache::get($cacheKey);
|
||
if ($cached) {
|
||
return $cached;
|
||
}
|
||
|
||
$cfg = self::getMiniAppConfig($side);
|
||
$appid = $cfg['appid'];
|
||
$secret = $cfg['secret'];
|
||
if (!$appid || !$secret) {
|
||
return ['error' => ($side === 'master' ? '师傅端' : '用户端') . '微信配置缺失'];
|
||
}
|
||
|
||
$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'])) {
|
||
$ec = isset($data['errcode']) ? (int)$data['errcode'] : 0;
|
||
$em = isset($data['errmsg']) ? (string)$data['errmsg'] : '获取 access_token 失败';
|
||
\think\Log::error("[WxLogin::getAccessToken] side={$side}, errcode={$ec}, errmsg={$em}");
|
||
return ['error' => '微信服务授权异常,请稍后重试', 'errcode' => $ec];
|
||
}
|
||
|
||
$token = $data['access_token'];
|
||
$expire = isset($data['expires_in']) ? max(60, (int)$data['expires_in'] - 200) : 6000;
|
||
\think\Cache::set($cacheKey, $token, $expire);
|
||
return $token;
|
||
}
|
||
|
||
/**
|
||
* 通过手机号快速验证 code 换取真实手机号
|
||
* @param string $code
|
||
* @param string $side user|master
|
||
*/
|
||
public static function getPhoneNumber($code, $side = 'user')
|
||
{
|
||
$side = $side === 'master' ? 'master' : 'user';
|
||
$token = self::getAccessToken($side);
|
||
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']) ? (string)$data['errmsg'] : '换取手机号失败';
|
||
if ($ec === 40001 || $ec === 42001) {
|
||
\think\Cache::rm('wechat_access_token_' . $side);
|
||
}
|
||
\think\Log::error("[WxLogin::getPhoneNumber] side={$side}, errcode={$ec}, errmsg={$em}");
|
||
$hint = [
|
||
40029 => '手机号授权凭证已失效,请重新点击登录',
|
||
40163 => '手机号授权凭证已被使用,请重新点击登录',
|
||
40001 => '微信登录凭证已刷新,请重试',
|
||
42001 => '微信登录凭证已刷新,请重试',
|
||
45011 => '操作过于频繁,请稍后再试',
|
||
];
|
||
return ['error' => isset($hint[$ec]) ? $hint[$ec] : '获取微信手机号失败,请重试', '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];
|
||
}
|
||
|
||
/**
|
||
* 师傅端:按 openid 落库(fa_master + fa_master_wechat),幂等
|
||
* @return array ['master_id' => int, 'is_new' => 0|1]
|
||
*/
|
||
public static function provisionMaster($openid, $unionid = '', $sessionKey = '', $nickname = '', $avatar = '')
|
||
{
|
||
$openid = (string)$openid;
|
||
$bind = Db::name('master_wechat')->where('openid', $openid)->find();
|
||
$masterId = $bind ? (int)$bind['master_id'] : 0;
|
||
|
||
if ($masterId > 0 && !Db::name('master')->where('id', $masterId)->find()) {
|
||
$masterId = 0;
|
||
}
|
||
|
||
$now = time();
|
||
$isNew = 0;
|
||
if ($masterId === 0) {
|
||
$isNew = 1;
|
||
$masterId = (int)Db::name('master')->insertGetId([
|
||
'mobile' => null,
|
||
'nickname' => $nickname !== '' ? mb_substr($nickname, 0, 20) : ('师傅' . substr($openid, -4)),
|
||
'realname' => '',
|
||
'avatar' => $avatar,
|
||
'verify_status' => 'draft',
|
||
'work_status' => 'off',
|
||
'status' => 'normal',
|
||
'level' => 1,
|
||
'score' => 5.00,
|
||
'accept_rate' => 100.00,
|
||
'ontime_rate' => 100.00,
|
||
'serve_radius' => 10,
|
||
'money' => 0.00,
|
||
'frozen_money' => 0.00,
|
||
'createtime' => $now,
|
||
'updatetime' => $now,
|
||
]);
|
||
MasterSecurity::ensure($masterId);
|
||
}
|
||
|
||
$data = [
|
||
'master_id' => $masterId,
|
||
'openid' => $openid,
|
||
'unionid' => (string)$unionid,
|
||
'session_key' => (string)$sessionKey,
|
||
'updatetime' => $now,
|
||
];
|
||
if ($nickname !== '') {
|
||
$data['nickname'] = mb_substr($nickname, 0, 64);
|
||
}
|
||
if ($avatar !== '') {
|
||
$data['avatar'] = $avatar;
|
||
}
|
||
|
||
if ($bind) {
|
||
Db::name('master_wechat')->where('id', $bind['id'])->update($data);
|
||
} else {
|
||
$data['createtime'] = $now;
|
||
Db::name('master_wechat')->insert($data);
|
||
}
|
||
|
||
$masterUpdate = ['updatetime' => $now];
|
||
if ($nickname !== '') {
|
||
$masterUpdate['nickname'] = mb_substr($nickname, 0, 20);
|
||
}
|
||
if ($avatar !== '') {
|
||
$masterUpdate['avatar'] = $avatar;
|
||
}
|
||
Db::name('master')->where('id', $masterId)->update($masterUpdate);
|
||
|
||
return ['master_id' => $masterId, 'is_new' => $isNew];
|
||
}
|
||
|
||
/**
|
||
* 师傅端:按手机号结合 openid 注册或登录独立师傅账号(fa_master + fa_master_wechat,幂等合并)
|
||
* @return array ['master_id' => int, 'is_new' => 0|1]
|
||
*/
|
||
public static function provisionMasterWithMobile($mobile, $openid = '', $unionid = '', $sessionKey = '')
|
||
{
|
||
$mobile = trim((string)$mobile);
|
||
$openid = trim((string)$openid);
|
||
$masterId = 0;
|
||
$isNew = 0;
|
||
$now = time();
|
||
|
||
// 1. 优先按手机号匹配已存在师傅账号
|
||
$existMaster = Db::name('master')->where('mobile', $mobile)->find();
|
||
if ($existMaster) {
|
||
$masterId = (int)$existMaster['id'];
|
||
}
|
||
|
||
// 2. 若手机号未查到,但有 openid,检查 fa_master_wechat 是否已绑定师傅
|
||
if ($masterId === 0 && $openid !== '') {
|
||
$bind = Db::name('master_wechat')->where('openid', $openid)->find();
|
||
if ($bind && Db::name('master')->where('id', $bind['master_id'])->find()) {
|
||
$masterId = (int)$bind['master_id'];
|
||
Db::name('master')->where('id', $masterId)->update(['mobile' => $mobile, 'updatetime' => $now]);
|
||
}
|
||
}
|
||
|
||
// 3. 师傅账号完全不存在,新建独立师傅账号(状态 draft,需提交实名入驻审核)
|
||
if ($masterId === 0) {
|
||
$isNew = 1;
|
||
$masterId = (int)Db::name('master')->insertGetId([
|
||
'mobile' => $mobile,
|
||
'nickname' => '师傅' . substr($mobile, -4),
|
||
'realname' => '',
|
||
'avatar' => '',
|
||
'verify_status' => 'draft',
|
||
'work_status' => 'off',
|
||
'status' => 'normal',
|
||
'level' => 1,
|
||
'score' => 5.00,
|
||
'accept_rate' => 100.00,
|
||
'ontime_rate' => 100.00,
|
||
'serve_radius' => 10,
|
||
'money' => 0.00,
|
||
'frozen_money' => 0.00,
|
||
'createtime' => $now,
|
||
'updatetime' => $now,
|
||
]);
|
||
}
|
||
|
||
MasterSecurity::ensure($masterId);
|
||
|
||
// 4. 若有 openid,建立或更新 fa_master_wechat 关联
|
||
if ($openid !== '') {
|
||
$bind = Db::name('master_wechat')->where('openid', $openid)->find();
|
||
$bindData = [
|
||
'master_id' => $masterId,
|
||
'openid' => $openid,
|
||
'unionid' => (string)$unionid,
|
||
'session_key' => (string)$sessionKey,
|
||
'updatetime' => $now,
|
||
];
|
||
if ($bind) {
|
||
Db::name('master_wechat')->where('id', $bind['id'])->update($bindData);
|
||
} else {
|
||
$bindData['createtime'] = $now;
|
||
Db::name('master_wechat')->insert($bindData);
|
||
}
|
||
}
|
||
|
||
return ['master_id' => $masterId, 'is_new' => $isNew];
|
||
}
|
||
|
||
}
|