Keeping the access token valid during API calls

1,935 views
Skip to first unread message

Danny

unread,
Feb 9, 2017, 3:21:14 PM2/9/17
to AdWords API Forum
Hi

I'm currently running into API call issues whenever my access token expires. I've already saved the client's refresh token and I'm trying to figure out whether AdWords will automatically renew the access token if you build the session with the OAuth2 object that contains the refresh token details.

Here's an example,

$this->oath2 = new OAuth2([
'authorizationUri' => self::AUTHORIZATION_URI,
'tokenCredentialUri' => CredentialsLoader::TOKEN_CREDENTIAL_URI,
'redirectUri' => self::BASE_URL . self::REDIRECT_PATH,
'clientId' => self::CLIENTID,
'clientSecret' => self::CLIENTSECRET,
'scope' => self::API_SCOPE
]);
$this->oauth2->setRefreshToken($refresh_token); // let's assume $refresh_token was retrieved from database
$this->session =
    (new AdWordsSessionBuilder())
    ->withDeveloperToken(self::DEVELOPER_TOKEN)
    ->withOAuth2Credential($this->oauth2)
         ->build();
// Make some API calls with AdWordsServices and $this->session

Based on the code snippet above, 
  1. Would AdWords automatically handle the expired access token, or  
  2. Do I have to explicitly check whether the access token is valid (via https://www.googleapis.com/oauth2/v3/tokeninfo) and if invalid, make a call (via https://www.googleapis.com/oauth2/v4/token) to get the new access token?
Thanks.

Shwetha Vastrad (AdWords API Team)

unread,
Feb 9, 2017, 4:16:37 PM2/9/17
to AdWords API Forum
Hi Danny,

You can check if the access token is about to expire and then refresh this token as needed. The OAuth2TokenRefresher.php provides functionality to retrieve OAuth2 access tokens and handling refreshing the token if it is going to expire. By default, the client libraries automatically refresh expired access tokens.

Regards,
Shwetha, AdWords API Team.

Danny

unread,
Feb 9, 2017, 7:52:13 PM2/9/17
to AdWords API Forum
Thanks - I'll look into that.

But could you also clarify whether the code snippet I shared would work, if I create the session with the OAuth2 object containing the refresh token?

Adam Haining

unread,
Feb 10, 2017, 12:35:46 AM2/10/17
to AdWords API Forum
I've tried all of this as well, and if I try to force renewing the token before it expires, it just gives me the current token.  Then after it expires, I just always get the message:
invalid_grant
Token has been expired or revoked.

Specific examples on how to do this would be greatly appreciated.  I've attempted using OAuth2TokenRefresher.php as well, no luck.  Thanks!

Danny

unread,
Feb 10, 2017, 3:07:31 AM2/10/17
to AdWords API Forum
Hi Adam

I "think" I might've solved my own issue with the solution I presented where the refresh token is set to the OAuth2 object, which is then passed to the AdWordsSessionBuilder. Based on this, I assume when you use the returned AdWordsSession object to make API calls (containing the refresh token via OAuth2), the API knows to automatically refresh the access token with the given refresh token, so you don't get API call errors due to expired access token.

Although my solution is a bit different, reading the README at https://github.com/googleads/googleads-php-lib and if you're not using adsapi_php.ini, have a look at OAuth2TokenBuilder.php, where you can build using withClientId(), withClientSecret() and withRefreshToken(), which I assume is then passed to AdWordsSessionBuilder.php via withOAuth2Credential() that you just created.

With some pseudo code, I'm guessing,

$oauth2 =(new OAuth2TokenBuilder())
   
->withClientId('client_id')  // replace with real values
   
->withClientSecret('client_secret')  
// replace with real values
   
->withRefreshToken('refresh_token')  
// replace with real values
   
->withScopes('scopes_urls')  
// replace with real values
    ->build();

$session = (new AdWordsSessionBuilder())
   
->withOAuth2Credential($oauth2)
   
->withDeveloperToken('dev_token')  
// replace with real values
   
->build();

// make API calls with $session based on
https://github.com/googleads/googleads-php-lib#basic-usage

The reason why I'm not using the adsapi_php.ini file is because I'm using the web application flow (not installed app).

Josh Averbeck

unread,
May 22, 2017, 1:03:44 AM5/22/17
to AdWords API Forum
Hi Danny, 

I'm running into the same problems with regenerating oauth2tokens using a refresh token. I tried your code but you have to remove scopes because that is only for installed application flow. It throws an error if you the scopes withScopes() method because of conflicts. Here's the code I have right now:

 
  $oauth2Token = (new OAuth2TokenBuilder())
     
->withClientId($clientId)
     
->withClientSecret($clientSecret)
     
->withRefreshToken($refreshToken)
     
->build();
    $adWordsSession
= (new AdWordsSessionBuilder())
     
->withOAuth2Credential($oauth2Token)
     
->withDeveloperToken($developerToken)
     
->build();


When I try to use that adWordsSession to make API calls, I get a bad request. The $oauth2Token doesn't contain an accessToken so I'm assuming it's not properly generating. Did you ever figure out a solution? It'd be nice if the web flow documentation was a bit better.

Shwetha Vastrad (AdWords API Team)

unread,
May 22, 2017, 2:12:59 PM5/22/17
to AdWords API Forum
Hi Josh, 

This guide provides an example on implementing OAuth2 authentication using web flow. Could you try using the code snippet provided in that guide to get your OAuth2 tokens? If this doesn't work, please provide the error message you receive so I can take a look. 

Josh Averbeck

unread,
May 25, 2017, 8:28:52 PM5/25/17
to AdWords API Forum
Hi Shwetha, 

My above code works, I actually had an error on my end but it works. The guide you linked to does not detail how to get a new oauth2 token and generate a new session using the user's refresh token. The code that I posted above does do just that though.

Thanks!

nazar pryymak

unread,
Oct 25, 2019, 6:20:24 AM10/25/19
to AdWords API and Google Ads API Forum
Hi Shwetha,

I have created ads test account and yesterday in response I have received response :
google.auth.exceptions.RefreshError: ('invalid_grant: Token has been expired or revoked.', '{\n  "error": "invalid_grant",\n  "error_description": "Token has been expired or revoked."\n}')

This error occured due to exceeded a maximum number of granted (live) refresh tokens ?

Could you help me to resolve mention issue ?

Google Ads API Forum Advisor Prod

unread,
Oct 25, 2019, 1:25:28 PM10/25/19
to nazar...@gmail.com, adwor...@googlegroups.com

Hi Nazar,

I am Nikisha from the Google Ads API team. If you are using our client libraries while making call to the API, it will automatically take care of refreshing the expired access tokens. The access token will be valid for only 3600 seconds after it is generated, so this might be a reason for you to face this error. Also, you are only allowed to generate 50 refresh tokens from an account, generating more than 50 refresh tokens will cause the oldest tokens to be revoked automatically. Could you please verify your refresh token, elaborate how are you creating them and accessing your account to help further? Could you try to generate a new refresh token using the instructions for the specific client library you are using and let me know if there are still issues?

Regards,
Nikisha Patel, Google Ads API Team



ref:_00D1U1174p._5001UKOTgj:ref

nazar pryymak

unread,
Oct 28, 2019, 9:02:14 AM10/28/19
to AdWords API and Google Ads API Forum
Hi Nikisha,

Thanks a lot for detailed answer.

I am using your library and getting GoogleAdsClient with data stored in the file according this example :

google.ads.google_ads.client.GoogleAdsClient.load_from_storage("root_to_yaml_file")

and I  was successfully running it previously.
Few days ago we started to run few instances of our aplication after that mention error occurred (but not sure if it is related to this issue).

Today I have tried to generate new refresh token for TEST account according to these instructions and with new refresh token I received another error:
google-ads-python/examples/basic_operations/get_campaigns.py
Request made: ClientCustomerId: <CLIENT_CUSTOMER_ID>, Host: googleads.googleapis.com:443, Method: /google.ads.googleads.v2.services.GoogleAdsService/Search, RequestId: None, IsFault: True, FaultMessage: Request had insufficient authentication scopes.

With old refresh token I have error :
google.auth.exceptions.RefreshError: ('invalid_grant: Token has been expired or revoked.', '{\n  "error": "invalid_grant",\n  "error_description": "Token has been expired or revoked."\n}')

Questions:
  1. It looks like that we were running few applications in parallel and all of them where automatically updating token via your lib. Is it possible that due to that refresh token was revoked?
  2. Do you know reason why new refresh token failing with error insufficient authentication scopes during getting campaings?
     
Thanks,
Br,
Nazar

Google Ads API Forum Advisor Prod

unread,
Oct 28, 2019, 11:27:34 AM10/28/19
to nazar...@gmail.com, adwor...@googlegroups.com

Hi Nazar,

Please find my response to your queries below:

  • It looks like that we were running few applications in parallel and all of them where automatically updating token via your lib. Is it possible that due to that refresh token was revoked? It might be possible that the refresh token was revoked because of this operation as you are only allowed to generate 50 refresh tokens from an account and generating more than 50 refresh tokens can cause the oldest token to be revoked automatically.

  • Do you know reason why new refresh token failing with error insufficient authentication scopes during getting campaigns? This error could be a result of one of the below scenarios where the scope, redirect URI and permissions are assigned. 
    • The email address should have standard or admin access to the account in order to make the API call. Could you please share the email address of the user using which the scopes are authorized and the client customer id using Reply privately to the author option?
    • Please confirm whether the client id and client secret are generated using the same email address and check whether the project in Google API Console Credentials page still exists. If yes, could you please check whether the authorized redirect URI is specified correctly as shown in step-5 here?
    • Also, could you please try adding those scope separated by comma "," and authorize again as shown in step-4 and 5 here with a valid user that is having access to the account?

Let us know if you need any further clarifications.



Regards,
Nikisha Patel, Google Ads API Team



ref:_00D1U1174p._5001UKOTgj:ref

Nazar Pryymak

unread,
Oct 29, 2019, 8:41:23 AM10/29/19
to AdWords API and Google Ads API Forum
Hi Nikisha,

I have replied to you privately with detailed information about accounts

Thanks,

Br,
Nazar

Google Ads API Forum Advisor Prod

unread,
Oct 29, 2019, 11:12:42 AM10/29/19
to adwor...@googlegroups.com

Hi Nazar,

We haven't received the response yet. Could you please retry sharing the requested information using Reply privately to author option for me to assist you better?



Regards,
Nikisha Patel, Google Ads API Team



ref:_00D1U1174p._5001UKOTgj:ref

Nazar Pryymak

unread,
Oct 29, 2019, 6:30:44 PM10/29/19
to AdWords API and Google Ads API Forum
Few minutes ago I resend it and received information that my message was sent (see screnshoot below ). Let me know iif you received my message privately :

Sirinart khongyadee

unread,
Oct 30, 2019, 11:02:01 AM10/30/19
to 'Nazar Pryymak' via AdWords API and Google Ads API Forum
Yes i​ got your​ email

ส่งจากโทรศัพท์มือถือ Huawei ของฉัน


-------- ข้อความต้นฉบับ --------
เรื่อง: Re: Keeping the access token valid during API calls
จาก: 'Nazar Pryymak' via AdWords API and Google Ads API Forum
ถึง: AdWords API and Google Ads API Forum
สำเนา:

Few minutes ago I resend it and received information that my message was sent (see screnshoot below ). Let me know iif you received my message privately :

--
--
=~=~=~=~=~=~=~=~=~=~=~=~=~=~=~=~=~=~=~=~=~=~=~=~
Also find us on our blog:
https://googleadsdeveloper.blogspot.com/
=~=~=~=~=~=~=~=~=~=~=~=~=~=~=~=~=~=~=~=~=~=~=~=~
 
You received this message because you are subscribed to the Google
Groups "AdWords API and Google Ads API Forum" group.
To post to this group, send email to adwor...@googlegroups.com
To unsubscribe from this group, send email to
adwords-api...@googlegroups.com
For more options, visit this group at
http://groups.google.com/group/adwords-api?hl=en
---
You received this message because you are subscribed to the Google Groups "AdWords API and Google Ads API Forum" group.
To unsubscribe from this group and stop receiving emails from it, send an email to adwords-api...@googlegroups.com.
To view this discussion on the web visit https://groups.google.com/d/msgid/adwords-api/2f3e8c17-f678-43c1-976e-0b70c27c2151%40googlegroups.com.

Deepa Varma

unread,
Dec 8, 2021, 7:29:58 AM12/8/21
to AdWords API and Google Ads API Forum
Hi Team,

    I am getting an error as follows when I am trying to call api sometimes. 

Client error: `POST https://www.googleapis.com/oauth2/v4/token` resulted in a `400 Bad Request` response:
{
  "error": "unsupported_grant_type",
  "error_description": "Invalid grant_type: "
}

It is not occuring in every api calls.  As some of the api calls are successfull, I believe that the refresh token is not revoked. 

Please help me figure out the issue.

Thank you for your help in advance. 

Google Ads API Forum Advisor

unread,
Dec 9, 2021, 3:29:05 AM12/9/21
to rdva...@gmail.com, adwor...@googlegroups.com

Hi Deepa,

Thanks for commenting on this forum thread.

Could you provide us with the complete request and response logs with the request-id, so our team can better check?

If you are using a client library, you may first enable logging by navigating to the Client libraries > Your client library (ex. Java) > Logging documentation, which you can access from this link. You may then send the requested information via the Reply privately to author option. If this option is not available, you may send the details directly to our googleadsa...@google.com alias instead.

Regards,

Google Logo
Yasar
Google Ads API Team
 


ref:_00D1U1174p._5004Q2Sd8me:ref
Reply all
Reply to author
Forward
0 new messages