Google Drive API:OAuth2令牌出错

时间:2013-01-24 10:22:11

标签: google-api google-drive-api google-authentication google-api-php-client

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

  

发生错误:刷新OAuth2令牌时出错,消息:' {   "错误" :" invalid_grant" }' Array()

代码如下:

<?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;
}
?>

1 个答案:

答案 0 :(得分:2)