1

I would like to create a webapp that use Google Drive as a storage and I'm playing with the Google API but I have a problem with the authentication. I have choose the Service account as a authentication method but when I try to run the script I got this error:

An error occurred: Error refreshing the OAuth2 token, message: '{ "error" : "invalid_grant" }'Array ( )

The code is the following:

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

1 回答 1

2

Did you remember to delegate domain-wide authority to your service account's client ID?

于 2013-01-24T20:42:53.610 回答