我試圖使用公共API密鑰將測試文件從CLI PHP腳本發送到我的Google雲端硬盤帳戶中的特定文件夾。我已經生成了密鑰並在Google開發控制檯中設置了我的IP地址。使用公共API密鑰將文件從CLI從CLI發送到特定文件夾
這是我目前:
<?php
if (strtolower(PHP_SAPI) !== 'cli')
{
throw new Exception("Run this from CLI only");
}
$autoloader_path = '.' . DIRECTORY_SEPARATOR . 'vendor' . DIRECTORY_SEPARATOR;
$autoloader_file = realpath($autoloader_path . 'autoload.php');
if (!file_exists($autoloader_file))
{
throw new Exception("Autoloader file not found");
}
require_once $autoloader_file;
if (!class_exists('\Composer\Autoload\ClassLoader', true))
{
throw new Exception("Composer autoloader failed to load");
}
$client = new Google_Client();
$client->setDeveloperKey('my-public-api-key');
$service = new Google_Service_Drive($client);
$file = new Google_Service_Drive_DriveFile($client);
$d = array(
'data' => file_get_contents("test.txt"),
'mimeType' => 'text/plain',
'uploadType' => 'media'
);
$result = $service->files->insert($file, $d);
var_dump($result);
我得到「需要登錄」錯誤:
$ php backup.php
PHP Fatal error: Uncaught exception 'Google_Service_Exception' with message 'Error calling POST https://www.googleapis.com/upload/drive/v2/files?uploadType=media&key=**<my key>**: (401) Login Required' in /home/raspi/gdrive/vendor/google/apiclient/src/Google/Http/REST.php:79
Stack trace:
#0 /home/raspi/gdrive/vendor/google/apiclient/src/Google/Http/REST.php(44): Google_Http_REST::decodeHttpResponse(Object(Google_Http_Request))
#1 /home/raspi/gdrive/vendor/google/apiclient/src/Google/Client.php(556): Google_Http_REST::execute(Object(Google_Client), Object(Google_Http_Request))
#2 /home/raspi/gdrive/vendor/google/apiclient/src/Google/Service/Resource.php(195): Google_Client->execute(Object(Google_Http_Request))
#3 /home/raspi/gdrive/vendor/google/apiclient/src/Google/Service/Drive.php(1760): Google_Service_Resource->call('insert', Array, 'Google_Service_...')
#4 /home/raspi/gdrive/backup.php(37): Google_Service_Drive_Files_Resource->insert(Object(Google_Service_Drive_DriveFile), Array)
#5 {main}
thr in /home/raspi/gdrive/vendor/google/apiclient/src/Google/Http/REST.php on line 79
因此,如何我可以使用公共API密鑰發送文件或者我需要使用OAuth?我已使用Google搜索,但只能找到OAuth文件發送示例。
composer.json
:
{
"name": "raspi/gdrive",
"description": "Gdrive",
"license": "BSD",
"require": {
"php": ">=5.4",
"google/apiclient": "1.0.*@beta"
}
}