How to refresh token with Google API client?

how to get refresh token google api
get refresh token google api javascript
google refresh token expiration
refresh access token google api
get refresh token google api-php
google oauth redirect uri
google.oauth2 python
obtain an access token from the google authorization server

I've been playing around with the Google Analytics API (V3) and have run into som errors. Firstly, everything is set up correct and worked with my testing account. But when I want to grab data from another profile ID (Same Google Accont/GA Account) I get an 403 Error. The strange thing is that data from some GA accounts will return data whilst other generate this error.

I've revoked the token and authenticated one more time, and now it seems like I can grab data from all of my accounts. Problem solved? Not. As the access key will expire, I will run into the same issue again.

If I have understood things right, one could use the resfreshToken to get a new authenticationTooken.

The problem is, when I run:

$client->refreshToken(refresh_token_key) 

the following error is returned:

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

I’ve checked the code behind the refreshToken method and tracked the request back to the "apiOAuth2.php" file. All parameters are sent correctly. The grant_type is hard coded to ‘refresh_token’ within the method, so it’s hard for me to understand what’s wrong. The parameter array looks like this:

Array ( [client_id] => *******-uqgau8uo1l96bd09eurdub26c9ftr2io.apps.googleusercontent.com [client_secret] => ******** [refresh_token] => 1\/lov250YQTMCC9LRQbE6yMv-FiX_Offo79UXimV8kvwY [grant_type] => refresh_token )

The procedure is as follows.

$client = new apiClient();
$client->setClientId($config['oauth2_client_id']);
$client->setClientSecret($config['oauth2_client_secret']);
$client->setRedirectUri($config['oauth2_redirect_uri']);
$client->setScopes('https://www.googleapis.com/auth/analytics.readonly');
$client->setState('offline');

$client->setAccessToken($config['token']); // The access JSON object.

$client->refreshToken($config['refreshToken']); // Will return error here

Is this a bug, or have I completely misunderstood something?

So i finally figured out how to do this. The basic idea is that you have the token you get the first time you ask for authentication. This first token has a refresh token. The first original token expires after an hour. After an hour you have to use the refresh token from the first token to get a new usable token. You use $client->refreshToken($refreshToken) to retrieve a new token. I will call this "temp token." You need to store this temp token as well because after an hour it expires as well and note it does not have a refresh token associated with it. In order to get a new temp token you need to use the method you used before and use the first token's refreshtoken. I have attached code below, which is ugly, but im new at this...

//pull token from database
$tokenquery="SELECT * FROM token WHERE type='original'";
$tokenresult = mysqli_query($cxn,$tokenquery);
if($tokenresult!=0)
{
    $tokenrow=mysqli_fetch_array($tokenresult);
    extract($tokenrow);
}
$time_created = json_decode($token)->created;
$t=time();
$timediff=$t-$time_created;
echo $timediff."<br>";
$refreshToken= json_decode($token)->refresh_token;


//start google client note:
$client = new Google_Client();
$client->setApplicationName('');
$client->setScopes(array());
$client->setClientId('');
$client->setClientSecret('');
$client->setRedirectUri('');
$client->setAccessType('offline');
$client->setDeveloperKey('');

//resets token if expired
if(($timediff>3600)&&($token!=''))
{
    echo $refreshToken."</br>";
    $refreshquery="SELECT * FROM token WHERE type='refresh'";
    $refreshresult = mysqli_query($cxn,$refreshquery);
    //if a refresh token is in there...
    if($refreshresult!=0)
    {
        $refreshrow=mysqli_fetch_array($refreshresult);
        extract($refreshrow);
        $refresh_created = json_decode($token)->created;
        $refreshtimediff=$t-$refresh_created;
        echo "Refresh Time Diff: ".$refreshtimediff."</br>";
        //if refresh token is expired
        if($refreshtimediff>3600)
        {
            $client->refreshToken($refreshToken);
        $newtoken=$client->getAccessToken();
        echo $newtoken."</br>";
        $tokenupdate="UPDATE token SET token='$newtoken' WHERE type='refresh'";
        mysqli_query($cxn,$tokenupdate);
        $token=$newtoken;
        echo "refreshed again";
        }
        //if the refresh token hasn't expired, set token as the refresh token
        else
        {
        $client->setAccessToken($token);
           echo "use refreshed token but not time yet";
        }
    }
    //if a refresh token isn't in there...
    else
    {
        $client->refreshToken($refreshToken);
        $newtoken=$client->getAccessToken();
        echo $newtoken."</br>";
        $tokenupdate="INSERT INTO token (type,token) VALUES ('refresh','$newtoken')";
        mysqli_query($cxn,$tokenupdate);
        $token=$newtoken;
        echo "refreshed for first time";
    }      
}

//if token is still good.
if(($timediff<3600)&&($token!=''))
{
    $client->setAccessToken($token);
}

$service = new Google_DfareportingService($client);

Using OAuth 2.0 for Web Server Applications, At https://developers.google.com/api-client-library/php/auth/web-app#offline it says: Access tokens periodically expire. You can refresh an� This first token has a refresh token. The first original token expires after an hour. After an hour you have to use the refresh token from the first token to get a new usable token. You use The first original token expires after an hour.

The problem is in the refresh token:

[refresh_token] => 1\/lov250YQTMCC9LRQbE6yMv-FiX_Offo79UXimV8kvwY

When a string with a '/' gets json encoded, It is escaped with a '\', hence you need to remove it.

The refresh token in your case should be:

1/lov250YQTMCC9LRQbE6yMv-FiX_Offo79UXimV8kvwY

