Jac*_*oth 2 php google-api google-api-client google-drive-api google-api-php-client
我希望使用 PHP 脚本和 Google Drive API(将设置为 cron 作业)将 MySQL 备份从网络服务器推送到 Google Drive。
我知道这是一个服务器到服务器的应用程序,因此需要 Google 服务帐户(我知道可以使用用户帐户并刷新访问令牌 - 但我认为这不是正确的用例因为我不希望有任何用户交互?)。
我已在 Cloud Console 中设置了 Google 服务帐号。使用我的常规帐户,我与服务帐户共享一个目录,并且我尝试使用以下脚本上传测试文件:
function getClient()
{
$client = new Google_Client();
if ($credentials_file = checkServiceAccountCredentialsFile())
{
// set the location manually
$client->setAuthConfig($credentials_file);
}
else
{
echo missingServiceAccountDetailsWarning();
return;
}
$client->setApplicationName('Backups');
$client->setScopes(Google_Service_Drive::DRIVE);
$guzzleClient = new \GuzzleHttp\Client(array( 'curl' => array( CURLOPT_SSL_VERIFYPEER => false, ), ));
$client->setHttpClient($guzzleClient);
return $client;
}
Run Code Online (Sandbox Code Playgroud)
$file_to_upload = 'test.txt';
if(file_exists($file_to_upload))
{
// Get the API client and construct the service object.
$client = getClient();
$service = new Google_Service_Drive($client);
$folder_id = '#####################-##########';
$file = new Google_Service_Drive_DriveFile();
$file->setName($file_to_upload);
$file->setParents(array($folder_id));
$result = $service->files->create(
$file,
array(
'data' => file_get_contents("test.txt"),
'mimeType' => 'text/plain',
'uploadType' => 'multipart'
)
);
}
Run Code Online (Sandbox Code Playgroud)
这将返回以下异常:
Fatal error: Uncaught Google_Service_Exception: { "error": { "errors": [ { "domain": "global", "reason": "notFound", "message": "File not found: #####################-##########.", "locationType": "parameter", "location": "fileId" } ], "code": 404, "message": "File not found: #####################-##########." } }
Run Code Online (Sandbox Code Playgroud)
我理解这是一个权限错误 - 文件夹 ID 正确并且与与服务帐户共享的目录匹配:
我尚未将服务帐户客户端 ID 和https://www.googleapis.com/auth/drive范围添加到 GSuite 管理控制台 - 这是我错过的必需步骤吗?(我目前无法访问管理控制台)。
我注意到服务帐户可用于常规非 GSuite 帐户,那么这将如何工作,因为它们无法添加范围?
我很高兴服务帐户拥有它上传的文件,但希望普通用户能够手动删除它们 - 因为普通用户拥有共享文件夹,这可能吗?
是否有任何其他现有解决方案可以将文件从网络服务器备份到 Google 云端硬盘?
假设您已将服务帐户设置为云端硬盘上文件夹的有效编辑器,则可以使用服务帐户将文件上传到此文件夹,但有一个重要设置:
由于该文件夹不位于服务帐户的个人云端硬盘上,因此您需要将选项设置supportsAllDrives
为true
- 查看Files:Create 的文档。
否则无法找到该文件夹,从而导致您收到错误消息。
仅当您使用域范围委派时才需要执行此步骤- 也就是说,如果您让服务帐户代表另一个用户(例如您)并代表他行事。
请注意,非 G Suite(现在称为 Google Workspace)帐户无法使用全域模拟,因此这些用户无法在管理控制台中授权相应的范围。
对于在没有域范围委派的情况下使用服务帐户(如您的情况),您只需为相应的 GCP 项目启用相应的 API(驱动器)并将范围包含在代码中。
请注意,您的错误是由于权限问题造成的,您可能会获得 403 错误代码而不是 404。