2023-02-17 17:10:16 +08:00

60 lines
1.6 KiB
PHP
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

<?php
namespace App\Utils;
use App\Constants\HttpEnumCode;
use App\Exception\BusinessException;
use Firebase\JWT\ExpiredException;
use Firebase\JWT\Key;
use Firebase\JWT\SignatureInvalidException;
class Jwt
{
/**
* 生成jwttoken
* @param array $data 自定义数组
*/
public function encode(array $data): string
{
$time = time();
$secret = config('jwt.secret');
$expire = config('jwt.ttl');
$algo = config('jwt.algo');
$payload = [
'iss' => 'gdxz',
'iat' => $time,
'nbf' => $time,
'exp' => $time + $expire,
'userInfo' => $data,
];
// token_type:bearer
return \Firebase\JWT\JWT::encode($payload, $secret, $algo);
}
/**
* 解码jwttoken
* @param string $token token数据不卸载bearer
* @return array
*/
public function decode(string $token): array
{
$secret = config('jwt.secret');
try {
$jwt = json_decode(json_encode(\Firebase\JWT\JWT::decode($token, new Key($secret, 'HS256'))), true); // 解密jwt
} catch (SignatureInvalidException $e) {
// 签名不正确
throw new BusinessException( $e->getMessage(),HttpEnumCode::TOKEN_ERROR);
} catch (ExpiredException|\UnexpectedValueException|\InvalidArgumentException $e) {
// token过期
throw new BusinessException( $e->getMessage(),HttpEnumCode::TOKEN_EXPTIRED);
} catch (\Throwable $e) {
// 其他错误:
throw new BusinessException( $e->getMessage());
}
return $jwt;
}
}