Description
var schwab_apikey = scriptProperties.getProperty('schwab_apikey')
var schwab_secret = scriptProperties.getProperty('schwab_secret')
var encodedCredentials = Utilities.base64Encode(schwab_apikey + ":" + schwab_secret);
function getSchwabService_() {
// Create a new service with the given name. The name will be used when
// persisting the authorized token, so ensure it is unique within the
// scope of the property store.
return OAuth2.createService('schwab')
// Set the endpoint URLs, which are the same for all Google services.
.setAuthorizationBaseUrl('https://api.schwabapi.com/v1/oauth/authorize')
.setTokenUrl('https://api.schwabapi.com/v1/oauth/token')
// Set the client ID and secret
.setClientId(schwab_apikey)
.setClientSecret(schwab_secret)
// Set the name of the callback function in the script referenced
// above that should be invoked to complete the OAuth flow.
.setCallbackFunction('authCallback')
// Set the property store where authorized tokens should be persisted.
.setPropertyStore(PropertiesService.getUserProperties())
//Schwab API requires you to set an Authorization header on access token requests
.setTokenHeaders({'Authorization': 'Basic ' + encodedCredentials})
}
function authCallback(request) {
var schwabService = getSchwabService_();
var isAuthorized = schwabService.handleCallback(request);
if (isAuthorized) {
return HtmlService.createHtmlOutput('Success! You can close this tab.');
} else {
return HtmlService.createHtmlOutput('Denied. You can close this tab');
}
}
function showSidebar() {
var schwabService = getSchwabService_();
if (!schwabService.hasAccess()) {
var authorizationUrl = schwabService.getAuthorizationUrl();
var template = HtmlService.createTemplate(
'Authorize. ' +
'Reopen the sidebar when the authorization is complete.');
template.authorizationUrl = authorizationUrl;
var page = template.evaluate();
SpreadsheetApp.getUi().showSidebar(page);
} else {
// ...
}
}
function makeRequest() {
var schwabService = getSchwabService_();
var response = UrlFetchApp.fetch('https://api.schwabapi.com/trader/v1/accounts', {
headers: {
Authorization: 'Bearer ' + schwabService.getAccessToken()
}
});
Logger.log(response);
}