Search code examples
oauth-2.0oauthgoogle-oauthgoogle-ads-apirefresh-token

How To Generate Google API oAuth Refresh Token with REST API


I've been using 2 REST API calls to batch upload google offline click conversions. One generates the Access Token. The other is the API call to upload the offline click conversions.

All was well for a few weeks until suddenly we started getting invalid_grant messages in the JSON when trying to generate the Access Token. No clue why -- and we received no email or anything from Google on this. It just stopped working and the invalid_grant error was cryptic and the online help didn't explain much.

I resolved this issue by following this video to generate a new Refresh Token in the Google oAuth Playground:

https://youtu.be/KFICa7Ngzng

So, my question is -- can we automate this somehow? I can trap the invalid_grant JSON response and then would like to do some series of REST API calls to generate a new Refresh Token. Or, would I need to switch from a Web Application Type to a Service Account Type on the oAuth?

I also researched what might have caused the Refresh Token to expire. I looked at the following page and none of those bullet items applied to my situation:

https://developers.google.com/identity/protocols/oauth2#expiration


Solution

  • The answer is that it's not possible in code. One can use a Service Account, instead. The problem with a service account, however, is that Google says it isn't a recommended route because of difficulty of setup and security risks. Google Support couldn't really nail down for me why my oAuth Refresh Token broke. I would have to switch to paid support to troubleshoot that, which I didn't do. I assume it was because the Refresh Token was extremely old -- like 2 years old. However, I added code in my Access Token API calls to look for invalid_grant. When I receive it next time, I coded things so that it sends me an email so that I can do the process to reset the client keys and then go through the oAuth Consent Screen again to generate the next Refresh Token. I don't expect that to expire for another year or two.

    (Note, in my original question, I may have given the impression that the Refresh Token was only a couple weeks old. This was incorrect. What I mean is that another coder, no longer with my company, created the first code project and generated a Refresh Token a couple years ago and kept it in a config file. I used that and then rewrote the code from SOAP into HTTP REST, and used the same Refresh Token until it finally just stopped working. But then I created a new Refresh Token manually and all was well again.)