文件
yjyf/server/application/common/library/WxLogin.php
YuanWen c01e8fc7d9 feat: 新增大量服务类图标及相关接口配置
- 新增20+家电维修类图标(电视、空调、冰箱等)
- 新增短信发送、微信手机号登录接口
- 新增服务规格查询接口
- 更新后台配置与菜单结构
- 移除支付插件相关配置
2026-11-03 11:19:24 +08:00

246 行
8.9 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 = \think\Env::get('wechat.appid');
$secret = \think\Env::get('wechat.secret');
if (!$appid || !$secret) {
return ['error' => '微信登录未配置'];
}
$url = 'https://api.weixin.qq.com/sns/jscode2session?appid=' . $appid
. '&secret=' . $secret
. '&js_code=' . urlencode($code)
. '&grant_type=authorization_code';
$ctx = stream_context_create(['http' => ['timeout' => 8, 'ignore_errors' => true]]);
$resp = @file_get_contents($url, false, $ctx);
if ($resp === false) {
return ['error' => '微信服务不可达,请稍后重试'];
}
$wx = json_decode($resp, true);
if (empty($wx['openid'])) {
$ec = isset($wx['errcode']) ? (int)$wx['errcode'] : 0;
$em = isset($wx['errmsg']) ? $wx['errmsg'] : '未知错误';
$hint = [
40029 => '小程序 appid 与服务端配置不一致:请确认 manifest.json 的 mp-weixin.appid 为 ' . $appid,
40125 => 'appsecret 配置错误,请检查 .env 的 [wechat] secret',
45011 => '登录请求过于频繁,请稍后重试',
40226 => '该微信账号被风控限制,请稍后再试',
];
$msg = isset($hint[$ec]) ? $hint[$ec] : ('微信登录失败(' . $ec . '):' . $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];
}
}