认证谷歌内容Api服务帐户-错误'用户无法访问帐户'


authentication Google Content Api service account - error 'user cannot access account'

我拼命想让我的代码正常工作。我已经通过使用重定向url的身份验证路由成功连接到google Api。

然而,我需要得到这个工作作为一个独立的服务,将在crontab中运行。

所以现在我正在尝试使用'服务帐户'进行身份验证。

这是我的代码,下面你会发现它给我的错误。

$client = new Google_Client();
$client->setApplicationName('GoogleShoppingService');
if (isset($_SESSION['service_token'])) {
    $client->setAccessToken($_SESSION['service_token']);
}
$service = new Google_Service_Content($client);
$client_id = 'xxxxxxx.apps.googleusercontent.com';
$client->setClientId($client_id);
$service_account_name = 'xxxxxxx@developer.gserviceaccount.com';

$key_file_location = 'privatekey.p12';
$key = file_get_contents($key_file_location);
$scope = 'https://www.googleapis.com/auth/content';
$cred = new Google_Auth_AssertionCredentials(
    $service_account_name,
        array($scope),
        $key
    );
$result = $client->setAssertionCredentials($cred);
print_r($result);
if($client->getAuth()->isAccessTokenExpired()) {
    $client->getAuth()->refreshTokenWithAssertion($cred);
}
$_SESSION['service_token'] = $client->getAccessToken();
echo $client->getAccessToken();
$merchantId = 1234567;//this a dummy value, I replace it with the actual merchantId
$accountId = 1234567;//this a dummy value, I replace it with the actual accountId
$accountstatuses = $service->accountstatuses->get($merchantId,$accountId);

所以这是我在运行代码时得到的消息。(注意,令牌已经创建,但是我不能访问Google Shopping提要的内容。)

{"access_token":"ya29.NQD7MQz0cas9PhoAAADRPMlTVecqYXYh4fNoZfRMymQtSF4hwqJn31uobohLbw","expires_in":3600,"created":1404200605}
Fatal error:
Uncaught exception 'Google_Service_Exception' with message 'Error calling GET https://www.googleapis.com/content/v2/1234567/accountstatuses/1234567: (401) User cannot access account 1234567' in /home/sites/site1/web/googleShopping2/src/Google/Http/REST.php:79
Stack trace:
#0 /home/sites/site1/web/googleShopping2/src/Google/Http/REST.php(44): Google_Http_REST::decodeHttpResponse(Object(Google_Http_Request))
#1 /home/sites/site1/web/googleShopping2/src/Google/Client.php(499): Google_Http_REST::execute(Object(Google_Client), Object(Google_Http_Request))
#2 /home/sites/site1/web/googleShopping2/src/Google/Service/Resource.php(195): Google_Client->execute(Object(Google_Http_Request))
#3 /home/sites/site1/web/googleShopping2/src/Google/Service/Content.php(685): Google_Service_Resource->call('get', Array, 'Google_Service_...')
#4 /home/sites/site1/web/googleShopping2/examples/test.php(58): Google_Service_Content_Accountstatuses_Resource->get(1234567, 1234567)
#5 {main} thrown in /home/sites/site1/web/googleShopping2/src/Google/Http/REST.php on line 79

我已经试着找到一个解决方案2天了,但我找到的任何提示都没有帮助我。我还用新的Api认证密钥创建了一个新项目,但没有任何工作,我总是得到上述消息。请问谁能帮我?

问候,马丁

您需要在设置>用户下将您创建的服务帐户的电子邮件地址添加到Google商家帐户。

On https://merchants.google.com/

  • 在右上方,点击齿轮图标即设置。
  • 点击帐户访问
  • 点击+添加用户
  • 添加您从服务帐户.json文件中获得的电子邮件地址。(它在那里)
  • 确保添加的用户被设置为admin。