Google Apps Script to Retrieve Access & Refresh Token For Google Drive API Full Project For Beginners

 

 

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

 

 

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

 

 

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);

Leave a Reply