setChannel('genera'); } /** * 小程序登录 * @throws GeneralException */ public function login(string $code): array { $session_info = $this->miniProgramLogin($code); $token_info = $this->userLogin($session_info['open_id'], $session_info['session_key']); Redis::setex($token_info['access_token'], 86400 * 7, json_encode($session_info, JSON_UNESCAPED_UNICODE)); return $token_info; } /** * 用户登录 * @param string $open_id * @param string $session_key * @return array */ protected function userLogin(string $open_id, string $session_key): array { $user = User::firstOrCreate([ 'email' => $open_id ], [ 'name' => $open_id, 'password' => bcrypt($open_id) ]); // 撤销之前正在使用的所有token $user->tokens()->delete(); // 获取新token $expire_time = Carbon::now()->addDays(7); $token_str = $user->createToken(bcrypt($session_key), ['*'], $expire_time)->plainTextToken; [$id, $token] = explode('|', $token_str, 2); return [ 'access_token' => $token ?: '', 'token_type' => 'Bearer', ]; } /** * 小程序登录 * @param string $code * @return array * @throws GeneralException */ protected function miniProgramLogin(string $code): array { try { $mini = getWeChatMiniProgramApp(); $response = $mini->getUtils()->codeToSession($code); return [ 'open_id' => $response['openid'], 'session_key' => $response['session_key'], 'union_id' => $response['unionid'] ?? '' ]; } catch (HttpExceptionInterface|ExceptionInterface|Exception $e) { //service error $message = $e->getMessage() . ' in ' . $e->getFile() . ':' . $e->getLine(); $this->error('授权登录接口报错', [$message]); throw new GeneralException('授权登录失败,请稍后再试!', Response::HTTP_BAD_REQUEST); } } }