我一直在尝试实现一个程序,将用户网站的备份上传到谷歌驱动器。他们都在我的域上有一个帐户,所以我完成了授予域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()
有人对如何解决这个问题有什么建议或意见吗?如果你用谷歌搜索这些问题,谷歌只会提供一页又一页的链接到他们自己的文档,正如我上面所展示的,这根本不起作用。
基本上,我希望看到一个如何使用"服务帐户"的示例,该帐户已被授予域范围的访问权限,以实例化驱动器服务对象。
文档中似乎有一些拼写错误(如果我们编写文档,它应该被称为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);
他们定义了三个变量,但使用了三个三常数-删除了contsnt并使用了变量。
没有方法
Google_AssertionCredentials::setPrn()
。属性prn
的可见性是公开的。所以您可以将其设置为$auth->prn = $userEmail;