header('appid'); if (!$appid) { return $this->error('appid参数缺失'); } $agent = Agent::query()->firstWhere('appid', $appid); //代理商数据 if (!$agent) { return $this->error('找不到该appid相关记录'); } $code = request()->input('code'); if (!$code) { return $this->error('code参数缺失'); } $config = config('wechat.mini_program.default'); $config = array_merge($config, [ 'app_id' => $agent['appid'], 'secret' => $agent['appsecret'], ]); $app = Factory::miniProgram($config); try { $res = $app->auth->session($code); if (!empty($res['errcode']) || empty($res['openid']) && empty($res['unionid'])) { $msg = $res['errmsg'] ?? '登录失败'; return $this->error($msg); } if (empty($res['session_key'])) { $this->error('获取session_key失败'); } } catch (InvalidConfigException $e) { return $this->error($e->getMessage()); } // TODO 登录部分待优化 $userModel = User::firstOrCreate([ 'openid' => $res['openid'] ?? '', 'unionid' => $res['unionid'] ?? '', 'agent_id' => $agent->id, ], [ //'nickname' => uniqid(), 根据前端判断,不设置默认值 //'avatar' => '/static/images/avatar.png' ]); //保存session_key Cache::put('session_key_' . $userModel->id, $res['session_key']); //TODO 存入初始化数据 user_channel $token_key = md5($userModel->id . env('APP_KEY')); Cache::put($token_key, $userModel->id); // 测试代码结束 $userModel->token = $token_key; return $this->success($userModel); } }