Setting an alternative ontoken callback

This describes how to call another function when a token has been received while using the Goa library as described in Oauth2 for Apps Script in a few lines of code (which you should read first for background).

The library, cGoa, is available under this project key.


Normal pattern

The normal pattern for a webapp type OAuth2 flow is to check if consent is needed with goa.needsConsent() , and if so to return goa.getConsent() for processing by your doGet/doPost function. When a token is received either through this consent or by refreshing a token without the need for a dialog, the flow continues transparently in your doGet servicing function. 

Alternative onToken call back. 

You might be preferable just to call some function when a token is detected. Goa allows the setting of an callback when a token is eventually received like this.
  var goa = cGoa.GoaApp.createGoa('githubgoa',PropertiesService.getScriptProperties())
    .setOnToken (function(token,packageName,args) {
      return 'token:' + token + ' packagename:' + packageName +' args:' + JSON.stringify(args);

This example uses an anonymous function, called when the token process is completed. It  receives the token , the name of the credentials package and any arguments originally present when the Goa process started. 

Equally this could have been a regular named function.
function callMeWhenYouHaveAToken ( token , packageName , myArgs) {
  return 'token:' + token + ' packagename:' + packageName +' args:' + JSON.stringify(args);

function doGet (e) {
  var goa = cGoa.GoaApp.createGoa('githubgoa',PropertiesService.getScriptProperties())
    .setOnToken (callMeWhenYouHaveAToken)
  // .... etc...


A note on arguments and lexical scoping

Any  arguments handled in this way must be stringifiable objects - remember that could be passed to an entirely different instance of your app so are reinitialized. Similarly, anonymous functions can't rely on lexical scoping to inherit values for the same reason. 

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.