wechat_auth_url . '?' . http_build_query([ 'appid' => $this->appid, 'secret' => $this->secret, 'js_code' => $code, 'grant_type' => 'authorization_code' ]); $result = Curl::get($url); $res = $this->userExternalService->wechatNewUser($result['data']['openid']); if (!$res['code'] !== 200) { throw new BusinessException($res['code'], $res['msg']); } if (empty($res['data']['user'])) { throw new BusinessException(AuthErrorCode::CODE_TO_AUTH_FAIL); } return $this->getToken($res['data']['user']['user_id'], $res['data']['user']['user_nickname'], $res['data']['user']['user_openid']); } /** * 获取JWT认证token * * @param int $user_id * @param string $nickname * @param string $openid * @return array */ public function getToken(int $user_id, string $nickname, string $openid) { try { $token = $this->jwt->getToken('default', [ 'user_id' => $user_id, 'nickname' => $nickname, 'openid' => $openid ]); } catch (InvalidArgumentException) { // TODO 记录日志 throw new BusinessException(AuthErrorCode::CODE_TO_AUTH_FAIL); } return [ 'token' => $token->toString(), 'exp' => $this->jwt->getTTL($token->toString()) ]; } /** * 刷新token * * @return array */ public function refreshToken() : array { try { $token = $this->jwt->refreshToken(); } catch (InvalidArgumentException) { // TODO 记录日志 throw new BusinessException(AuthErrorCode::CODE_TO_AUTH_FAIL); } return [ 'token' => $token->toString(), 'exp' => $this->jwt->getTTL($token->toString()) ]; } }