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'])) { return $this->error('获取session_key失败'); } } catch (InvalidConfigException $e) { return $this->error($e->getMessage()); } // TODO 登录部分待优化 $userModel = User::query()->firstOrCreate([ 'openid' => $res['openid'] ?? '', 'agent_id' => $agent->id, ], [ 'unionid' => $res['unionid'] ?? '', ]); //保存session_key Cache::put('session_key_' . $userModel->id, $res['session_key']); //如果是新增,插入初始数据 if ($userModel->wasRecentlyCreated) { $channel_ids = UserChannel::where('user_id', $userModel->id)->first(); //如果不存在则存入初始数据 if (!$channel_ids) { $channel_ids = Channel::where([ ['agent_id', '=', $this->agent_id], ['pid', '<>', 0], ]) ->orderBy('id') ->limit(8) ->pluck('id') ->toArray(); //存入user_channel UserChannel::where('user_id', $userModel->id) ->insert([ 'user_id' => $userModel->id, 'channels' => json_encode($channel_ids) ]); } } $token_key = md5($userModel->id . env('APP_KEY')); Cache::put($token_key, $userModel->id); // 测试代码结束 $userModel->token = $token_key; return $this->success($userModel); } }