Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Xero Private Application from Google Apps Script
function xeroTest() {
var oauth_nonce = createGuid();
var oauth_timestamp = (new Date().valueOf()/1000).toFixed(0);
var signatureBase = "GET" + "&"
+ encodeURIComponent("https://api.xero.com/api.xro/2.0/Organisation") + "&"
+ encodeURIComponent("oauth_consumer_key=" + UserProperties.getProperty("consumerKey") + "&oauth_nonce="+oauth_nonce+"&oauth_signature_method=RSA-SHA1&oauth_timestamp="+oauth_timestamp+"&oauth_token=" + UserProperties.getProperty("consumerKey") + "&oauth_version=1.0");
var rsa = new RSAKey();
rsa.readPrivateKeyFromPEMString(UserProperties.getProperty("pemKey"));
var hashAlg = "sha1";
var hSig = rsa.signString(signatureBase, hashAlg);
var data = new Array();
for (var i = 0; i < hSig.length; i += 2) {
data.push(parseInt("0x" + hSig.substr(i, 2)));
}
var oauth_signature = Base64.encode(data);
var authHeader = "OAuth oauth_token=\"" + UserProperties.getProperty("consumerKey") + "\",oauth_nonce=\"" + oauth_nonce + "\",oauth_consumer_key=\"" + UserProperties.getProperty("consumerKey") + "\",oauth_signature_method=\"RSA-SHA1\",oauth_timestamp=\"" + oauth_timestamp + "\",oauth_version=\"1.0\",oauth_signature=\"" + encodeURIComponent(oauth_signature) + "\"";
var headers = { "User-Agent": + UserProperties.getProperty("userAgent") , "Authorization": authHeader };
var options = { "headers": headers };
Logger.log(signatureBase);
Logger.log(oauth_signature);
Logger.log(authHeader);
var response = UrlFetchApp.fetch("https://api.xero.com/api.xro/2.0/Organisation", options);
var responseXml = response.getContentText();
Logger.log(responseXml);
}
function createGuid() {
return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function(c) {
var r = Math.random()*16|0, v = c == 'x' ? r : (r&0x3|0x8);
return v.toString(16)
});
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment