1、安装 composer require firebase/php-jwt 2、封装(在框架根目录extend下新建Token.php) 复制代码 <?php use Firebase\JWT\JWT; class Token { const SECRET = 'hello';//密钥 //创建token static public function create_token($uid = 1) { $payload = [ 'iss' => 'pyg', //签发人(官方字段:非必需) 'exp' => time() + 60, //过期时间(官方字段:非必需) 'aud' => 'admin', //接收人(官方字段:非必需) 'nbf' => time(), //生效时间(官方字段:非必需) 'iat' => time(), //签发时间(官方字段:非必需) 'admin_id' => $uid, //自定义字段(用户id) ]; $token = JWT::encode($payload, self::SECRET, 'HS256'); return $token; } //验证token static public function verify_token($token) { try { $Result = JWT::decode($token, self::SECRET, ['HS256']); return true; } catch (\Exception $e) { return false; } } } 复制代码 3、调用(参考) 复制代码 <?php namespace app\api\controller; use think\Controller; use think\Request; use Token; class Login extends Controller { public function login(){ //登录成功生成token $user_id = 2; $token = Token::create_token($user_id); return $token; } public function verifyToken(){ $token = input('token'); $res = Token::verify_token($token); var_dump($res); } }