Getting and using the token

This describes how to get and access token from the Goa library as described in Oauth2 for Apps Script in a few lines of code (which you should read first for background).

If you have initialized the credentials as described in Goa Setup, and gone through the process of the Goa Authentication dialog you are now ready to use the token or refreshed tokens with no further dialogs required. 

This example does a query using the reddit API.

getting the token


function reddit(params) {
       
  // pick up the token refreshing if necessary
  var goa =  cGoa.GoaApp.createGoa('reddit', PropertiesService.getScriptProperties()).execute(params);
  
  // This is a webapp, so your function should return the HtmlOutput result of your process
  if (!goa.hasToken()) {
    throw 'for a non webapp version - first publish once off to provoke a dialog - token will be refreshed automatically thereafter';
  }
  
  // do a test - passing the token and any parameters that arrived to this function
  Logger.log (testReddit (goa.getToken(), goa.getParams() ));
  

consuming the token


function testReddit (accessToken,params) {
 
   var options = {
     method: "GET",
     headers: {
       authorization: "Bearer " + accessToken
     }
   };

   return UrlFetchApp.fetch("https://oauth.reddit.com/api/v1/me", options);

}

The consent screen code

As described in Authentication dialog, you can simply leave the doGet() dialog in place instead of using this pattern, but using this simplified pattern allows you to unpublish the web app.

For more like this, see Oauth2 for Apps Script in a few lines of code. Why not join our forumfollow the blog or follow me on twitter to ensure you get updates when they are available. 

You want to learn Google Apps Script?

Learning Apps Script, (and transitioning from VBA) are covered comprehensively in my my book, Going Gas - from VBA to Apps script, All formats are available from O'ReillyAmazon and all good bookshops. You can also read a preview on O'Reilly

If you prefer Video style learning I also have two courses available. also published by O'Reilly.
Google Apps Script for Developers and Google Apps Script for Beginners.

Comments