使用全域委托服务帐户从 Google App Engine 访问 GDrive

Accessing GDrive from Google App Engine with domain-wide delegation service account

这是我第一次使用 Google App Engine,所以我的一些术语可能有点不对,请多多包涵。

我在使用 google-api-php-客户端的 GAE 之外的 Web 应用程序中有一些 php 代码 运行ning库访问 gdrive 文件夹和创建文件。效果非常好。

我正在尝试使用具有域范围授权的项目迁移到 GAE,以便我的应用程序可以 access/create 我的 gdrive 帐户中的文件。例如,假设我的域是 kennywyland.com,我使用的 Google 帐户是 kenny@kennywyland.com。

我这样创建我的 Google 客户端,我从 https://developers.google.com/api-client-library/php/auth/service-accounts:

$client = new Google_Client();
$client->setAuth(new Google_Auth_AppIdentity($client));
$client->getAuth()->authenticateForScope('https://www.googleapis.com/auth/drive');

然后我像这样创建 gdrive 服务:

$service = new Google_Service_Drive($client);

我没有从中得到任何错误,并且我能够在不抛出错误消息的情况下执行查询,但是,我得到的是完全空的结果集。我的 gdrive 帐户中有很多文件,所以我假设当我将以下代码发布到 GAE 和 运行 它时我应该看到它们(retreiveAllFiles() 函数来自 Google'在这里找到的代码示例:https://developers.google.com/drive/v2/reference/files/list#try-it):

$allfiles = retrieveAllFiles($service);

print_r($allfiles);

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

但是,我得到一个空的结果集。 print_r() 打印一个空数组:

Array ( )

我错过了什么?我觉得我的 project/app 能够成功访问 gdrive 服务器,但它无法看到我帐户中与该工作域关联的任何文件。

该解决方案涉及一项主要更改,需要进一步更改。主要的变化是我使用的是 google-api-php-client v1,但我需要使用 v2 候选版本(奇怪的是它位于 https://github.com/google/google-api-php-client/tree/v1-master 分支)。

他们有一个从 1.0 升级到 2.0 所需的代码更改列表(谢谢,非常方便的 githubers!) https://github.com/google/google-api-php-client/blob/master/UPGRADING.md

我最终使用以下代码配置了我的客户端,然后它立即能够访问 gdrive,就好像它是当前登录的人一样(假设 'kenny@kennywyland.com' 在我的示例中,他是我的特殊成员的一部分具有 domain-wide 授权的域)。

require_once('vendor/autoload.php');

$client = new Google_Client();

$client->setAuthConfig('myapp-xxxxxxxx.json');
$user_to_impersonate = "kenny@kennywyland.com";
$client->setSubject($user_to_impersonate);

$client->addScope('https://www.googleapis.com/auth/drive');

$service = new Google_Service_Drive($client);

myapp-xxxxxxx.json 文件是在我的开发者控制台中为我的应用服务帐户生成的。