thinkphp8.1 调用巨量广告API接口,刷新token

1、在mysql中建立表sys_token;

sql 复制代码
CREATE TABLE `sys_token` (
  `id` int UNSIGNED NOT NULL,
  `access_token` varchar(50) COLLATE utf8mb4_general_ci NOT NULL,
  `expires_in` datetime NOT NULL,
  `refresh_token` varchar(50) COLLATE utf8mb4_general_ci NOT NULL,
  `refresh_token_expires_in` datetime NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci COMMENT='API token';

备注:expires_in\refresh_token_expires_in 巨量引擎返回的是纯数字,单位:秒,需要你在tp里转换成年月日时分秒;在数据库里存储时,一定要用datetime类型;否则会很麻烦的;

2、第一次获取令牌时,官方会给你auth_code,你根据你的app_id,secret,auth_code获取令牌,并存入database中;

3、由于令牌的有效期是1天,刷新令牌有效期是30天;令牌过期了需要刷新令牌;

php 复制代码
use think\response\Json;
use think\facade\Db;
use GuzzleHttp\Client;
use GuzzleHttp\Exception\RequestException;
use DateTime;
use DateInterval;

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);
            
            $expires_in_seconds = $result['data']['expires_in'];  // expires_in = 86052 秒
            $refresh_token_expires_in_seconds = $result['data']['refresh_token_expires_in'];  // refresh_token_expires_in = 2591652 秒
            
            // 获取当前时间并加上秒数
            $expires_in_formatted = (new DateTime())->add(new DateInterval("PT{$expires_in_seconds}S"))->format('Y-m-d H:i:s');
            $refresh_token_expires_in_formatted = (new DateTime())->add(new DateInterval("PT{$refresh_token_expires_in_seconds}S"))->format('Y-m-d H:i:s');
            $data = [
                'id'=>1,
                'access_token' => $result['data']['access_token'],
                'expires_in' => $expires_in_formatted,
                'refresh_token' => $result['data']['refresh_token'],
                'refresh_token_expires_in' => $refresh_token_expires_in_formatted
            ];
            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; 欢迎大家指正........

相关推荐
xmode16 天前
常用自定义函数laravel版+thinkphp版
后端·php·laravel·thinkphp
mooyuan天天17 天前
内网渗透之Thinkphp5提权实战+reGeorg代理横向移动(CVE-2018-20062)
内网渗透·横向移动·thinkphp·regeorg·cve-2018-20062·thinkphp代码执行漏洞
蹦极的考拉19 天前
夜间无法登录:ThinkPHP api接口 23:00 准时罢工的排查全纪录
小程序·thinkphp·api接口·无法登陆
青茶36019 天前
ThinkCMF是一个开源的内容管理框架
php·cms·thinkphp
quweiie20 天前
thinkphp8.0链接SQL SERVER2022数据库
数据库·sqlserver·thinkphp
ghie90901 个月前
基于ThinkPHP实现动态ZIP压缩包的生成
thinkphp
用户3074596982071 个月前
容器(Container)—— 对象的“智能工厂+调度官”
后端·thinkphp
非凡的世界2 个月前
ThinkPHP6 集成TCP长连接 GatewayWorker
网络·网络协议·tcp/ip·gateway·thinkphp·worker·workman
王阿觉2 个月前
ThinkPHP8 配置 Swagger
thinkphp
非凡的世界2 个月前
Thinkphp8 Redis队列与消息队列topthink/think-queue 原创
数据库·redis·bootstrap·thinkphp