如何从PHP脚本访问我的谷歌驱动器,无需手动授权

use*_*961 2 php google-api google-drive-api google-oauth

我想写一个服务器php脚本,它将访问我的谷歌驱动器并在那里复制一个文件.服务器必须保存我的谷歌驱动器的凭据,而不是要求授权.我看到的所有示例都描述了各种用户可以在其驱动器上执行操作的Web应用程序.例如,https://developers.google.com/drive/v3/web/quickstart/php 如何在我的服务器上保存所有需要的凭据.

use*_*961 8

经过长时间的研究和阅读谷歌文档和示例,我发现了一种适合我的方式.

  1. 您需要一个服务帐户.此帐户将访问Google云端硬盘数据.
  2. 我使用谷歌域名,因此我需要向此服务帐户授予域范围权限.
  3. 在这里,您可以找到如何创建服务帐户并授予其域范围的权限,但此链接没有PHP示例
  4. 在这里,您可以找到与PHP示例相同的说明
  5. 创建服务帐户时请注意您需要JSON类型的密钥文件.
  6. 我使用了Google Application Default Credentials.

最后这是工作代码片段:

<?php
require_once '/path/to/google-api-php-client/vendor/autoload.php';

putenv('GOOGLE_APPLICATION_CREDENTIALS=/path/to/service-account.json');

$client = new Google_Client();
$client->useApplicationDefaultCredentials();
$client->setScopes(['https://www.googleapis.com/auth/drive']);
$client->setSubject('email_of_account@you_want_to_work.for');

$service = new Google_Service_Drive($client);

//Create a new folder
$fileMetadata = new Google_Service_Drive_DriveFile(
     array('name' => 'Invoices', 
           'mimeType' => 'application/vnd.google-apps.folder'));
$file = $service->files->create($fileMetadata, array('fields' => 'id'));
echo $file->id;
?>
Run Code Online (Sandbox Code Playgroud)