【发布时间】:2016-07-08 22:57:22
【问题描述】:
好吧...我不得不说我没有足够的使用 Google API 的经验,所以我会尽可能详细地解释。
我需要使用 PHP 来获取云存储的数据,所以我尝试使用 gsUtil 我的凭据从存储桶中获取数据,它可以工作;但是当我尝试使用 PHP 库抓取数据时,API 回复了我这样的内容:
"error": {
"errors": [
{
"domain": "global",
"reason": "forbidden",
"message": "Forbidden"
}
],
"code": 403,
"message": "Forbidden"
}
由于它没有准确地告诉我哪一步是错误的,所以我在这个网站上搜索并尝试了所有看起来相似的东西,但情况仍然存在。
这是我的 Google Dev 上的配置。控制台:
Api Manager > Overall > Enabled API:
(a)Drive API.
(b)Cloud Storage.
(c)Cloud Storage JSON API.
Api Manager > Credentials:
(a)Api Key / OAuth 2.0 ID / Service Acc. Key are created.
(b)Server IPs are added to the Api key's accept IP list.
(c)Service Account have the Editor permission to the Project, service acc key is bind to this account too.
在 PHP 中:
$email = '<my gmail>';
$scope = 'https://www.googleapis.com/auth/cloud-platform';
$apiKey = '<my api key>';
$oAuthId = '<OAuth ID>';
$serviceAcc = '<service account id>@developer.gserviceaccount.com';
$keyFileLocation = $_SERVER['DOCUMENT_ROOT']. "/<p12 file>";
$bucketId = '<my bucket id>';
$list = array();
$client = new Google_Client();
$client->setApplicationName("gp-api");
$client->setDeveloperKey($apiKey);
$cred = new Google_Auth_AssertionCredentials (
$serviceAcc,
array($scope),
file_get_contents($keyFileLocation)
);
$client->setAssertionCredentials($cred);
if($client->getAuth()->isAccessTokenExpired())
$client->getAuth()->refreshTokenWithAssertion($cred);
if($client->getAccessToken()) {
$reqUrl = "https://www.googleapis.com/storage/v1/b/$bucketId/o/";
$request = new Google_Http_Request($reqUrl, 'GET', null, null);
$httpRequest = $client->getAuth()->authenticatedRequest($request);
if ($httpRequest->getResponseHttpCode() == 200) {
$objects = json_decode($httpRequest->getResponseBody());
foreach ($objects->items as $object) {
$list[] = $object->mediaLink;
}
}
else {
echo $httpRequest->getResponseHttpCode(); // This is where I got the 403
}
}
如果我遗漏了什么,请告诉我。
【问题讨论】:
-
您是否可能没有存储桶的 READ 权限?或者,我看到您同时定义了 $email 和 $serviceAcc,但在创建 Google_Auth_AssertionCredentials 时使用了未定义的变量 $accountName。你是用其他代码来填充它吗?
-
@Brandon Yarbrough 哎呀,我的打字错误。 xD 现在已经修复了。
-
@Brandon Yarbrough 但如果我没有 READ 权限,我应该在使用 gsUtil 读取存储桶时遇到错误。但是我的具有这些凭据的 gsUtils 可以正常工作。
-
gsutil 使用的是您的凭据,还是服务帐户 $serviceAcc 的凭据?
-
gsutil 使用 oAuth2 令牌(将生成一个 url 用于浏览并从中获取 Auth 代码)和项目 ID(可以在开发控制台的仪表板中找到,位于应用程序/项目名称下方)
标签: php api google-api google-cloud-storage gsutil