12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697 |
- <?php
- namespace app\common;
- use Firebase\JWT\JWT;
- use think\Exception;
- class Token
- {
- private static $key = '@#$%^&*!';
- /**
- * @param $user
- * @return array
- */
- public static function getToken($user)
- {
- $accessToken = self::createAccessToken($user);
- $refreshToken = self::createRefreshToken($user);
- return [
- 'access_token' => $accessToken,
- 'refresh_token' => $refreshToken
- ];
- }
- /**
- * @param $user
- * @return string[]
- */
- public static function getClientToken($user)
- {
- $accessToken = self::createAccessToken($user);
- return [
- 'access_token' => $accessToken,
- ];
- }
- /**
- * 刷新token
- * @return string[]
- * @throws Exception
- * @throws \think\db\exception\DataNotFoundException
- * @throws \think\db\exception\DbException
- * @throws \think\db\exception\ModelNotFoundException
- */
- public static function refreshToken($user)
- {
- $accessToken = self::createAccessToken($user);
- return [
- 'access_token' => $accessToken,
- ];
- }
- /**
- * 创建token
- * @param $user
- * @return string
- */
- private static function createAccessToken($user)
- {
- $payload = [
- 'iss' => 'tp6', //签发者
- 'iat' => time(), //什么时候签发的
- 'exp' => time() + 7200, //过期时间
- 'user' => $user,
- ];
- $token = JWT::encode($payload, self::$key);
- return $token;
- }
- /**
- * 创建刷新token
- * @param $user
- * @return string
- */
- private static function createRefreshToken($user)
- {
- $payload = [
- 'iss' => 'tp6', //签发者
- 'iat' => time(), //什么时候签发的
- 'user' => $user,
- ];
- $token = JWT::encode($payload, self::$key);
- return $token;
- }
- /**
- * 根据token获取用户信息
- * @param $token
- * @return mixed|string
- */
- public static function getTokenValue($token)
- {
- $secretKey = self::$key;
- $jwt = (array)JWT::decode($token, $secretKey, ['HS256']);
- return $jwt['user']??'';
- }
- }
|