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

使用Google API出现Undefined index: expires_in错误的排查与解决

错误含义

Undefined index: expires_in 是PHP数组索引未定义错误,说明Google Client库的client.php第574行尝试访问$this->token['expires_in']时,该键不存在于数组中。尽管代码里有isset($this->token['expires_in'])的判断,但实际运行仍触发错误,核心原因是你传入客户端的$accessToken数组不完整,缺少expires_in字段。

解决方案

  • 检查并重置本地凭证文件
    打开$credentialsPath指向的JSON文件,查看是否包含expires_in、access_token、refresh_token等必要字段。如果文件内容缺失、损坏或格式错误,直接删除该文件,重新运行脚本走授权流程,获取并存储完整的token。

  • 在授权流程中校验token完整性
    获取token后先做字段校验,避免存储无效数据:

    $accessToken = $client->fetchAccessTokenWithAuthCode($authCode);
    // 校验核心字段是否存在
    if (!isset($accessToken['expires_in'], $accessToken['refresh_token'], $accessToken['access_token'])) {
        die('授权失败,获取的token不完整,请检查API凭据配置');
    }
    
  • 给token数组补充默认值
    在调用setAccessToken()前,为缺失的字段设置默认值,确保数组结构合规:

    // 确保accessToken包含必要字段,缺失则设默认值
    $accessToken = array_merge([
        'expires_in' => 0,
        'created' => time()
    ], $accessToken);
    $client->setAccessToken($accessToken);
    
  • 更新Google Client库版本
    旧版本的google/apiclient可能存在逻辑漏洞,执行以下命令更新到最新稳定版:

    composer update google/apiclient
    

内容的提问来源于stack exchange,提问作者Taniya Halder

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.15 16:35:25