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

如何调试PHP版Google API客户端库的ACCESS_TOKEN_SCOPE_INSUFFICIENT错误

问题:Google翻译API突然返回403 "Request had insufficient authentication scopes"错误

我们采用服务账号认证方式使用PHP版Google APIs客户端库,代码如下:

putenv('GOOGLE_APPLICATION_CREDENTIALS=' . $google_api_key_file_path);
$client = new Google_Client();
$client->setApplicationName('Google Translate API');
$client->useApplicationDefaultCredentials();
$client->addScope(Google_Service_Translate::CLOUD_TRANSLATION);
$service = new Google_Service_Translate($client);
$projects = $service->projects;
$postbody = new Google_Service_Translate_TranslateTextRequest();
$postbody->setContents($contents);
$postbody->setSourceLanguageCode($source_lang);
$postbody->setTargetLanguageCode($target_lang);
$result = $projects->translateText('projects/myproject', $postbody)->translations;

这段代码此前运行正常,但约一个月前开始返回如下错误:

{ "error": { "code": 403, "message": "Request had insufficient authentication scopes.", "errors": [ { "message": "Insufficient Permission", "domain": "global", "reason": "insufficientPermissions" } ], "status": "PERMISSION_DENIED", "details": [ { "@type": "type.googleapis.com/google.rpc.ErrorInfo", "reason": "ACCESS_TOKEN_SCOPE_INSUFFICIENT", "domain": "googleapis.com", "metadata": { "service": "translate.googleapis.com", "method": "google.cloud.translation.v3.TranslationService.TranslateText" } } ] } }

已知情况:

  • 代码及谷歌账号设置均未变更
  • 翻译API已启用
  • 同一服务账号可正常调用其他Google API
  • 已尝试禁用并重新启用翻译API

回答

问题根源

你调用的是翻译API v3的TranslateText方法,但当前代码中使用的Google_Service_Translate::CLOUD_TRANSLATION权限范围存在版本不匹配,或是客户端库版本过旧导致scope常量未正确适配v3 API的权限校验逻辑。

解决方案

  1. 升级Google API PHP客户端库
    执行Composer命令更新到最新版本:

    composer update google/apiclient
    

    旧版本库可能未正确映射v3 API所需的权限范围,升级后通常能自动修复常量匹配问题。

  2. 直接指定v3 API的权限范围
    如果升级库后问题仍存在,替换代码中的scope常量为v3 API的官方权限范围值:

    // 替换原有的addScope行
    $client->addScope('https://www.googleapis.com/auth/cloud-translation');
    
  3. 校验服务账号IAM权限
    登录Google Cloud控制台,检查该服务账号是否拥有roles/cloudtranslate.user或更高权限(如roles/cloudtranslate.admin)。即使服务账号能调用其他API,翻译API v3的权限可能需要单独配置。

补充说明

近期Google可能收紧了API权限范围的校验逻辑,原本兼容v2/v3的scope常量在新版本校验中出现不匹配,导致原本正常的代码触发权限错误。升级库或直接指定正确scope是最直接的修复方式。


内容的提问来源于stack exchange,提问作者Achille D'Aniello

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.07 02:57:40