Token.php 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697
  1. <?php
  2. namespace app\common;
  3. use Firebase\JWT\JWT;
  4. use think\Exception;
  5. class Token
  6. {
  7. private static $key = '@#$%^&*!';
  8. /**
  9. * @param $user
  10. * @return array
  11. */
  12. public static function getToken($user)
  13. {
  14. $accessToken = self::createAccessToken($user);
  15. $refreshToken = self::createRefreshToken($user);
  16. return [
  17. 'access_token' => $accessToken,
  18. 'refresh_token' => $refreshToken
  19. ];
  20. }
  21. /**
  22. * @param $user
  23. * @return string[]
  24. */
  25. public static function getClientToken($user)
  26. {
  27. $accessToken = self::createAccessToken($user);
  28. return [
  29. 'access_token' => $accessToken,
  30. ];
  31. }
  32. /**
  33. * 刷新token
  34. * @return string[]
  35. * @throws Exception
  36. * @throws \think\db\exception\DataNotFoundException
  37. * @throws \think\db\exception\DbException
  38. * @throws \think\db\exception\ModelNotFoundException
  39. */
  40. public static function refreshToken($user)
  41. {
  42. $accessToken = self::createAccessToken($user);
  43. return [
  44. 'access_token' => $accessToken,
  45. ];
  46. }
  47. /**
  48. * 创建token
  49. * @param $user
  50. * @return string
  51. */
  52. private static function createAccessToken($user)
  53. {
  54. $payload = [
  55. 'iss' => 'tp6', //签发者
  56. 'iat' => time(), //什么时候签发的
  57. 'exp' => time() + 7200, //过期时间
  58. 'user' => $user,
  59. ];
  60. $token = JWT::encode($payload, self::$key);
  61. return $token;
  62. }
  63. /**
  64. * 创建刷新token
  65. * @param $user
  66. * @return string
  67. */
  68. private static function createRefreshToken($user)
  69. {
  70. $payload = [
  71. 'iss' => 'tp6', //签发者
  72. 'iat' => time(), //什么时候签发的
  73. 'user' => $user,
  74. ];
  75. $token = JWT::encode($payload, self::$key);
  76. return $token;
  77. }
  78. /**
  79. * 根据token获取用户信息
  80. * @param $token
  81. * @return mixed|string
  82. */
  83. public static function getTokenValue($token)
  84. {
  85. $secretKey = self::$key;
  86. $jwt = (array)JWT::decode($token, $secretKey, ['HS256']);
  87. return $jwt['user']??'';
  88. }
  89. }