|
| 1 | +var PRIVATE_KEY = '...'; |
| 2 | +var CLIENT_EMAIL = '...'; |
| 3 | +var USER_EMAIL = '...'; |
| 4 | + |
| 5 | +/** |
| 6 | + * Authorizes and makes a request to the Google+ API. |
| 7 | + */ |
| 8 | +function run() { |
| 9 | + var service = getService(); |
| 10 | + if (service.hasAccess()) { |
| 11 | + var url = 'https://www.googleapis.com/drive/v2/files?pageSize=1'; |
| 12 | + var response = UrlFetchApp.fetch(url, { |
| 13 | + headers: { |
| 14 | + Authorization: 'Bearer ' + service.getAccessToken() |
| 15 | + } |
| 16 | + }); |
| 17 | + var result = JSON.parse(response.getContentText()); |
| 18 | + Logger.log(JSON.stringify(result, null, 2)); |
| 19 | + } else { |
| 20 | + Logger.log(service.getLastError()); |
| 21 | + } |
| 22 | +} |
| 23 | + |
| 24 | +/** |
| 25 | + * Reset the authorization state, so that it can be re-tested. |
| 26 | + */ |
| 27 | +function reset() { |
| 28 | + var service = getService(); |
| 29 | + service.reset(); |
| 30 | +} |
| 31 | + |
| 32 | +/** |
| 33 | + * Configures the service. |
| 34 | + */ |
| 35 | +function getService() { |
| 36 | + return OAuth2.createService('GoogleDrive:' + USER_EMAIL) |
| 37 | + // Set the endpoint URL. |
| 38 | + .setTokenUrl('https://accounts.google.com/o/oauth2/token') |
| 39 | + |
| 40 | + // Set the private key and issuer. |
| 41 | + .setPrivateKey(PRIVATE_KEY) |
| 42 | + .setIssuer(CLIENT_EMAIL) |
| 43 | + |
| 44 | + // Set the name of the user to impersonate. This will only work for |
| 45 | + // Google Apps for Work/EDU accounts whose admin has setup domain-wide |
| 46 | + // delegation: |
| 47 | + // https://developers.google.com/identity/protocols/OAuth2ServiceAccount#delegatingauthority |
| 48 | + .setSubject(USER_EMAIL) |
| 49 | + |
| 50 | + // Set the property store where authorized tokens should be persisted. |
| 51 | + .setPropertyStore(PropertiesService.getScriptProperties()) |
| 52 | + |
| 53 | + // Set the scope and additional Google-specific parameters. |
| 54 | + .setScope('https://www.googleapis.com/auth/drive'); |
| 55 | +} |
0 commit comments