Retrieving Access Token for Google Drive API using GAS

These GASs retrieve an access token for using Google Drive API. There are 3 parts. Before you use this, please retrieve client ID, client secret and redirect uri from Google , and choose scopes.

1. Retrieving code from web

This is a script to output URL for retrieving “code” from web. Please retrieve “code” by import this URL to your browser. After you run this script, using “url” got from this script, it retrieves “code”.

  var url = 'https://accounts.google.com/o/oauth2/auth' +
        "?client_id=" + encodeURIComponent(clientid) +
        "&redirect_uri=" + encodeURIComponent(redirecturi) +
        "&scope=" + encodeURIComponent(scopes) +
        "&response_type=code&access_type=offline";
  Logger.log(url);

2. Retrieving refresh token

This is a script to retrieve “refresh token”. Before you run this script, it sets “code” got at part 1. By this script, you can also retrieve “access token”. Also this “access token” can be used. But there is a limit time for it. So you have to retrieve “access token” again. At that time, “refresh token” is need to it. According to “golang.org/x/oauth2”, it uses “refresh token” every time without using the limit time of access token. So this script can be used to only retrieve “refresh token”.

  var token = JSON.parse(UrlFetchApp.fetch("https://accounts.google.com/o/oauth2/token", {
    "method" : "POST",
    "payload" : {
      "code" : code,
      "client_id" : clientid,
      "client_secret" : clientsecret,
      "redirect_uri" : redirecturi,
      "grant_type" : "authorization_code"
    },
    "muteHttpExceptions" : true
  }).getContentText());
  Logger.log(token.refresh_token);

3. Retrieving access token

This is a script to retrieve “access token” using “refresh token”. Before you run this script, it sets “refresh token” got at part 2. When you use Drive API, the “access token” can be retrieved by this script. You can continue to use “refresh token” got at part 2, until it’s revoked.

  var token = JSON.parse(UrlFetchApp.fetch("https://www.googleapis.com/oauth2/v4/token", {
    "method" : "POST",
    "payload" : {
      "client_id" : clientid,
      "client_secret" : clientsecret,
      "refresh_token" :refreshtoken,
      "grant_type" : "refresh_token"
    },
    "muteHttpExceptions" : true
  }).getContentText());
  Logger.log(token.access_token);

 Share!