google service account example returns “Error refreshing the OAuth2 token { “error” : “invalid_grant” }”

谁说我不能喝 提交于 2019-12-13 11:35:25

问题


My goal is to make the simplest query on Google Fusion Tables on behalf of my web app users. For that, I created a service account on google console. Here is the code:

    // Creating a google client
    $client = new \Google_Client();


    // setting the service acount credentials
    $serviceAccountName = 'XXXXX.apps.googleusercontent.com';
    $scopes= array(
                'https://www.googleapis.com/auth/fusiontables',
                'https://www.googleapis.com/auth/fusiontables.readonly',
                );
    $privateKey=file_get_contents('/path/to/privatekey.p12');
    $privateKeyPassword='notasecret'; // the default one when generated in the console

    $credential = new \Google_Auth_AssertionCredentials($serviceAccountName,
            $scopes, $privateKey, $privateKeyPassword);

    // setting assertion credentials
    $client->setAssertionCredentials($credential);

    $service = new \Google_Service_Fusiontables($client);
    $sql = 'select name from XXXXXXXX'; 
    $result = $service->query->sql($sql);

After running this code, I got this error:

Error refreshing the OAuth2 token, message: '{
"error" : "invalid_grant"
}'

I googled that for days and most of answers are talking about refreshing the token. I made this refresh but still the same errors!

Any idea for solving this problem? Thanks


回答1:


In my case it was caused by the server's time being too far off (about 5 minutes).

Although your issue is already solved, maybe this is of any help for someone who lands here in the future as the error returned by Google is the same.




回答2:


I know that many people are facing the same problem like mine. So, this is the solution after days of search on google.

The code I proposed has only one error: the client id is like an email similar to 123456789-abcdebsbjf@developer.gserviceaccount.com

The second thing you have to do is to share the table you are quering in google fusion tables with the client id of the service account.

After that, thing will work perfectly.

I hope this would help other.




回答3:


I got same error in google analytic API, I have solved it by adding my Service accounts Email address with google analytic account.



来源:https://stackoverflow.com/questions/24572077/google-service-account-example-returns-error-refreshing-the-oauth2-token-err

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!