使用谷歌云存储api与开发者密钥(不是OAuth2)


using google cloud storage api with developer key (not OAuth2)

我想从一些控制台命令上传文件到谷歌云。正如我所理解的,不能用OAuth2做到这一点,所以我需要使用Api密钥。但什么都没用。我试过这个

$ch = curl_init();
$url = 'https://www.googleapis.com/upload/storage/v1/b/temp/o?uploadType=media&name=p11&key='.$this->key;
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_HTTPHEADER, [
    'Authorization: key '.$this->key
]);
curl_setopt($ch, CURLOPT_POSTFIELDS, '@/var/www/test.txt');
$content = curl_exec($ch);
var_dump($content);

有一个错误:

{ "error": { "errors": [ { "domain": "global", "reason": "authError", "message": "Invalid Credentials", 
  "locationType": "header", "location": "Authorization" } ],
  "code": 401, "message": "Invalid Credentials" } }

And i try php-sdk

$client = new Google_Client();
$client->setApplicationName("alasdg");
$client->setDeveloperKey($this->key);
$client->setScopes(['https://www.googleapis.com/auth/devstorage.read_write']);
$client->getAuth();
$storageService = new Google_Service_Storage($client);
$buckets = $storageService->buckets->listBuckets('temp');
var_dump($buckets);exit;

错误是:

Error calling GET https://www.googleapis.com/storage/v1/b?project=temp&key=afJwBJWucqvIU: (400) Invalid argument.

我可以上传文件没有OAuth2吗?

Invalid Credentials错误意味着您的Authorization标头在某种程度上是无效的,您需要刷新您的OAuth 2.0访问令牌。考虑到API密钥不是有效的访问令牌,这就可以解释了。你可能想要构建一个看起来像Authorization: Bearer ya29.xxxxxxxx的头,其中"ya29"等是一个访问令牌。凭据交换是由php-sdk代表您完成的。

你得到的第二个错误是因为很可能没有项目ID为"temp"的项目。这有点麻烦,因为您可以为项目分配一个"友好的名称",但该名称可以在许多项目中共享,并且不是唯一标识符。您必须使用命名的项目ID,或者,如果您还没有为您的项目分配一个,您可以使用数字项目ID,当您在https://console.developers.google.com/

中查看它时,它在URL中可见。

读写操作总是需要适当的身份验证和授权,即OAuth2令牌(更多信息)。如果只使用API密钥,您将被限制为匿名只读API访问(给定目标资源被标记为公共)。