php Google电子表格API"请求的认证范围不足"

时间:2017-06-14 12:09:45

标签: php api spreadsheet

我对Spreadsheed api和"范围"有问题。 使用这些脚本我想更新工作表上的单元格。

我不和作曲家合作ich只是下载了相互关联的包。令牌已存在,错误来自这些行:

" $ response = $ service-> spreadsheets_values-> get($ spreadsheetId,$ range);"

<?php
session_start();
require_once __DIR__.'/vendor/autoload.php';

$client = new Google_Client();
$client->setAuthConfig('oauth-credentials.json');

$client->addScope(Google_Service_Drive::DRIVE_METADATA_READONLY);

if (isset($_SESSION['access_token']) && $_SESSION['access_token']) 
{
      $client->setAccessToken($_SESSION['access_token']);

      echo "<pre>";   
      $service = new Google_Service_Sheets($client);
      $spreadsheetId = 'xxx';
      $range = 'Tabellenblatt1!A2:E';

        $response = $service->spreadsheets_values->get($spreadsheetId, $range);
        $values = $response->getValues();

        if (count($values) == 0) {
          print "No data found.\n";
        } else {
          print "Name, Major:\n";
          foreach ($values as $row) {
            // Print columns A and E, which correspond to indices 0 and 4.
            printf("%s, %s <br>", $row[0], $row[4]);
          }
        }
    } else {
      $redirect_uri = 'http://' . $_SERVER['HTTP_HOST'] . '/api/oauth2callback.php';

      header('Location: ' . filter_var($redirect_uri, FILTER_SANITIZE_URL));
    }
?>

这些代码带来以下错误

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

2 个答案:

答案 0 :(得分:1)

您已定义此范围:
$client->addScope(Google_Service_Drive::DRIVE_METADATA_READONLY);

用于访问电子表格值:
$response = $service->spreadsheets_values->get($spreadsheetId, $range);

你应该有:
$client->addScope(Google_Service_Sheets::SPREADSHEETS_READONLY);

$client->addScope(Google_Service_Sheets::SPREADSHEETS);

来源:
https://developers.google.com/identity/protocols/googlescopes#sheetsv4

答案 1 :(得分:0)

您必须按照@ random425所述更新范围,

,但此后删除 Token.json 。 这将再次启动验证过程,这将为您提供具有已更改为新范围的新令牌。