如何修复更新 Google 电子表格时的错误

How can I fix an error on update Google spreadsheet

我在 PHP 框架上使用 Google Sheet Api,更新 sheet 时遇到错误。

Fatal error: Uncaught Google_Service_Exception: {
  "error": {
    "code": 403,
    "message": "Request had insufficient authentication scopes.",
    "errors": [
      {
        "message": "Request had insufficient authentication scopes.",
        "domain": "global",
        "reason": "forbidden"
      }
    ],
    "status": "PERMISSION_DENIED"
  }

我该如何解决?

function add($spreadsheetId, $range, $value, $service){
    $result = $service->spreadsheets_values->get($spreadsheetId, $range);
    $numRows = $result->getValues() != null ? count($result->getValues()) : 0;
    printf("%d rows retrieved.", $numRows);
    $body = new Google_Service_Sheets_ValueRange([
        'values' => [$value]
    ]);
    $end = chr(65 + count($value) - 1);
    $range = $range."!A".($numRows + 1).":".$end;//ex:Sheet!A6:H
    printf("%s\n", $range);
    $result = $service->spreadsheets_values->update($spreadsheetId, $range, $body, ['valueInputOption' => 'USER_ENTERED']);
    printf("%d cells added.\n", $result->getUpdatedCells());
}

我也遇到过这样的错误。 我通过再次下载 credential.json 文件解决了这个问题。 此外,请检查 spreadsheetId 是否正确或写了 $client->setScopes(Google_Service_Sheets::SPREADSHEETS);在创建服务之前。