身份验证Google内容Api服务帐户 - 错误'用户无法访问帐户'

时间:2014-07-01 08:34:23

标签: php authentication google-oauth service-accounts

我正在试图让我的代码发挥作用。 通过使用带有重定向网址的身份验证路由,我已经成功连接到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购物Feed的内容。)

{"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 auth键创建了一个新项目,但没有任何作用,我总是收到上述消息。 谁可以帮助我?

此致 马丁

1 个答案:

答案 0 :(得分:5)

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