Skip to content

Instantly share code, notes, and snippets.

@zirinisp
Created June 23, 2019 10:06
Show Gist options
  • Save zirinisp/3c87bc543baf8ab48c7a7625941d825e to your computer and use it in GitHub Desktop.
Save zirinisp/3c87bc543baf8ab48c7a7625941d825e to your computer and use it in GitHub Desktop.
Xero Google Script Integration
// Got the code from https://github.com/csi-lk/google-app-script-xero-api
var API_END_POINT = 'https://api.xero.com/api.xro/2.0';
var INVOICES_END_POINT = '/Invoices';
// Working method to send a request with a payload
function sendRequest(endpoint, method, payload) {
var url = 'https://api.xero.com/api.xro/2.0' + endpoint
var authHeader = getAuthHeader(method, url);
var headers = {
"Authorization": authHeader,
"Accept": "application/json"
};
var options = {
"headers": headers,
'method' : method,
'payload' : payload,
'muteHttpExceptions': true,
};
Logger.log(authHeader);
var response = UrlFetchApp.fetch(url, options);
return response;
}
// Receive Sales Invoices
function receiveSalesInvoices() {
var salesInvoives = receiveInvoices("Statuses=Paid"); // Works
// var salesInvoives = receiveInvoices("Statuses=Paid,Draft"); // Does not work
// var salesInvoives = receiveInvoices("where=AccountCode==201"); // Does not work
// Does not work
//var whereComponent = encodeURIComponent("accountcode=200");
//var salesInvoices = receiveInvoices("where="+whereComponent);
return salesInvoives;
}
// Receive Invoices
function receiveInvoices(query) {
var method = 'GET';
// If query is used then it fails, as the request is not signed properly
var oauth_nonce = createGuid();
var oauth_timestamp = (new Date().valueOf()/1000).toFixed(0);
var url = API_END_POINT+'/Invoices';
var authHeader = getAuthHeader(method, url, query);
var headers = {
"Authorization": authHeader,
"Accept": "application/json"
};
var options = {
"headers": headers,
'method' : method,
// 'payload' : JSON.stringify(data),
'muteHttpExceptions': true,
};
if (query) {
url += "?"+query;
}
var response = UrlFetchApp.fetch(url, options);
var responseXml = response.getContentText();
var responseArray = JSON.parse(responseXml);
return responseArray;
}
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