| 12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364 |
- <?php
- namespace App\Services;
- use Firebase\JWT\JWT;
- use Firebase\JWT\Key;
- /**
- * JWT服务管理-服务类
- * @author laravel开发员
- * @since 2020/11/11
- * @package App\Services
- */
- class JwtService extends BaseService
- {
- protected static $instance = null;
- protected $alg = 'HS256';
- /**
- * 静态入口
- */
- public static function make(){
- if(!self::$instance){
- self::$instance = new static();
- }
- return self::$instance;
- }
- public function encode($data, $iss='',$ttl=0)
- {
- $jwtTtl = env('JWT_TTL',3600);
- $jwtTtl = $jwtTtl>0?$jwtTtl:3600;
- $payload = array(
- "iss" => $iss,
- "aud" => '',
- "iat" => time(),
- "nbf" => time(),
- "exp" => time() + intval($ttl>0?$ttl:$jwtTtl), // 有效期
- "data" => $data
- );
- return JWT::encode($payload, env('JWT_KEY'), $this->alg);
- }
- public function verifyToken($token)
- {
- try {
- $payload = JWT::decode($token, new Key(env('JWT_KEY'), $this->alg));
- if(empty($payload)){
- $this->error = 'TOKEN无效';
- return false;
- }
- if($payload->exp<=time()){
- $this->error = 'TOKEN已过期';
- return false;
- }
- return $payload->data;
- } catch (\Exception $exception){
- $this->error = $exception->getMessage();
- return false;
- }
- }
- }
|