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

Google Sheets API 404错误:Requested Entity Was Not Found问题求助

问题:Google Sheets API PHP调用返回404 "Requested entity was not found."

我从未使用过Google API及类似服务,刚接触PHP。现在尝试通过Google Sheets API读取电子表格并打印内容,代码看似无误,但运行时出现如下错误:

PHP Fatal error:  Uncaught Google\Service\Exception: {
  "error": {
    "code": 404,
    "message": "Requested entity was not found.",
    "errors": [
      {
        "message": "Requested entity was not found.",
        "domain": "global",
        "reason": "notFound"
      }
    ],
    "status": "NOT_FOUND"
  }
}

我的PHP代码如下:

require __DIR__ . '/vendor/autoload.php';

$client = new \Google_Client();
$client->setApplicationName('Sheets Test');
$client->setScopes([\Google_Service_Sheets::SPREADSHEETS]);
$client->setAccessType('offline');
$client->setAuthConfig(__DIR__ . '/credentials.json');
$service = new \Google_Service_Sheets($client);
$spreadsheetId = "1sefMmSCVnQRMVFuG8l5SKx7phpD2vvmwzq7opsgyuebYIU";
$range = "currentRatings!A2:C4";
$response = $service->spreadsheets_values->get($spreadsheetId, $range);
$values = $response->getValues();
if(empty($values)){
    print "No data found. \n";
} else {
     $mask = "%10s %-10s $s\n";
     foreach($values as $row){
        echo sprintf($mask, $row[2], $row[1], $row[0]);
    }
} 

如上述代码所示,我已连接credentials.json文件,对应的服务账号已被共享至目标表格。问题出在$response = $service->spreadsheets_values->get($spreadsheetId, $range);这一行。

我已尝试以下方法:

  • 反复核对表格ID
  • 通过Composer降级Google API版本
  • 修改$range参数(即使修改为错误的工作表名称也无变化)
  • 在Google控制台创建新的服务账号
  • 确认目标表格已共享给服务账号

恳请帮忙解决该问题。


解决方案

  1. 修正Spreadsheet ID
    你提供的spreadsheetId长度异常,正常Google Sheets的ID是20-40位字符。直接从浏览器地址栏提取:地址格式为https://docs.google.com/spreadsheets/d/[SPREADSHEET_ID]/edit,取/d/和/edit之间的字符串。

  2. 确认服务账号权限与共享状态
    从credentials.json中找到client_email字段对应的邮箱,确保该邮箱已被添加为目标表格的协作者(至少拥有查看权限),且共享操作已生效(部分情况下会有1-2分钟延迟)。

  3. 检查Google Sheets API是否启用
    登录Google Cloud控制台,进入你的项目,依次点击左侧菜单「APIs & Services」→「Library」,搜索「Google Sheets API」,确认其状态为「已启用」。

  4. 修复代码语法错误
    代码中$mask = "%10s %-10s $s\n";存在语法错误,$s应改为%s,否则会导致sprintf调用失败,修正后:

    $mask = "%10s %-10s %s\n";
    
  5. 验证认证有效性
    添加代码验证客户端是否成功获取访问令牌,确保credentials.json路径正确且文件有效:

    if ($client->isAccessTokenExpired()) {
        $client->fetchAccessTokenWithAssertion();
    }
    var_dump($client->getAccessToken()); // 查看是否返回有效令牌数据
    

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.21 10:11:15