..,'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]; } }