@@ -42,13 +42,15 @@ the menu item "File > Project properties".
42
42
Alternatively you can call the service's ` getRedirectUri() ` method to view the
43
43
exact URL that the service will use when performing the OAuth flow:
44
44
45
- /**
46
- * Logs the redict URI to register.
47
- */
48
- function logRedirectUri() {
49
- var service = getService();
50
- Logger.log(service.getRedirectUri());
51
- }
45
+ ``` js
46
+ /**
47
+ * Logs the redict URI to register.
48
+ */
49
+ function logRedirectUri () {
50
+ var service = getService ();
51
+ Logger .log (service .getRedirectUri ());
52
+ }
53
+ ```
52
54
53
55
## Usage
54
56
@@ -62,64 +64,68 @@ information is not persisted to any data store, so you'll need to create this
62
64
object each time you want to use it. The example below shows how to create a
63
65
service for the Google Drive API.
64
66
65
- function getDriveService() {
66
- // Create a new service with the given name. The name will be used when
67
- // persisting the authorized token, so ensure it is unique within the
68
- // scope of the property store.
69
- return OAuth2.createService('drive')
67
+ ``` js
68
+ function getDriveService () {
69
+ // Create a new service with the given name. The name will be used when
70
+ // persisting the authorized token, so ensure it is unique within the
71
+ // scope of the property store.
72
+ return OAuth2 .createService (' drive' )
70
73
71
- // Set the endpoint URLs, which are the same for all Google services.
72
- .setAuthorizationBaseUrl('https://accounts.google.com/o/oauth2/auth')
73
- .setTokenUrl('https://accounts.google.com/o/oauth2/token')
74
+ // Set the endpoint URLs, which are the same for all Google services.
75
+ .setAuthorizationBaseUrl (' https://accounts.google.com/o/oauth2/auth' )
76
+ .setTokenUrl (' https://accounts.google.com/o/oauth2/token' )
74
77
75
- // Set the client ID and secret, from the Google Developers Console.
76
- .setClientId('...')
77
- .setClientSecret('...')
78
+ // Set the client ID and secret, from the Google Developers Console.
79
+ .setClientId (' ...' )
80
+ .setClientSecret (' ...' )
78
81
79
- // Set the name of the callback function in the script referenced
80
- // above that should be invoked to complete the OAuth flow.
81
- .setCallbackFunction('authCallback')
82
+ // Set the name of the callback function in the script referenced
83
+ // above that should be invoked to complete the OAuth flow.
84
+ .setCallbackFunction (' authCallback' )
82
85
83
- // Set the property store where authorized tokens should be persisted.
84
- .setPropertyStore(PropertiesService.getUserProperties())
86
+ // Set the property store where authorized tokens should be persisted.
87
+ .setPropertyStore (PropertiesService .getUserProperties ())
85
88
86
- // Set the scopes to request (space-separated for Google services).
87
- .setScope('https://www.googleapis.com/auth/drive')
89
+ // Set the scopes to request (space-separated for Google services).
90
+ .setScope (' https://www.googleapis.com/auth/drive' )
88
91
89
- // Below are Google-specific OAuth2 parameters.
92
+ // Below are Google-specific OAuth2 parameters.
90
93
91
- // Sets the login hint, which will prevent the account chooser screen
92
- // from being shown to users logged in with multiple accounts.
93
- .setParam('login_hint', Session.getActiveUser().getEmail())
94
+ // Sets the login hint, which will prevent the account chooser screen
95
+ // from being shown to users logged in with multiple accounts.
96
+ .setParam (' login_hint' , Session .getActiveUser ().getEmail ())
94
97
95
- // Requests offline access.
96
- .setParam('access_type', 'offline')
98
+ // Requests offline access.
99
+ .setParam (' access_type' , ' offline' )
97
100
98
- // Forces the approval prompt every time. This is useful for testing,
99
- // but not desirable in a production application.
100
- .setParam('approval_prompt', 'force');
101
- }
101
+ // Forces the approval prompt every time. This is useful for testing,
102
+ // but not desirable in a production application.
103
+ .setParam (' approval_prompt' , ' force' );
104
+ }
105
+ ```
102
106
103
107
### 2. Direct the user to the authorization URL
104
108
105
109
Apps Script UI's are not allowed to redirect the user's window to a new URL, so
106
110
you'll need to present the authorization URL as a link for the user to click.
107
111
The URL is generated by the service, using the function ` getAuthorizationUrl() ` .
108
112
109
- function showSidebar() {
110
- var driveService = getDriveService();
111
- if (!driveService.hasAccess()) {
112
- var authorizationUrl = driveService.getAuthorizationUrl();
113
- var template = HtmlService.createTemplate(
114
- '<a href="<?= authorizationUrl ?>" target="_blank">Authorize</a>. ' +
115
- 'Reopen the sidebar when the authorization is complete.');
116
- template.authorizationUrl = authorizationUrl;
117
- var page = template.evaluate();
118
- DocumentApp.getUi().showSidebar(page);
119
- } else {
120
- ...
121
- }
122
- }
113
+ ``` js
114
+ function showSidebar () {
115
+ var driveService = getDriveService ();
116
+ if (! driveService .hasAccess ()) {
117
+ var authorizationUrl = driveService .getAuthorizationUrl ();
118
+ var template = HtmlService .createTemplate (
119
+ ' <a href="<?= authorizationUrl ?>" target="_blank">Authorize</a>. ' +
120
+ ' Reopen the sidebar when the authorization is complete.' );
121
+ template .authorizationUrl = authorizationUrl;
122
+ var page = template .evaluate ();
123
+ DocumentApp .getUi ().showSidebar (page);
124
+ } else {
125
+ // ...
126
+ }
127
+ }
128
+ ```
123
129
124
130
### 3. Handle the callback
125
131
@@ -128,15 +134,17 @@ for your service will be invoked. This callback function should pass its
128
134
request object to the service's ` handleCallback ` function, and show a message
129
135
to the user.
130
136
131
- function authCallback(request) {
132
- var driveService = getDriveService();
133
- var isAuthorized = driveService.handleCallback(request);
134
- if (isAuthorized) {
135
- return HtmlService.createHtmlOutput('Success! You can close this tab.');
136
- } else {
137
- return HtmlService.createHtmlOutput('Denied. You can close this tab');
138
- }
139
- }
137
+ ``` js
138
+ function authCallback (request ) {
139
+ var driveService = getDriveService ();
140
+ var isAuthorized = driveService .handleCallback (request);
141
+ if (isAuthorized) {
142
+ return HtmlService .createHtmlOutput (' Success! You can close this tab.' );
143
+ } else {
144
+ return HtmlService .createHtmlOutput (' Denied. You can close this tab' );
145
+ }
146
+ }
147
+ ```
140
148
141
149
If the authorization URL was opened by the Apps Script UI (via a link, button, etc)
142
150
it's possible to automatically close the window/tab using ` window.top.close() ` .
@@ -149,15 +157,17 @@ Now that the service is authorized you can use its access token to make
149
157
reqests to the API. The access token can be passed along with a ` UrlFetchApp `
150
158
request in the "Authorization" header.
151
159
152
- function makeRequest() {
153
- var driveService = getDriveService();
154
- var response = UrlFetchApp.fetch('https://www.googleapis.com/drive/v2/files?maxResults=10', {
155
- headers: {
156
- Authorization: 'Bearer ' + driveService.getAccessToken()
157
- }
158
- });
159
- ...
160
+ ``` js
161
+ function makeRequest () {
162
+ var driveService = getDriveService ();
163
+ var response = UrlFetchApp .fetch (' https://www.googleapis.com/drive/v2/files?maxResults=10' , {
164
+ headers: {
165
+ Authorization: ' Bearer ' + driveService .getAccessToken ()
160
166
}
167
+ });
168
+ // ...
169
+ }
170
+ ```
161
171
162
172
## Compatiblity
163
173
@@ -174,11 +184,13 @@ If you have an access token set and need to remove it from the property store
174
184
you can remove it with the ` reset() ` function. Before you can call reset you
175
185
need to set the property store.
176
186
177
- function clearService(){
178
- OAuth2.createService('drive')
187
+ ``` js
188
+ function clearService (){
189
+ OAuth2 .createService (' drive' )
179
190
.setPropertyStore (PropertiesService .getUserProperties ())
180
191
.reset ();
181
- }
192
+ }
193
+ ```
182
194
183
195
#### Setting the token format
184
196
@@ -195,18 +207,21 @@ header on access token requests. The `setTokenHeaders()` method allows you
195
207
to pass in a JavaScript object of additional header key/value pairs to be used
196
208
in these requests.
197
209
198
- .setTokenHeaders({
199
- 'Authorization': 'Basic ' + Utilities.base64Encode(CLIENT_ID + ':' + CLIENT_SECRET)
200
- });
210
+ ``` js
211
+ .setTokenHeaders ({
212
+ ' Authorization' : ' Basic ' + Utilities .base64Encode (CLIENT_ID + ' :' + CLIENT_SECRET )
213
+ });
214
+ ```
201
215
202
216
See the [ FitBit sample] ( samples/FitBit.gs ) for the complete code.
203
217
204
218
#### Modifying the access token payload
205
219
Similar to Setting additional token headers, some services, such as the Smartsheet API, require you to [ add a hash to the access token request payloads] ( http://smartsheet-platform.github.io/api-docs/?javascript#oauth-flow ) . The ` setTokenPayloadHandler ` method allows you to pass in a function to modify the payload of an access token request before the request is sent to the token endpoint:
206
220
207
-
208
- // Set the handler for modifying the access token request payload:
209
- .setTokenPayloadHandler(myTokenHandler)
221
+ ``` js
222
+ // Set the handler for modifying the access token request payload:
223
+ .setTokenPayloadHandler (myTokenHandler)
224
+ ```
210
225
211
226
See the [ Smartsheet sample] ( samples/Smartsheet.gs ) for the complete code.
212
227
0 commit comments