This commit is contained in:
szdot 2024-06-05 16:40:18 +08:00
commit 6e5ae5b545

View File

@ -14,29 +14,28 @@ class PublicController extends Controller
//初始化
public function _initialize()
{
//解构文件头里面的token
$server = isset($_SERVER) ? $_SERVER : "";
$token = isset($server['HTTP_TOKEN']) && is_string($server['HTTP_TOKEN']) ? $server['HTTP_TOKEN'] : null;
// 如果 token 不存在,可以返回错误信息
if (!$token) {
// 获取请求头中的 Token
$token = isset($_SERVER['HTTP_TOKEN']) ? $_SERVER['HTTP_TOKEN'] : null;
// 如果 token 不存在,返回错误信息
if (empty($token)) {
echo json_encode(array('status' => -1, 'msg' => 'Token 不存在或无效!'));
exit();
}
$jwtKey = C('jwtKey'); // jwt密钥
// 获取 jwt 密钥
$jwtKey = C('jwtKey');
try {
$jwt = JWT::decode($token, new Key($jwtKey, 'HS256')); // 使用密钥和 HS256 算法对 JWT 进行解码
$res_token = (array) $jwt; // 将解码后的对象转换为数组
// token过期
if (empty($res_token)) {
echo json_encode(array('status' => -1, 'msg' => '帐号认证过期!'));
exit();
}
// token检测通过 获取用户id
$this->openid = $res_token['openid'];
$this->session_key = $res_token['session_key'];
} catch (Exception $e) {
// 捕获解码过程中可能的异常,并返回错误信息
echo json_encode(array('status' => -1, 'msg' => 'Token 无效: ' . $e->getMessage()));
// 解码 JWT Token
$decoded = JWT::decode($token, new Key($jwtKey, 'HS256'));
// Token 没有过期,继续处理
$this->openid = $decoded->openid;
$this->session_key = $decoded->session_key;
} catch (\Firebase\JWT\ExpiredException $e) {
// Token 过期
echo json_encode(array('status' => -1, 'msg' => 'Token 已过期'));
exit();
} catch (\Exception $e) {
// 其他 JWT 解码错误
echo json_encode(array('status' => -1, 'msg' => 'Token 解码失败: ' . $e->getMessage()));
exit();
}
}