Search code examples
javascriptgoogle-apps-scriptblogger

How to run the triggers in Google app script without reauth each time


Hello I have a script which is not a web app but it is an API based one it fetch data from json and sent them to blogger as post , and I am running this function with time based trigger , but after some run I need to open the auth url and get verification .. How can I avoid that and run the triggers continues This is the auth code

var service = getBloggerService_();

if (service.hasAccess()) {
var api ='https://www.googleapis.com/blogger/v3/blogs/' + blogId + '/posts/';

var headers = {
  'Authorization': 'Bearer ' + getBloggerService_().getAccessToken()
};

var options = {
  'headers': headers,
  'method' : 'post',
  'contentType': 'application/json',
  'payload': body,
  'muteHttpExceptions': false
};

try {
  var response = UrlFetchApp.fetch(api, options);

  var responseCode = response.getResponseCode();
  Logger.log(responseCode);
  var json = JSON.parse(response.getContentText());
  Logger.log(json);
}
catch(err) {
  Logger.log(err); // error with url fetch call
}
  }
else {
 var  authorizationUrll=service.getAuthorizationUrl();
 Logger.log('Open the following URL and 
re-run the script: %s',
    authorizationUrl);

} }


Solution

  • Solution:

    • Add the Blogger scope in appsscript.json manually.

      {
        ...
        "oauthScopes": [
          "https://www.googleapis.com/auth/blogger",
          "https://www.googleapis.com/auth/script.external_request"
        ],
        ...
      }
      
    • You can then use:

      var headers = {
        'Authorization': 'Bearer ' + ScriptApp.getOAuthToken(); //contains Blogger scope always
      };
      
    • You don't need to use service or any other library.

    References: