【发布时间】:2020-12-03 19:42:02
【问题描述】:
我目前正在尝试创建一个文件,并使用 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>';
【问题讨论】:
-
@Aerials 该问题已经包含足够的信息,以便清楚问题并提供答案。
标签: google-api google-drive-api google-oauth google-api-php-client