sreekant krishnan
sreekant krishnan

Reputation: 65

Google authentication return invalid grant

I know this question has been posted before. But none of them has the answer. So I am re-posting the question. I am trying to get the analytics data. But after authenticating I get the 'invalid_grant' error for access token. Now I had the same code working for about 3 months and now all of a sudden I'm getting this issue. I have saved the refresh token in the database and use this for getting the access token. Is there a possibility that the request token expire? Please help!

$oauth2token_url    =   "https://accounts.google.com/o/oauth2/token";
$clienttoken_post   =   array(
                        "client_id" => $client_id,
                        "client_secret" => $client_secret,
                        "refresh_token" => $refreshToken,
                        "grant_type"    => 'refresh_token'
                    );

$authObj        =   getAccessToken($oauth2token_url, $clienttoken_post);

function getAccessToken($oauth2token_url, $clienttoken_post){

    $curl = curl_init($oauth2token_url);

    curl_setopt($curl, CURLOPT_POST, true);
    curl_setopt($curl, CURLOPT_POSTFIELDS, $clienttoken_post);
    curl_setopt($curl, CURLOPT_HTTPAUTH, CURLAUTH_ANY);
    curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
    curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);

    $json_response = curl_exec($curl);
    curl_close($curl);

    $authObj = json_decode($json_response);

    return $authObj;
}

Response of token :****************** is - stdClass Object ( [error] => invalid_grant )

Upvotes: 1

Views: 988

Answers (1)

sreekant krishnan
sreekant krishnan

Reputation: 65

Ok. I got it figured out. The problem was that when the user gives permission to the app the refresh token is refreshed. So if the user gives permission(2nd time) the 1st refresh token(that you have saved in the database or wherever) is refreshed. All you have to do is update the refresh token each time you are given permission.

Upvotes: 2

Related Questions