Class StateTokenBuilder

StateTokenBuilder

Allows scripts to create state tokens that can be used in callback APIs (like OAuth flows).

 

 // Reusable function to generate a callback URL, assuming the script has been published as a
 // web app (necessary to obtain the URL programmatically). If the script has not been published
 // as a web app, set `var url` in the first line to the URL of your script project (which
 // cannot be obtained programmatically).
 function getCallbackURL(callbackFunction){
   var url = ScriptApp.getService().getUrl();      // Ends in /exec (for a web app)
   url = url.slice(0, -4) + 'usercallback?state='; // Change /exec to /usercallback
   var stateToken = ScriptApp.newStateToken()
       .withMethod(callbackFunction)
       .withTimeout(120)
       .createToken();
   return url + stateToken;
 }
 

Methods

MethodReturn typeBrief description
createToken()StringConstructs an encrypted string representation of the state token.
withArgument(name, value)StateTokenBuilderAdds an argument to the token.
withMethod(method)StateTokenBuilderSets a callback function.
withTimeout(seconds)StateTokenBuilderSets the duration (in seconds) for which the token is valid.

Detailed documentation

createToken()

Constructs an encrypted string representation of the state token.

 

 var stateToken = ScriptApp.newStateToken().createToken();
 

Return

String — an encrypted string representing the token


withArgument(name, value)

Adds an argument to the token. This method can be called multiple times.

 

 var stateToken = ScriptApp.newStateToken().withArgument('myField', 'myValue').createToken();
 

Parameters

NameTypeDescription
nameStringthe name of the argument
valueStringthe value of the argument

Return

StateTokenBuilder — the state token builder, for chaining


withMethod(method)

Sets a callback function. The default is a function named callback().

 

 var stateToken = ScriptApp.newStateToken().withMethod('myCallback').createToken();
 

Parameters

NameTypeDescription
methodStringthe name of the callback function, represented as a string without parentheses or arguments

Return

StateTokenBuilder — the state token builder, for chaining


withTimeout(seconds)

Sets the duration (in seconds) for which the token is valid. The defaults is 60 seconds; the maximum duration is 3600 seconds (1 hour).

 

 var stateToken = ScriptApp.newStateToken().withTimeout(60).createToken();
 

Parameters

NameTypeDescription
secondsIntegerthe duration for which the token is valid; the maximum value is 3600

Return

StateTokenBuilder — the state token builder, for chaining

发送以下问题的反馈:

此网页
Apps Script
Apps Script