@@ -12,23 +12,50 @@ var CLIENT_SECRET = '...';
1212function run ( ) {
1313 var service = getService ( ) ;
1414 if ( service . hasAccess ( ) ) {
15- // GET requests require access_token parameter
1615 var url = service . getToken ( ) . instance_url +
1716 '/services/data/v24.0/chatter/users/me' ;
18- var response = UrlFetchApp . fetch ( url , {
19- headers : {
20- Authorization : 'Bearer ' + service . getAccessToken ( )
21- }
17+ // Make the HTTP request using a wrapper function that handles expired
18+ // sessions.
19+ var response = withRetry ( service , function ( ) {
20+ return UrlFetchApp . fetch ( url , {
21+ headers : {
22+ Authorization : 'Bearer ' + service . getAccessToken ( ) ,
23+ }
24+ } ) ;
2225 } ) ;
2326 var result = JSON . parse ( response . getContentText ( ) ) ;
24- Logger . log ( JSON . stringify ( result , null , ' ' ) ) ;
27+ Logger . log ( JSON . stringify ( result , null , 2 ) ) ;
2528 } else {
2629 var authorizationUrl = service . getAuthorizationUrl ( ) ;
2730 Logger . log ( 'Open the following URL and re-run the script: %s' ,
2831 authorizationUrl ) ;
2932 }
3033}
3134
35+ /**
36+ * Wrapper function that detects an expired session, refreshes the access token,
37+ * and retries the request again.
38+ * @param {OAuth2.Service_ } service The service to refresh.
39+ * @param {Function } func The function that makes the UrlFetchApp request
40+ and returns the response.
41+ * @return {UrlFetchApp.HTTPResponse } The HTTP response.
42+ */
43+ function withRetry ( service , func ) {
44+ var response ;
45+ var content ;
46+ try {
47+ response = func ( ) ;
48+ content = response . getContentText ( ) ;
49+ } catch ( e ) {
50+ content = e . toString ( ) ;
51+ }
52+ if ( content . indexOf ( 'INVALID_SESSION_ID' ) !== - 1 ) {
53+ service . refresh ( ) ;
54+ return func ( ) ;
55+ }
56+ return response ;
57+ }
58+
3259/**
3360 * Reset the authorization state, so that it can be re-tested.
3461 */
@@ -55,7 +82,10 @@ function getService() {
5582 . setCallbackFunction ( 'authCallback' )
5683
5784 // Set the property store where authorized tokens should be persisted.
58- . setPropertyStore ( PropertiesService . getUserProperties ( ) ) ;
85+ . setPropertyStore ( PropertiesService . getUserProperties ( ) )
86+
87+ // Set the scopes to be requested.
88+ . setScope ( 'chatter_api refresh_token' ) ;
5989}
6090
6191/**
0 commit comments