2

我一直在尝试实现一个程序,将我的用户网站的备份上传到谷歌驱动器。他们所有人都在我的域上拥有一个帐户,因此我完成了为我的应用程序授予域 wde 授权的步骤,如下所述:https ://developers.google.com/drive/delegation

不幸的是,他们用于实例化驱动服务对象的示例代码在许多层面上都失败了。这里是:

<?php

require_once "google-api-php-client/src/Google_Client.php";
require_once "google-api-php-client/src/contrib/Google_DriveService.php";
require_once "google-api-php-client/src/contrib/Google_Oauth2Service.php";
session_start();

$DRIVE_SCOPE = 'https://www.googleapis.com/auth/drive';
$SERVICE_ACCOUNT_EMAIL = '<some-id>@developer.gserviceaccount.com';
$SERVICE_ACCOUNT_PKCS12_FILE_PATH = 'privatekey.p12';

/**
 * Build and returns a Drive service object 
 * authorized with the service accounts
 * that acts on behalf of the given user.
 *
 * @param userEmail The email of the user.
 * @return Google_DriveService service object.
 */
function buildService($userEmail) {
  $key = file_get_contents(KEY_FILE);
  $auth = new Google_AssertionCredentials(
      SERVICE_ACCOUNT_EMAIL,
      array(DRIVE_SCOPE),
      $key);
  $auth->setPrn($userEmail);
  $client = new Google_Client();
  $client->setUseObjects(true);
  $client->setAssertionCredentials($auth);
  return new Google_DriveService($client);
}

?>

第一个明显的错误是他们让你设置了变量,但函数使用了常量。因此,我硬编码了常量(KEY_FILE、SERVICE_ACCOUNT_EMAIL 等)应该存在的内容,以查看它是否有效,然后出现以下错误:

Fatal error: Call to undefined method Google_AssertionCredentials::setPrn()

有没有人对如何解决这个问题有任何建议或意见?如果你用谷歌搜索这些问题,谷歌只会提供一页又一页的链接到他们自己的文档,正如我上面显示的那样,它根本不起作用。

基本上,我希望看到一个示例,说明如何使用已被授予域范围访问权限的“服务帐户”来实例化驱动器服务对象。

4

1 回答 1

4

文档中似乎有一些拼写错误(如果我们编写了文档,则应该将其称为 bug :))。

<?php

require_once "google-api-php-client/src/Google_Client.php";
require_once "google-api-php-client/src/contrib/Google_DriveService.php";
require_once "google-api-php-client/src/contrib/Google_Oauth2Service.php";
session_start();

function buildService($userEmail) {

  $DRIVE_SCOPE = 'https://www.googleapis.com/auth/drive';
  $SERVICE_ACCOUNT_EMAIL = '<some-id>@developer.gserviceaccount.com';
  $SERVICE_ACCOUNT_PKCS12_FILE_PATH = 'privatekey.p12';

  $key = file_get_contents($SERVICE_ACCOUNT_PKCS12_FILE_PATH);

  $auth = new Google_AssertionCredentials($SERVICE_ACCOUNT_EMAIL, array($DRIVE_SCOPE), $key); // Changed!

  $auth->prn = $userEmail; // Changed!

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

$service = buildService('email@yourdomain.com');


$file = new Google_DriveFile();
$file->setTitle('My document');
$file->setDescription('A test document');
$file->setMimeType('text/plain');

$data = "contents";

$createdFile = $service->files->insert($file, array('data' => $data,'mimeType' =>'text/plain',));

print_r($createdFile);
  1. 他们定义了三个变量,但使用了三个三个常量——删除了常量并使用了变量。

  2. 没有办法Google_AssertionCredentials::setPrn()。该属性prn的可见性是公开的。所以你可以将它设置为 $auth->prn = $userEmail;

于 2012-11-15T11:19:05.940 回答