thinkphp8.1 调用巨量广告API接口,刷新token
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 GuzzleHttp\Psr7\Request;
use DateTime;class Index
{protected string $accessToken;public function __construct(){$data = Db::name('sys_token')->find(1);$expired_time = $data['expires_in']; // accessToken的过期时间$result = (new DateTime() > new DateTime($expired_time) ? 1 : 0);if ($result===1) {$this->getRefreshToken($data['refresh_token']); // 过期了刷新令牌} else {$this->accessToken = $data['access_token'];}}public function index(){// 在调用任意接口时,需要有访问令牌;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);return json(['code'=>0, 'msg'=>'刷新token成功']);} catch (RequestException $e) {// 错误处理return json(['code'=>1, 'msg'=>$e->getMessage()]);}}
}
测试环境:centOS stream 9、php8.3、thinkphp8.1; 欢迎大家指正........