1、在mysql中建立表sys_token;
CREATE TABLE `sys_token` (
`id` int UNSIGNED NOT NULL,
`access_token` varchar(50) COLLATE utf8mb4_general_ci NOT NULL,
`expires_in` timestamp NOT NULL,
`refresh_token` varchar(50) COLLATE utf8mb4_general_ci NOT NULL,
`refresh_token_expires_in` timestamp NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci COMMENT='API token';
备注:expires_in\refresh_token_expires_in 巨量引擎返回的是纯数字,单位:秒,需要你在tp里转换成年月日时分秒;
2、第一次获取令牌时,官方会给你auth_code,你根据你的app_id,secret,auth_code获取令牌,并存入database中;
3、由于令牌的有效期是1天,刷新令牌有效期是30天;令牌过期了需要刷新令牌;
use think\response\Json;
use think\facade\Db;
use GuzzleHttp\Client;
use GuzzleHttp\Exception\RequestException;
use DateTime;
class Index
{
// 去掉 readonly 修饰符,因为需要在刷新 token 后修改它
protected string $accessToken;
public function __construct()
{
$data = Db::name('sys_token')->find(1);
$expired_time = $data['expires_in']; // accessToken的过期时间
$isExpired = (new DateTime() > new DateTime($expired_time)); // 判断是否过期
if ($isExpired) {
$this->getRefreshToken($data['refresh_token']); // 过期了刷新令牌
} else {
$this->accessToken = $data['access_token']; // 已存在的 accessToken
}
}
public function index(): string
{
// 在调用任意接口时,需要有访问令牌;
return $this->accessToken;
}
public function getRefreshToken(string $refreshToken): Json
{
$client = new Client();
$headers = [
'Content-Type' => 'application/json',
];
// 请求体数据
$body = [
'app_id' => '你的app_id',
'secret' => '您的secret',
'refresh_token' => $refreshToken,
];
try {
// 异步请求
$response = $client->request('POST', 'https://api.oceanengine.com/open_api/oauth2/refresh_token/', [
'headers' => $headers,
'json' => $body, // 使用 'json' 自动编码为 JSON
]);
// 获取响应体并输出
$responseBody = $response->getBody()->getContents();
$result = json_decode($responseBody, true);
$data = [
'id' => 1,
'access_token' => $result['data']['access_token'],
'expires_in' => $result['data']['expires_in'],
'refresh_token' => $result['data']['refresh_token'],
'refresh_token_expires_in' => $result['data']['refresh_token_expires_in'],
];
Db::name('sys_token')->update($data);
// 将新获取的 accessToken 更新到实例的属性中
$this->accessToken = $result['data']['access_token']; // 使用新的 accessToken
return json(['code' => 0, 'msg' => '刷新token成功']);
} catch (RequestException $e) {
// 错误处理
return json(['code' => 1, 'msg' => $e->getMessage()]);
}
}
}
测试环境:centOS stream 9、php8.3、thinkphp8.1; 欢迎大家指正........