header('appid'); if (!$appid) { return $this->error('appid缺失'); } $agent_id = Agent::where('appid', $appid)->value('id'); if (!$agent_id) { return $this->error('appid无效'); } $code = request()->input('code'); if (!$code) { return $this->error('Invalid code!'); } $agent = Agent::select(['id', 'appid', 'appsecret'])->find($agent_id); //代理商数据 $config = config('wechat.mini_program.default'); $config = array_merge($config, [ 'app_id' => $agent['appid'], 'secret' => $agent['appsecret'], ]); $app = Factory::miniProgram($config); $res = $app->auth->session($code); if (!isset($res['errcode']) || $res['errcode'] != 0 || empty($res['openid']) || empty($res['unionid'])) { $msg = $res['errcode'] ? $res['errcode'] . ': ' : ''; $msg .= $res['errmsg'] ?? '登录失败'; return $this->error($msg); } // TODO 登录部分待优化 $userModel = new User(); $userModel->firstOrCreate([ 'openid' => $res['openid'], 'unionid' => $res['unionid'], 'agent_id' => $agent_id ], [ 'nickname' => '未设置昵称', 'avatar' => '/static/images/avatar.png' ]); //保存session_key Cache::put('session_key_' . $userModel->id, $res['session_key']); // TODO 用于测试 $token_key = md5($userModel->id); Cache::put($token_key, 1); Cache::put($agent['appid'], $agent['id']); // 测试代码结束 return $this->success(['token' => md5($userModel->id)]); } }