我找到了 Google Drive API 文档,它们都谈到了 OAuth,这将允许我的用户授予对其帐户文件的访问权限,但我想通过 API 提供我的文件。我怎样才能做到这一点?另外,我正在使用 PHP 和这个库 https://github.com/googleapis/google-api-php-client
我当前的代码
<?php
use Google\Client;
use Google\Service\Drive;
$files = [];
try{
require_once 'vendor/autoload.php';
$client = new Google\Client();
$client->setApplicationName("MYNAME");
$client->setDeveloperKey("MYKEY");
$client->addScope(Drive::DRIVE);
$driveService = new Drive($client);
$pageToken = null;
do {
$response = $driveService->files->listFiles(array(
'q' => "mimeType='image/jpeg'",
'spaces' => 'drive',
'pageToken' => $pageToken,
'fields' => 'nextPageToken, files(id, name)',
));
foreach ($response->files as $file) {
printf("Found file: %s (%s)\n", $file->name, $file->id);
}
array_push($files, $response->files);
$pageToken = $response->pageToken;
} while ($pageToken != null);
var_dump($files);
} catch(Exception $e) {
echo "Error Message: ".$e;
}
?>
这给我带来了不够的文件权限。
要使用 Google Drive API 访问 Google Drive 中您自己的文件而不需要通过 OAuth 进行用户授权,您应该使用服务帐户。服务帐户专为服务器到服务器交互而设计,可以访问与服务帐户关联的帐户拥有的文件。
设置方法如下:
如果您希望服务帐户访问特定文件或文件夹:
[email protected]
)。现在,更新您的 PHP 代码以使用服务帐户凭据:
<?php
require_once 'vendor/autoload.php';
use Google\Client;
use Google\Service\Drive;
$files = [];
try {
$client = new Client();
$client->setApplicationName("MYNAME");
$client->setScopes(Drive::DRIVE);
$client->setAuthConfig('path/to/your-service-account.json'); // Path to your downloaded JSON key file
$client->setSubject('[email protected]'); // Optional: the email of the user you want to impersonate (if applicable)
$driveService = new Drive($client);
$pageToken = null;
do {
$response = $driveService->files->listFiles(array(
'q' => "mimeType='image/jpeg'",
'spaces' => 'drive',
'pageToken' => $pageToken,
'fields' => 'nextPageToken, files(id, name)',
));
foreach ($response->files as $file) {
printf("Found file: %s (%s)\n", $file->name, $file->id);
}
array_push($files, $response->files);
$pageToken = $response->nextPageToken; // Fixed typo here
} while ($pageToken != null);
var_dump($files);
} catch (Exception $e) {
echo "Error Message: " . $e->getMessage();
}
?>
此设置应允许您的 PHP 应用程序访问 Google 云端硬盘中的文件,而无需用户 OAuth 权限。如果您需要进一步的帮助,请告诉我!