Google Api Php客户端 - Spreadsheets权限错误

时间:2017-06-16 09:38:09

标签: php google-sheets google-api google-api-php-client

我正在使用Google PHP客户端访问电子表格数据。

我得到了这个致命的错误:

  

致命错误:未捕获的异常' Google_Service_Exception'消息' {"错误":{"代码":403,"消息":"来电者没有权限" ,"错误":[{"消息":"来电者没有权限","域":"全球&# 34;,"原因":"禁止" }]," status":" PERMISSION_DENIED" }}

我的代码:

  $client = new Google_Client();
  $client->setApplicationName("Google spreadsheets");
  $client->setDeveloperKey("xxxxx");
  $client->setScopes(array('https://www.googleapis.com/auth/drive',    
  'https://www.googleapis.com/auth/spreadsheets.readonly',     
  'https://www.googleapis.com/auth/drive.file'));

  $service = new Google_Service_Sheets($client);

  $range = 'Class Data!A2:E';
  $response = $service->spreadsheets_values->get($sheetid, $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\n", $row[0], $row[4]);
    }
  }

如何解决这个问题?

4 个答案:

答案 0 :(得分:2)

获取服务帐户的电子邮件地址,并像使用其他任何用户一样与其共享工作表。然后它可以访问表单

答案 1 :(得分:0)

错误表示您无权访问该工作表。我建议您按照Google Sheets php quick start tutorial进行操作,这将向您展示如何使身份验证正常运行。

<?php
require_once __DIR__ . '/vendor/autoload.php';


define('APPLICATION_NAME', 'Google Sheets API PHP Quickstart');
define('CREDENTIALS_PATH', '~/.credentials/sheets.googleapis.com-php-quickstart.json');
define('CLIENT_SECRET_PATH', __DIR__ . '/client_secret.json');
// If modifying these scopes, delete your previously saved credentials
// at ~/.credentials/sheets.googleapis.com-php-quickstart.json
define('SCOPES', implode(' ', array(
  Google_Service_Sheets::SPREADSHEETS_READONLY)
));

if (php_sapi_name() != 'cli') {
  throw new Exception('This application must be run on the command line.');
}

/**
 * Returns an authorized API client.
 * @return Google_Client the authorized client object
 */
function getClient() {
  $client = new Google_Client();
  $client->setApplicationName(APPLICATION_NAME);
  $client->setScopes(SCOPES);
  $client->setAuthConfig(CLIENT_SECRET_PATH);
  $client->setAccessType('offline');

  // Load previously authorized credentials from a file.
  $credentialsPath = expandHomeDirectory(CREDENTIALS_PATH);
  if (file_exists($credentialsPath)) {
    $accessToken = json_decode(file_get_contents($credentialsPath), true);
  } else {
    // Request authorization from the user.
    $authUrl = $client->createAuthUrl();
    printf("Open the following link in your browser:\n%s\n", $authUrl);
    print 'Enter verification code: ';
    $authCode = trim(fgets(STDIN));

    // Exchange authorization code for an access token.
    $accessToken = $client->fetchAccessTokenWithAuthCode($authCode);

    // Store the credentials to disk.
    if(!file_exists(dirname($credentialsPath))) {
      mkdir(dirname($credentialsPath), 0700, true);
    }
    file_put_contents($credentialsPath, json_encode($accessToken));
    printf("Credentials saved to %s\n", $credentialsPath);
  }
  $client->setAccessToken($accessToken);

  // Refresh the token if it's expired.
  if ($client->isAccessTokenExpired()) {
    $client->fetchAccessTokenWithRefreshToken($client->getRefreshToken());
    file_put_contents($credentialsPath, json_encode($client->getAccessToken()));
  }
  return $client;
}

/**
 * Expands the home directory alias '~' to the full path.
 * @param string $path the path to expand.
 * @return string the expanded path.
 */
function expandHomeDirectory($path) {
  $homeDirectory = getenv('HOME');
  if (empty($homeDirectory)) {
    $homeDirectory = getenv('HOMEDRIVE') . getenv('HOMEPATH');
  }
  return str_replace('~', realpath($homeDirectory), $path);
}

// Get the API client and construct the service object.
$client = getClient();
$service = new Google_Service_Sheets($client);

// Prints the names and majors of students in a sample spreadsheet:
// https://docs.google.com/spreadsheets/d/1BxiMVs0XRA5nFMdKvBdBZjgmUUqptlbs74OgvE2upms/edit
$spreadsheetId = '1BxiMVs0XRA5nFMdKvBdBZjgmUUqptlbs74OgvE2upms';
$range = 'Class Data!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\n", $row[0], $row[4]);
  }
}

答案 2 :(得分:0)

根据此文档,除非您公开提供文档,否则您无法通过API key访问自己的电子表格:

来源:https://developers.google.com/sheets/api/guides/authorizing

该文件说:

  
      
  • 如果请求需要授权(例如请求个人的私人数据),则应用程序必须提供OAuth   带有请求的2.0令牌。应用程序还可以提供API密钥,但它不必提供。
  •   
  • 如果请求不需要授权(例如请求公共数据),则应用程序必须提供API密钥或   OAuth 2.0令牌,或两者兼而有之 - 无论什么选项最方便   你。
  •   

不幸的是,它不是很清楚&#34;这意味着什么。

但是结合来自多个来源的解释,这意味着API key允许您识别自己&#34; 访问公开信息。如果你想从谷歌地图获得一个可用的资源,谷歌仍然想知道谁会问及#34;。 API Key在这里工作。

相反,虽然上一个链接中的文字可能表明OAuth用于访问来自其他用户的数据&#34;实际上,任何私有 OAuth方法必须访问数据甚至您自己的数据

因此,要访问包含公司数据并且尚未公开发布的私有Google电子表格,则必须使用OAuth密钥系统。

答案 3 :(得分:0)

从下载的JSON文件或“服务帐户”中获取“ client_email”,并使用此电子邮件地址共享电子表格,您将可以访问电子表格。这个解决方案对我有用。