Skip to content

Instantly share code, notes, and snippets.

@wendeehsu
Created November 18, 2021 15:12
Show Gist options
  • Save wendeehsu/1df4505c09cb9346f0c3be1b64dff7bb to your computer and use it in GitHub Desktop.
Save wendeehsu/1df4505c09cb9346f0c3be1b64dff7bb to your computer and use it in GitHub Desktop.
// refer to: https://github.com/googleworkspace/apps-script-oauth2/blob/master/samples/Google.gs
var CLIENT_ID = 'YOUR_CLIENT_ID';
var CLIENT_SECRET = 'YOUR_CLIENT_SECRET';
/**
* Authorizes and makes a request to the Google Drive API.
*/
function run() {
var service = getService();
if (service.hasAccess()) {
var url = 'https://mybusinessaccountmanagement.googleapis.com/v1/accounts';
var response = UrlFetchApp.fetch(url, {
headers: {
Authorization: 'Bearer ' + service.getAccessToken()
}
});
var result = JSON.parse(response.getContentText());
Logger.log(JSON.stringify(result, null, 2));
} else {
var authorizationUrl = service.getAuthorizationUrl();
Logger.log('Open the following URL and re-run the script: %s', authorizationUrl);
}
}
/**
* Reset the authorization state, so that it can be re-tested.
*/
function reset() {
getService().reset();
}
/**
* Configures the service.
*/
function getService() {
return OAuth2.createService('Google')
// Set the endpoint URLs.
.setAuthorizationBaseUrl('https://accounts.google.com/o/oauth2/v2/auth')
.setTokenUrl('https://oauth2.googleapis.com/token')
// Set the client ID and secret.
.setClientId(CLIENT_ID)
.setClientSecret(CLIENT_SECRET)
// Set the name of the callback function that should be invoked to
// complete the OAuth flow.
.setCallbackFunction('authCallback')
// Set the property store where authorized tokens should be persisted.
.setPropertyStore(PropertiesService.getUserProperties())
// Set the scope and additional Google-specific parameters.
.setScope('https://www.googleapis.com/auth/business.manage')
.setParam('access_type', 'offline')
.setParam('approval_prompt', 'force')
.setParam('login_hint', Session.getActiveUser().getEmail());
}
/**
* Handles the OAuth callback.
*/
function authCallback(request) {
var service = getService();
var authorized = service.handleCallback(request);
if (authorized) {
return HtmlService.createHtmlOutput('Success!');
} else {
return HtmlService.createHtmlOutput('Denied.');
}
}
/**
* Logs the redict URI to register in the Google Developers Console.
*/
function logRedirectUri() {
Logger.log(OAuth2.getRedirectUri());
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment