好的...我不得不说,我在使用谷歌的API方面没有足够的经验,所以我会尽可能详细地解释。
我需要使用 PHP 来获取云存储的数据,所以我尝试使用 gsUtil 使用我的凭据从存储桶中获取数据并且可以工作;但是当我尝试使用 PHP 库来获取数据时,API 回复了我以下内容:
"error": {
"errors": [
{
"domain": "global",
"reason": "forbidden",
"message": "Forbidden"
}
],
"code": 403,
"message": "Forbidden"
}
由于它没有确切地告诉我哪个步骤是错误的,所以我搜索了这个网站并尝试了所有看起来相似的内容,但情况仍然存在。
这是我的谷歌开发控制台上的配置:
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
}
}
如果我错过了什么,请告诉我。
好的,我遇到了问题:它必须模拟有权访问我在程序中提到的 API 范围的用户帐户。
因此,必须添加一些附加代码,如下所示:
$email = '<email account which could access that api>';
$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),
'notasecret',
'http://oauth.net/grant_type/jwt/1.0/bearer',
$email
);
呜,另一个问题解决了! 是时候为下一个问题前进了。