Refresh token using google api returning invalid_r

2019-08-23 06:21发布

问题:

I am trying to refresh my expired token using the Google API following the instructions on https://developers.google.com/accounts/docs/OAuth2WebServer#refresh

So here is my code (python)

refresh_token = requests.post(
    'https://accounts.google.com/o/oauth2/token',
     headers={
        'Content-Type': 'application/x-www-form-urlencoded',
     },
     data=json.dumps({
         'client_id': APP_ID,
         'client_secret': APP_SECRET,
         'refresh_token': refresh_token,
         'grant_type': 'refresh_token',
     })
)

However, I am getting the response:

Status code: 400
{
  "error" : "invalid_request"
}

What am I doing wrong?

回答1:

You are telling the google server that your request is form-encoded when its actually json encoded. Requests will automatically form-encode your data if you give it a dict, so try this instead:

refresh_token = requests.post(
    'https://accounts.google.com/o/oauth2/token',
     data={
         'client_id': APP_ID,
         'client_secret': APP_SECRET,
         'refresh_token': refresh_token,
         'grant_type': 'refresh_token',
     }
)