继续从Google API获取403 Forbidden(使用PHP客户端库v1)

时间:2016-03-22 06:52:43

标签: php api google-api google-cloud-storage gsutil

好的......我不得不说我没有足够的经验来使用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
  }
}

如果我错过了什么,请告诉我。

1 个答案:

答案 0 :(得分:0)

好的,我遇到了问题:它必须模拟有权访问我在程序中提到的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
);

Woooooyaaaaa,另一个问题解决了!是时候提出下一个问题了。