我想通过一些控制台命令将文件上传到谷歌云。据我所知,不能用 OAuth2 做到这一点,所以我需要使用 Api key 。但没有任何效果。我试过了
$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" } }
我试过 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
header 在某种程度上无效,您需要刷新 OAuth 2.0 访问 token 。鉴于 API key 不是有效的访问 token ,这可以解释它。您可能想要构建一个看起来像 Authorization: Bearer ya29.xxxxxxxx
的 header ,其中“ya29”等是访问 token 。凭据交换由 php-sdk 代表您完成。
您收到的第二个错误是因为很可能没有项目 ID 为“temp”的项目。这有点难,因为您可以为您的项目分配一个“友好名称”,但该名称可以在许多项目之间共享,并且不是唯一标识符。您必须使用命名的项目 ID,或者,如果您没有为项目分配 ID,则可以使用数字项目 ID,当您在 https://console.developers.google.com/ 中查看它时,它会在 URL 中可见。
关于php - 将 google 云存储 api 与开发人员 key (不是 OAuth2)一起使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24608235/