|
| 1 | +/* |
| 2 | + * This sample demonstrates how to configure the library for the Etsy API. |
| 3 | + * Instructions on how to generate OAuth credentials is available here: |
| 4 | + * https://developers.etsy.com/documentation/essentials/authentication |
| 5 | + */ |
| 6 | + |
| 7 | +const CLIENT_ID = '...'; |
| 8 | +const CLIENT_SECRET = '...'; |
| 9 | + |
| 10 | + |
| 11 | +/** |
| 12 | + * Authorizes and makes a request to the Etsy API. |
| 13 | + */ |
| 14 | +function run() { |
| 15 | + var service = getService_(); |
| 16 | + if (service.hasAccess()) { |
| 17 | + var url = 'https://openapi.etsy.com/v3/application/users/me'; // Replace with the appropriate Etsy API endpoint |
| 18 | + var settings = { |
| 19 | + method: 'GET', |
| 20 | + headers: { 'Content-Type': 'application/json', "Authorization": 'Bearer ' + service.getAccessToken(), 'x-api-key': CLIENT_ID } |
| 21 | + }; |
| 22 | + |
| 23 | + var response = UrlFetchApp.fetch(url, settings); |
| 24 | + var result = JSON.parse(response.getContentText()); |
| 25 | + Logger.log(JSON.stringify(result, null, 2)); |
| 26 | + } else { |
| 27 | + Logger.log(service.getLastError()); |
| 28 | + } |
| 29 | + } |
| 30 | + |
| 31 | +/** |
| 32 | + * Configures the service. |
| 33 | + */ |
| 34 | +function getService_() { |
| 35 | + var userProps = PropertiesService.getUserProperties(); |
| 36 | + |
| 37 | + return OAuth2.createService('Etsy') |
| 38 | + .setAuthorizationBaseUrl('https://www.etsy.com/oauth/connect') |
| 39 | + .setTokenUrl('https://api.etsy.com/v3/public/oauth/token') |
| 40 | + .setClientId(CLIENT_ID) |
| 41 | + .setClientSecret(CLIENT_SECRET) |
| 42 | + .setCallbackFunction('authCallback') |
| 43 | + .setPropertyStore(userProps) |
| 44 | + // Etsy requires the scope to access data |
| 45 | + .setScope('shops_r') |
| 46 | + .setParam('response_type', 'code') |
| 47 | + // Generate the PKCE parameters automatically |
| 48 | + .generateCodeVerifier() |
| 49 | + .setTokenPayloadHandler(function(tokenPayload) { |
| 50 | + // No need to manually set code_verifier here, |
| 51 | + // generateCodeVerifier() takes care of it. |
| 52 | + return tokenPayload; |
| 53 | + }); |
| 54 | +} |
| 55 | + |
| 56 | +function authCallback(request) { |
| 57 | + var service = getService_(); |
| 58 | + |
| 59 | + var authorized = service.handleCallback(request); |
| 60 | + if (authorized) { |
| 61 | + return HtmlService.createHtmlOutput('Success!'); |
| 62 | + } else { |
| 63 | + return HtmlService.createHtmlOutput('Denied.'); |
| 64 | + } |
| 65 | +} |
| 66 | + |
| 67 | +/** |
| 68 | + * Reset the authorization state, so that it can be re-tested. |
| 69 | + */ |
| 70 | +function resetAuth() { |
| 71 | + PropertiesService.getUserProperties().deleteAllProperties(); |
| 72 | +} |
0 commit comments