You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Google Drive API PHP项目免重复手动认证的access token自动化方案咨询

解决方案

问题根源

导致每24小时需要重新认证的核心原因有两个:

  1. 现有代码缺少access token过期后自动用refresh token刷新的逻辑,access token默认有效期只有1小时,过期后没有自动续期就会触发重新认证要求
  2. 若你的Google Cloud项目OAuth同意屏幕处于「测试」状态,refresh token默认7天就会过期,需要调整为正式发布状态才能拿到长期有效的refresh token

操作步骤

1. 调整Google Cloud配置

  • 打开Google Cloud控制台进入对应项目,依次点击「API和服务」→「OAuth同意屏幕」
  • 将应用发布状态从「测试」修改为「正式发布」,无需提交官方审核,个人使用场景改完即刻生效

2. 新增自动刷新token逻辑

你可以把Google客户端初始化逻辑抽为公共函数,所有需要调用Drive API的地方统一调用,自动处理token过期刷新:

function getClient() {
    $client = new Google_Client();
    $client->setApplicationName('Google Drive API PHP Quickstart');
    $client->setScopes(Google_Service_Drive::DRIVE);
    $client->setAuthConfig('credentials.json');
    $client->setAccessType('offline');
    $client->setPrompt('select_account consent');

    $tokenPath = 'token.json';
    // 读取已保存的全量token信息
    if (file_exists($tokenPath)) {
        $accessToken = json_decode(file_get_contents($tokenPath), true);
        $client->setAccessToken($accessToken);
    }

    // 检测access token是否过期
    if ($client->isAccessTokenExpired()) {
        // 存在refresh token则直接刷新获取新的access token
        if ($refreshToken = $client->getRefreshToken()) {
            $newToken = $client->fetchAccessTokenWithRefreshToken($refreshToken);
            // 刷新接口返回的新token默认不带refresh token,需要合并原有refresh token
            if (!isset($newToken['refresh_token'])) {
                $newToken['refresh_token'] = $accessToken['refresh_token'];
            }
            $client->setAccessToken($newToken);
            // 将新的token信息写入文件持久化
            file_put_contents($tokenPath, json_encode($newToken));
        } else {
            // 仅当refresh token失效时才需要重新走手动认证流程
            throw new Exception('Refresh token失效,请重新进行身份认证');
        }
    }
    return $client;
}

3. 现有代码适配

  • 保留refreshtoken.php作为首次手动认证入口,第一次部署时访问该文件完成授权后会生成保存全量token的token.json文件
  • 后续所有调用Drive API的场景,直接调用上述getClient()函数获取已认证的客户端实例即可,无需再重复走认证流程
  • callback.php中的重复Google客户端初始化逻辑可以替换为调用getClient()函数,减少冗余代码

注意事项

  • token.json、credentials.json属于敏感文件,请勿放在web服务可公开访问的目录下,建议设置文件权限为仅所有者可读可写
  • 只要你不手动撤销应用授权、不修改应用请求的权限范围、不更换绑定的Google账号,首次认证后即可长期自动运行,无需人工干预

内容的提问来源于stack exchange,提问作者Junry Buenavista

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.28 20:48:02