Skip to content

Instantly share code, notes, and snippets.

@torpio
Created May 23, 2014 12:07
Show Gist options
  • Save torpio/0df1b1505db38d6f90ef to your computer and use it in GitHub Desktop.
Save torpio/0df1b1505db38d6f90ef to your computer and use it in GitHub Desktop.
Takes a webhook from FLG 360 and creates a new client in FreshBooks.
/*
This script receives a webhook from FLG 360 and creates a new client in FreshBooks **only if** a client with the same email address doesn't already exist.
If no email address is held in FLG 360, nothing will happen.
*/
if (request.body.email) {
// First check if the client already exists
var data = '<?xml version="1.0" encoding="utf-8"?> \
<request method="client.list"> \
<email>' + request.body.email + '</email> \
</request>';
service.post('freshbooks', 'xml-in', data, function (err, status, result) {
handle(err, status, result, function (err, output) {
if (!err) {
if (!output.response.clients.client) {
// Not found, lets create them
var data = '<?xml version="1.0" encoding="utf-8"?> \
<request method="client.create"> \
<client> \
<first_name>' + request.body.firstname + '</first_name> \
<last_name>' + request.body.lastname + '</last_name> \
<organization>' + request.body.company + '</organization> \
<email>' + request.body.email + '</email> \
<home_phone>' + request.body.phone1 + '</home_phone> \
<mobile>' + request.body.phone2 + '</mobile> \
<p_street1>' + request.body.address + '</p_street1> \
<p_street2>' + request.body.address2 + '</p_street2> \
<p_city>' + request.body.address3 + '</p_city> \
<p_state>' + request.body.towncity + '</p_state> \
<p_code>' + request.body.postcode + '</p_code> \
</client> \
</request>';
service.post('freshbooks', 'xml-in', data, function (err, status, result) {
handle(err, data, status, result, function (err, output) {});
});
}
}
});
});
}
function handle (err, data, status, result, fn) {
if (err || status >= 500) {
log.error(err, status, data);
script.result({ status: 500 });
} else if (result.indexOf('<response xmlns="http://www.freshbooks.com/api/" status="ok">') === -1) {
log.error(result, data);
fn(yes, null);
} else {
XML.parse(result, function (err, output) {
if (err) {
log.error(err, data);
script.result({ status: 500 });
fn(yes, null);
} else {
fn(null, output);
}
});
}
}
// Install with #torpio at https://torpio.com/app/scripts/shared/view/33515
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment