Last active
January 23, 2018 06:47
-
-
Save rjaus/f4d8390ba1bfcfcceb649f51116f5731 to your computer and use it in GitHub Desktop.
Xero webhooks Express JS example
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
'use strict' | |
const express = require('express') | |
const bodyParser = require('body-parser') | |
const crypto = require('crypto') | |
// Replace with your Xero Webhook Key | |
const xero_webhook_key = 'XERO_WEBHOOK_KEY' | |
// Create a new instance of express | |
const app = express() | |
// Set the body parser options | |
var options = { | |
type: 'application/json' | |
}; | |
// Using the options above, create a bodyParser middleware that returns raw responses. | |
var itrBodyParser = bodyParser.raw(options) | |
// Create a route that receives our webhook & pass it our itrBodyParser | |
app.post('/webhook', itrBodyParser, function (req, res) { | |
console.log("Body: "+req.body.toString()) | |
console.log("Xero Signature: "+req.headers['x-xero-signature']) | |
// Create our HMAC hash of the body, using our webhooks key | |
let hmac = crypto.createHmac("sha256", xero_webhook_key).update(req.body.toString()).digest("base64"); | |
console.log("Resp Signature: "+hmac) | |
if (req.headers['x-xero-signature'] == hmac) { | |
res.statusCode = 200 | |
} else { | |
res.statusCode = 401 | |
} | |
console.log("Response Code: "+res.statusCode) | |
res.send() | |
}) | |
// Tell our app to listen on port 3000 | |
app.listen(3000, function (err) { | |
if (err) { | |
throw err | |
} | |
console.log('Server started on port 3000') | |
}) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment