Skip to content

Commit ca07dfd

Browse files
author
Eric Koleda
authored
Merge pull request #63 from grant/master
Add syntax highlighting for README code samples
2 parents 90e8af6 + 5c275ea commit ca07dfd

File tree

1 file changed

+90
-75
lines changed

1 file changed

+90
-75
lines changed

README.md

Lines changed: 90 additions & 75 deletions
Original file line numberDiff line numberDiff line change
@@ -42,13 +42,15 @@ the menu item "File > Project properties".
4242
Alternatively you can call the service's `getRedirectUri()` method to view the
4343
exact URL that the service will use when performing the OAuth flow:
4444

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+
```
5254

5355
## Usage
5456

@@ -62,64 +64,68 @@ information is not persisted to any data store, so you'll need to create this
6264
object each time you want to use it. The example below shows how to create a
6365
service for the Google Drive API.
6466

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')
7073

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')
7477

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('...')
7881

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')
8285

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())
8588

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')
8891

89-
// Below are Google-specific OAuth2 parameters.
92+
// Below are Google-specific OAuth2 parameters.
9093

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())
9497

95-
// Requests offline access.
96-
.setParam('access_type', 'offline')
98+
// Requests offline access.
99+
.setParam('access_type', 'offline')
97100

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+
```
102106

103107
### 2. Direct the user to the authorization URL
104108

105109
Apps Script UI's are not allowed to redirect the user's window to a new URL, so
106110
you'll need to present the authorization URL as a link for the user to click.
107111
The URL is generated by the service, using the function `getAuthorizationUrl()`.
108112

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+
```
123129

124130
### 3. Handle the callback
125131

@@ -128,15 +134,17 @@ for your service will be invoked. This callback function should pass its
128134
request object to the service's `handleCallback` function, and show a message
129135
to the user.
130136

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+
```
140148

141149
If the authorization URL was opened by the Apps Script UI (via a link, button, etc)
142150
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
149157
reqests to the API. The access token can be passed along with a `UrlFetchApp`
150158
request in the "Authorization" header.
151159

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()
160166
}
167+
});
168+
// ...
169+
}
170+
```
161171

162172
## Compatiblity
163173

@@ -174,11 +184,13 @@ If you have an access token set and need to remove it from the property store
174184
you can remove it with the `reset()` function. Before you can call reset you
175185
need to set the property store.
176186

177-
function clearService(){
178-
OAuth2.createService('drive')
187+
```js
188+
function clearService(){
189+
OAuth2.createService('drive')
179190
.setPropertyStore(PropertiesService.getUserProperties())
180191
.reset();
181-
}
192+
}
193+
```
182194

183195
#### Setting the token format
184196

@@ -195,18 +207,21 @@ header on access token requests. The `setTokenHeaders()` method allows you
195207
to pass in a JavaScript object of additional header key/value pairs to be used
196208
in these requests.
197209

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+
```
201215

202216
See the [FitBit sample](samples/FitBit.gs) for the complete code.
203217

204218
#### Modifying the access token payload
205219
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:
206220

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+
```
210225

211226
See the [Smartsheet sample](samples/Smartsheet.gs) for the complete code.
212227

0 commit comments

Comments
 (0)