1
votes

I am attempting to retrieve an access token using my refresh token, client id and client secret for the youtube api using R Code.

This is google's example of how to POST a request.

POST /o/oauth2/token HTTP/1.1 Host: accounts.google.com Content-Type: application/x-www-form-urlencoded client_id=21302922996.apps.googleusercontent.com&client_secret=XTHhXh1SlUNgvyWGwDk1EjXB&refresh_token=1/6BMfW9j53gdGImsixUH6kU5RsR4zwI9lUVX-tqf8JXQ&grant_type=refresh_token

This was my r code: library(httr)

url<- paste("https://accounts.google.com/o/oauth2/token?client_id=", client_id, "&client_secret=", client_secret, "&refresh_token=", refresh_token, "&grant_type=access_token", sep="")
POST(url)

And I keep getting this response:

Response [https://accounts.google.com/o/oauth2/token?client_id=xxxxxxxxxx&client_secret=xxxxxxxx&refresh_token=xxxxxxxxxxxxxxxxxxxxxx&grant_type=refresh_token]

Date: 2015-09-02 16:43

Status: 400

Content-Type: application/json

Size: 102 B

{ "error" : "invalid_request", "error_description" : "Required parameter is missing: grant_type"

Is there a better way to do this? Maybe using RCurl? If so, what would the format of the request be? I would appreciate help on this!

1

1 Answers

0
votes

The RAdwords package has a function to retrieve the refresh token. If you don't want to add the entire package you can just add the following code to your script.

refreshToken = function(google_auth) {
  # This function refreshes the access token. 
  # The access token deprecates after one hour and has to updated 
  # with the refresh token.
  #
  # Args:
  #   access.token$refreh_token and credentials as input
  # Returns:
  #   New access.token with corresponding time stamp

    rt = rjson::fromJSON(RCurl::postForm('https://accounts.google.com/o/oauth2/token', 
                           refresh_token=google_auth$access$refresh_token, 
                           client_id=google_auth$credentials$c.id,
                           client_secret=google_auth$credentials$c.secret, 
                           grant_type="refresh_token", 
                           style="POST",
                           .opts = list(ssl.verifypeer = FALSE)))
    access <- rt

    access
}