jwtKey = env('app.jwt_key','Rn4zNAX9e3li5dfI6mBuWLvbacTZqUr3'); } public function getToken(int $userId,string $visitor = '') { $payload = [ "iat" => time(), "exp" => time() + (3600 * 24 * 7), "userId" => $userId, "visitor"=> $visitor ]; $token = JWT::encode($payload, $this->jwtKey); return $token; } public function decodeToken(): array { $token = request()->header('token') ?: request()->get('token'); if (empty($token)) { throw new ApiException('token不能为空'); } try { $decoded = JWT::decode($token, $this->jwtKey, ['HS256']); } catch (ExpiredException $e) { throw new TokenException('token到期,请刷新'); } catch (\Exception $e) { throw new ApiException('token无效' . $e->getMessage()); } $tokenInfo = (array)$decoded; if (time() - $tokenInfo['exp'] > 3600) { $GLOBALS['refreshToken'] = $this->getToken($tokenInfo['usrId']); } return (array)$decoded; } }