JwtService.php 1.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  1. <?php
  2. namespace App\Services;
  3. use Firebase\JWT\JWT;
  4. use Firebase\JWT\Key;
  5. /**
  6. * JWT服务管理-服务类
  7. * @author laravel开发员
  8. * @since 2020/11/11
  9. * @package App\Services
  10. */
  11. class JwtService extends BaseService
  12. {
  13. protected static $instance = null;
  14. protected $alg = 'HS256';
  15. /**
  16. * 静态入口
  17. */
  18. public static function make(){
  19. if(!self::$instance){
  20. self::$instance = new static();
  21. }
  22. return self::$instance;
  23. }
  24. public function encode($data, $iss='',$ttl=0)
  25. {
  26. $jwtTtl = env('JWT_TTL',3600);
  27. $jwtTtl = $jwtTtl>0?$jwtTtl:3600;
  28. $payload = array(
  29. "iss" => $iss,
  30. "aud" => '',
  31. "iat" => time(),
  32. "nbf" => time(),
  33. "exp" => time() + intval($ttl>0?$ttl:$jwtTtl), // 有效期
  34. "data" => $data
  35. );
  36. return JWT::encode($payload, env('JWT_KEY'), $this->alg);
  37. }
  38. public function verifyToken($token)
  39. {
  40. try {
  41. $payload = JWT::decode($token, new Key(env('JWT_KEY'), $this->alg));
  42. if(empty($payload)){
  43. $this->error = 'TOKEN无效';
  44. return false;
  45. }
  46. if($payload->exp<=time()){
  47. $this->error = 'TOKEN已过期';
  48. return false;
  49. }
  50. return $payload->data;
  51. } catch (\Exception $exception){
  52. $this->error = $exception->getMessage();
  53. return false;
  54. }
  55. }
  56. }