ufutx.love.util/app/Helpers/TokenHelper.php
2026-04-27 11:26:49 +08:00

99 lines
2.5 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\Helpers;
use Log;
class TokenHelper
{
private static $secret = 'ufutx_love_util';
/**
* 生成 token
* @param int $userId 用户ID
* @param int $expiresIn 过期时间(分钟)
* @return string
*/
public static function generate($userId, $expiresIn = 60)
{
$now = time();
$expires = $now + ($expiresIn * 60);
$payload = [
'user_id' => $userId,
'iat' => $now,
'exp' => $expires
];
// 使用更简单的方式base64 编码(避免版本兼容问题)
$encoded = base64_encode(json_encode($payload));
// 添加签名
$signature = hash_hmac('sha256', $encoded, self::$secret);
return $encoded . '.' . $signature;
}
/**
* 验证 token
* @return array|false
*/
public static function verify($tokenString)
{
try {
Log::info("token: " . $tokenString);
$parts = explode('.', $tokenString);
if (count($parts) != 2) {
Log::error("验证失败token无效");
return false;
}
list($payloadEncoded, $signature) = $parts;
// 验证签名
$expectedSignature = hash_hmac('sha256', $payloadEncoded, self::$secret);
if (!hash_equals($expectedSignature, $signature)) {
Log::error("验证失败,签名错误");
return false;
}
// 解码 payload
$payload = json_decode(base64_decode($payloadEncoded), true);
if (!$payload) {
Log::error("验证失败,解码错误");
return false;
}
// 检查是否过期
$now = time();
if (isset($payload['exp']) && $payload['exp'] < $now) {
Log::error("验证失败,已过期");
return false;
}
Log::info("验证成功");
return [
'user_id' => $payload['user_id'],
'expires_at' => $payload['exp']
];
} catch (\Exception $e) {
Log::error("验证失败,代码错误");
return false;
}
}
/**
* 刷新 token
*/
public static function refresh($oldToken, $expiresIn = 60)
{
$payload = self::verify($oldToken);
if (!$payload) {
return false;
}
return self::generate($payload['user_id'], $expiresIn);
}
}