|
| 1 | +/* |
| 2 | +* Zendesk OAuth Guide: |
| 3 | +* https://support.zendesk.com/hc/en-us/articles/203663836 |
| 4 | +*/ |
| 5 | + |
| 6 | +var CLIENT_ID = '...'; |
| 7 | +var CLIENT_SECRET = '...'; |
| 8 | +var SUBDOMAIN = '...' |
| 9 | + |
| 10 | +/** |
| 11 | + * Authorizes and makes a request to the Zendesk API. |
| 12 | + */ |
| 13 | +function run() { |
| 14 | + var service = getService(); |
| 15 | + if (service.hasAccess()) { |
| 16 | + var url = 'https://'.concat(SUBDOMAIN, '.zendesk.com/api/v2/tickets/recent.json'); |
| 17 | + var response = UrlFetchApp.fetch(url, { |
| 18 | + headers: { |
| 19 | + Authorization: 'Bearer ' + service.getAccessToken() |
| 20 | + } |
| 21 | + }); |
| 22 | + var result = JSON.parse(response.getContentText()); |
| 23 | + Logger.log(JSON.stringify(result, null, 2)); |
| 24 | + } else { |
| 25 | + var authorizationUrl = service.getAuthorizationUrl(); |
| 26 | + Logger.log('Open the following URL and re-run the script: %s', |
| 27 | + authorizationUrl); |
| 28 | + } |
| 29 | +} |
| 30 | + |
| 31 | +/** |
| 32 | + * Reset the authorization state, so that it can be re-tested. |
| 33 | + */ |
| 34 | +function reset() { |
| 35 | + var service = getService(); |
| 36 | + service.reset(); |
| 37 | +} |
| 38 | + |
| 39 | +/** |
| 40 | + * Configures the service. |
| 41 | + */ |
| 42 | +function getService() { |
| 43 | + return OAuth2.createService('Zendesk') |
| 44 | + // Set the endpoint URLs. |
| 45 | + .setAuthorizationBaseUrl('https://'.concat(SUBDOMAIN, '.zendesk.com/oauth/authorizations/new')) |
| 46 | + .setTokenUrl('https://'.concat(SUBDOMAIN, '.zendesk.com/oauth/tokens')) |
| 47 | + |
| 48 | + // Set scope (required by Zendesk) |
| 49 | + .setScope('read') |
| 50 | + |
| 51 | + // Set the client ID and secret. |
| 52 | + .setClientId(CLIENT_ID) |
| 53 | + .setClientSecret(CLIENT_SECRET) |
| 54 | + |
| 55 | + // Set the name of the callback function that should be invoked to complete |
| 56 | + // the OAuth flow. |
| 57 | + .setCallbackFunction('authCallback') |
| 58 | + |
| 59 | + // Set the property store where authorized tokens should be persisted. |
| 60 | + .setPropertyStore(PropertiesService.getUserProperties()) |
| 61 | +} |
| 62 | + |
| 63 | +/** |
| 64 | + * Handles the OAuth callback. |
| 65 | + */ |
| 66 | +function authCallback(request) { |
| 67 | + var service = getService(); |
| 68 | + var authorized = service.handleCallback(request); |
| 69 | + if (authorized) { |
| 70 | + return HtmlService.createHtmlOutput('Success!'); |
| 71 | + } else { |
| 72 | + return HtmlService.createHtmlOutput('Denied'); |
| 73 | + } |
| 74 | +} |
0 commit comments