composer require firebase/php-jwt ~~~ <?php namespace app\service; use Firebase\JWT\JWT; use Firebase\JWT\Key; class JwtService { /** * 创建token * @param $login_id * @param $login_type * @param $exp * @param $ttl * @return string */ static function createToken($login_id,$login_type,$exp=7*24*3600,$ttl=24*3600): string { $key = getenv("TOKEN_KEY"); $payload = array( // "iss" => "http://example.org",//暂时用不到 // "aud" => "http://example.com",//暂时用不到 "iat" => time(), "nbf" => time(), "exp" => time()+$exp,//过期时间 "ttl" => time()+$exp+$ttl,//刷新时间 "login_id" => $login_id, "login_type" => $login_type, ); return JWT::encode($payload,$key,'HS256'); } /** * 解析token * @param $token * @return array */ static function analyseToken($token): array { $key = getenv("TOKEN_KEY"); $decode = JWT::decode($token, new Key($key, 'HS256')); //失效 if(time() > $decode->ttl){ return noticeMsg(300,"令牌失效"); } //过期 if(time() > $decode->exp){ $token = JwtService::createToken($decode->login_id,$decode->login_type); return noticeMsg(201,"令牌已刷新 请保存新令牌",[ 'login_id' => $decode->login_id, 'login_type' => $decode->login_type, 'token' => $token ]); } return noticeMsg(200,"success",[ 'login_id' => $decode->login_id, 'login_type' => $decode->login_type, ]); } } ~~~