3

我正在尝试使用 Google Drive SDK 服务帐户创建一个可以在后台运行的 Google Drive 应用程序(例如 cronjob),无需任何用户交互,但它给了我这个错误,我不明白为什么:

调用 POST https://www.googleapis.com/upload/drive/v1/files?uploadType=multipart时出错:(403)经过身份验证的用户尚未安装客户端 ID 为 {my_client_id} 的应用程序

在 Google API 控制台上,我已经激活了 Drive API 和 Drive SDK。在 Drive SDK 选项卡上,我已经设置了所有必需的信息。我还向 Chrome 网上应用店发布了仅供测试人员使用的应用程序,并将其安装到我的 Google Chrome 中,应用程序名称出现在我的 Google Drive“创建”菜单上。

这是我的代码片段:

<?php

require_once dirname(__FILE__).'/google-api-php-client/src/apiClient.php';
require_once dirname(__FILE__).'/google-api-php-client/src/contrib/apiDriveService.php';

$apiClient = new apiClient();
$apiClient->setClientId(DRIVE_CLIENT_ID);
$apiClient->setClientSecret(DRIVE_CLIENT_SECRET);
$apiClient->setAssertionCredentials(new apiAssertionCredentials(
    OAUTH2_EMAIL, 
    array('https://www.googleapis.com/auth/drive.file'), 
    file_get_contents(SERVICE_ACCOUNT_PRIVATEKEY_FILE))
);

$apiDriveService = new apiDriveService($apiClient);

$file = new DriveFile();
$file->setTitle('filename.txt');
$file->setMimeType('text/plain');
$createdFile = $apiDriveService->files->insert($file, array(
    'data' => 'file content goes here....',
    'mimeType' => 'text/plain'
));

?>

据我了解,应用程序可以代表用户使用 Google Drive SDK 的服务帐户。这是否意味着用户没有身份验证问题(请求权限)?那么应用程序如何验证自己呢?或者我的理解可能是错误的?请在这里帮助启发我。

4

1 回答 1

2

由于其安全模型,Drive SDK 不支持服务帐户。

我的建议是使用您的应用程序从 Drive Web UI 打开(或创建)一个文件,并存储您在 OAuth 2.0 授权流程完成后获得的检索到的访问和刷新令牌。

从您的 cron 作业中,只需检索这些凭据即可代表您的用户向 Drive API 发送授权请求。

于 2012-05-03T17:31:19.140 回答