Google Drive API:OAuth2 令牌出错

问题描述 投票:0回答:1

我想创建一个使用 Google Drive 作为存储的网络应用程序,并且我正在使用 Google API,但我在身份验证方面遇到问题。 我已选择服务帐户作为身份验证方法,但当我尝试运行脚本时出现此错误:

发生错误:刷新 OAuth2 令牌时出错,消息:'{ “错误”:“invalid_grant”}'数组()

代码如下:

<?php
require_once 'api/Google_Client.php';
require_once 'api/contrib/Google_DriveService.php';
require_once "api/contrib/Google_Oauth2Service.php";
session_start();

$service = buildService();

$fileList = retrieveAllFiles($service);
print_r($fileList);

/**
 * Build and returns a Drive service object authorized with the service accounts.
 *
 * @return Google_DriveService service object.
 */
function buildService($userEmail) {

  $DRIVE_SCOPE = 'https://www.googleapis.com/auth/drive';
  $SERVICE_ACCOUNT_EMAIL = 'xxxapps.googleusercontent.com';
  $SERVICE_ACCOUNT_PKCS12_FILE_PATH = 'xxx-privatekey.p12';

  $key = file_get_contents($SERVICE_ACCOUNT_PKCS12_FILE_PATH);
  $auth = new Google_AssertionCredentials(
      $SERVICE_ACCOUNT_EMAIL,
      array($DRIVE_SCOPE),
      $key);
  $auth->prn = $SERVICE_ACCOUNT_EMAIL;

  $client = new Google_Client();
  $client->setUseObjects(true);
  $client->setAssertionCredentials($auth);
  return new Google_DriveService($client);
}


/**
 * Retrieve a list of File resources.
 *
 * @param Google_DriveService $service Drive API service instance.
 * @return Array List of Google_DriveFile resources.
 */
function retrieveAllFiles($service) {
  $result = array();
  $pageToken = NULL;

  do {
    try {
      $parameters = array();
      if ($pageToken) {
        $parameters['pageToken'] = $pageToken;
      }
      $files = $service->files->listFiles($parameters);

      $result = array_merge($result, $files->getItems());
      $pageToken = $files->getNextPageToken();
    } catch (Exception $e) {
      print "An error occurred: " . $e->getMessage();
      $pageToken = NULL;
    }
  } while ($pageToken);
  return $result;
}
?>
php google-api google-drive-api google-oauth google-api-php-client
1个回答
2
投票

您是否记得将域范围权限委托给您的服务帐户的客户端 ID

© www.soinside.com 2019 - 2024. All rights reserved.