|
| 1 | +/** |
| 2 | + * Demonstrates how to authorize access to the UltraCart API. |
| 3 | + * @see https://www.ultracart.com/api/#resource_oauth.html |
| 4 | + */ |
| 5 | + |
| 6 | +var CLIENT_ID = '...'; |
| 7 | +var CLIENT_SECRET = '...'; |
| 8 | + |
| 9 | +/** |
| 10 | + * Authorizes and makes a request to the UltraCart API. |
| 11 | + */ |
| 12 | +function run() { |
| 13 | + var service = getService(); |
| 14 | + if (service.hasAccess()) { |
| 15 | + var url = 'https://secure.ultracart.com/rest/v2/customer/customers'; |
| 16 | + var response = UrlFetchApp.fetch(url, { |
| 17 | + headers: { |
| 18 | + 'Authorization': 'Bearer ' + service.getAccessToken(), |
| 19 | + 'X-UltraCart-Api-Version': '2017-03-01' |
| 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 | + getService().reset(); |
| 36 | +} |
| 37 | + |
| 38 | +/** |
| 39 | + * Configures the service. |
| 40 | + */ |
| 41 | +function getService() { |
| 42 | + return OAuth2.createService('UltaCart') |
| 43 | + // Set the endpoint URLs. |
| 44 | + .setAuthorizationBaseUrl('https://secure.ultracart.com/rest/v2/oauth/authorize') |
| 45 | + .setTokenUrl('https://secure.ultracart.com/rest/v2/oauth/token') |
| 46 | + |
| 47 | + // Set the client ID and secret. |
| 48 | + .setClientId(CLIENT_ID) |
| 49 | + .setClientSecret(CLIENT_SECRET) |
| 50 | + |
| 51 | + // Set the name of the callback function that should be invoked to |
| 52 | + // complete the OAuth flow. |
| 53 | + .setCallbackFunction('authCallback') |
| 54 | + |
| 55 | + // Set the property store where authorized tokens should be persisted. |
| 56 | + .setPropertyStore(PropertiesService.getUserProperties()); |
| 57 | +} |
| 58 | + |
| 59 | +/** |
| 60 | + * Handles the OAuth callback. |
| 61 | + */ |
| 62 | +function authCallback(request) { |
| 63 | + var service = getService(); |
| 64 | + var authorized = service.handleCallback(request); |
| 65 | + if (authorized) { |
| 66 | + return HtmlService.createHtmlOutput('Success!'); |
| 67 | + } else { |
| 68 | + return HtmlService.createHtmlOutput('Denied'); |
| 69 | + } |
| 70 | +} |
| 71 | + |
| 72 | +/** |
| 73 | + * Logs the redict URI to register. |
| 74 | + */ |
| 75 | +function logRedirectUri() { |
| 76 | + Logger.log(getService().getRedirectUri()); |
| 77 | +} |
0 commit comments