What i'm assuming you've done is that you've printed the json string which google sent back and copied and pasted the token into your code because if you json_decode it then it will correctly remove the '\' for you!

How to refresh token with Google API client?, not have refresh token because grom google get refreshToken = null ot need set null with key refresh token or this dosn't metter ? `$client = $this-� Java. Follow these instructions in GitHub to get an OAuth2 refresh token and configure the client library.; Return to this page when you're done. After completing the steps, your ads.properties file should have all you need to make test API calls, and should contain values similar to the following:

here is the snippet to set token, before that make sure the access type should be set to offline

if (isset($_GET['code'])) {
  $client->authenticate();
  $_SESSION['access_token'] = $client->getAccessToken();
}

To refresh token

$google_token= json_decode($_SESSION['access_token']);
$client->refreshToken($google_token->refresh_token);

this will refresh your token, you have to update it in session for that you can do

 $_SESSION['access_token']= $client->getAccessToken()

googleapis/google-api-php-client, This tutorial demonstrates the steps it takes to generate a long-lived refresh token for your Duration: 4:02 Posted: Jul 26, 2013 Browse other questions tagged curl google-api google-oauth google-analytics-api google-api-client or ask your own question. The Overflow Blog Podcast 259: from web comics to React core with Rachel Nabors

The access type should be set to offline. state is a variable you set for your own use, not the API's use.

Make sure you have the latest version of the client library and add:

$client->setAccessType('offline');

See Forming the URL for an explanation of the parameters.

Google api refresh_token null and how to refresh access token , The REST API accepts the same Firebase ID tokens used by the client SDKs. Google OAuth2 access tokens. Any data that's publicly readable or� Google API: getting Credentials from refresh token with oauth2client.client (8 answers) Closed last year . This function is to get authenticated service from Google.

The answer posted by @uri-weg worked for me but as I did not find his explanations very clear, let me reword it a little.

During the first access permission sequence, in the callback, when you get to the point where you receive an authentication code, you must save the access token and the refresh token as well.

The reason is google api sends you an access token with a refresh token only when prompting for access permission. The next access tokens will be sent without any refresh token (unless you use the approval_prompt=force option).

The refresh token you received the first time stays valid until the user revokes access permission.

In simplistic php, an example of the callback sequence would be:

// init client
// ...

$authCode = $_GET['code'];
$accessToken = $client->authenticate($authCode);
// $accessToken needs to be serialized as json
$this->saveAccessToken(json_encode($accessToken));
$this->saveRefreshToken($accessToken['refresh_token']);

And later on, in simplistic php, the connection sequence would be:

// init client
// ...

$accessToken = $this->loadAccessToken();
// setAccessToken() expects json
$client->setAccessToken($accessToken);

if ($client->isAccessTokenExpired()) {
    // reuse the same refresh token
    $client->refreshToken($this->loadRefreshToken());
    // save the new access token (which comes without any refresh token)
    $this->saveAccessToken($client->getAccessToken());
}

Generating a refresh token for YouTube API calls using the OAuth , public class GoogleRefreshTokenRequest extends RefreshTokenRequest. Google-specific implementation of the OAuth 2.0 request to refresh an access token� I am using googles official oauth2client.client to access the google plus api. I have a refresh token (that does not expire) stored in a database, and need to recreate the temporary "Credentials" (

Authenticate REST Requests - Firebase, Builder for GooglePublicKeysManager . GoogleRefreshTokenRequest. Google- specific implementation of the OAuth 2.0 request to refresh an access token using � The application should store the refresh token for future use and use the access token to access a Google API. Once the access token expires, the application uses the refresh token to obtain a new one. For details, see Using OAuth 2.0 for Installed Applications. Client-side (JavaScript) applications

GoogleRefreshTokenRequest (google-api-java-client 1.30.10), Some flows include additional steps, such as using refresh tokens to acquire Google supplies when you register your application (such as the client ID and the be accompanied by an identifier, which can be an API key or an access token. to get a code that was then sent to our Java backend to exchanges the code for a refresh_token. We use the google-api-client library (v 1.22.0) to verify the user's id_token that is returned upon initial sign in and then a REST call to get the refresh_token returned.

com.google.api.client.googleapis.auth.oauth2 (google-api-java , After a user grants offline access to the requested scopes, you can continue to use the API client to access Google APIs on the user's behalf when the user is offline. The client object will refresh the access token as needed. Ruby. If your application needs offline access to a Google API, set the API client's access type to offline:

Comments
  • Don't know if it's a bug or something but i'm currently refreshing the access token using a raw CURL http request and it's working fine.
  • Seorch... you figure this one out yet? Same issue here.
  • @gremo could you share the raw CURL http request you used here? Would be really helpful. Thanks!
  • Instead of checking for 3600 seconds, you should use $client->isAccessTokenExpired()
  • Small update. In the latest version, when you request a refresh token the new access token that is returned now comes with a new refresh token. So essentially, you can use the updated json token to replace the previous json token, and do not need to retain the initial access token any longer. .
  • Note that $client->isAccessTokenExpired() will still only check the times held locally to see if it thinks the token has expired. The token may still have expired and the local application will only really know when it tries to use it. In this case the API client will return an exception, and will not automatically refresh the token.
  • amazing mention, made my day! saved hours!
  • You saved my day !
  • I wish i could upvote this 100 times. I was about to make a hole into a wall with my keyboard after staring at "bad grant" message for several hours after trying absolutely everything to make the token work. Fricking google man, why use slashes, just why?
  • you made my day with this :) thank you very much, a lot more simple than i thought it would be as i have been spending a lot of time getting nowhere :D