google-api - 使用服务帐户使用 Google Drive API 创建文件不会在授权用户帐户的 GD 上呈现文件
问题描述
我目前正在尝试创建一个文件,并使用 Google 提供的服务帐户身份验证方法将其上传到 Google Drive 帐户(因为它在最终产品中都是服务器端的,我不希望用户拥有授权访问,所以没有 OAuth per-say)。
我目前能够连接到服务帐户并上传文件,但是当我浏览我的 Google 云端硬盘时,该文件没有显示。
(我能够使用 OAuth 方法让它工作(上传和渲染);我会在上传之前手动授权应用程序,所以我很确定代码可以正常工作)
另外,我知道它工作的另一种方式是,一旦上传完成,我会返回一个文件 ID。如果我要去“https://drive.google.com/file/d/FILE_ID/view?usp=sharing”,我会遇到“需要授权”。
创建服务帐户时我应该做些什么,以便我的 Gmail 帐户可以访问文件?
有关信息,这是我连接到 API(服务器端)的方式:
<?php
$client = new Google_Client();
if ($this->oauth_credentials = $this->getServiceAccountCredentialsFile()) :
$client->setAuthConfig($this->oauth_credentials);
endif;
if ($this->warning != null) :
echo $this->warning;
return;
endif;
$client->setApplicationName("Test Google Drive Service Account");
$client->setScopes(['https://www.googleapis.com/auth/drive']);
$service = new Google_Service_Drive($client);
define("TESTFILE", ABSPATH.'testfile-small.txt');
if (!file_exists(TESTFILE)) {
$fh = fopen(TESTFILE, 'w');
fseek($fh, 1024 * 1024);
fwrite($fh, "!", 1);
fclose($fh);
}
$file = new Google_Service_Drive_DriveFile();
$result = $service->files->create(
$file,
array(
'data' => file_get_contents(TESTFILE),
'mimeType' => 'application/octet-stream',
'uploadType' => 'media'
)
);
echo '<pre>'; var_dump($result->id); echo '</pre>';
解决方案
你有四个选择...
- 不要使用服务帐户。只需为用户帐户存储一个刷新令牌。请参阅如何在没有用户干预的情况下授权应用程序(Web 或已安装)? . 服务帐户是服务器访问的唯一选项是一个神话。
- 使用服务帐户写入已由您的用户帐户共享到服务帐户的文件夹
- 使用服务帐户写入您的服务帐户与您的用户帐户共享的文件夹
- 使用 G-Suite 域中的服务帐户来模拟用户帐户
选项 1. 是最简单的,2 和 3 仅在谁拥有文件以及根据谁的配额计算文件方面有所不同。4 仅与 G-Suite 相关