Skip to content

Instantly share code, notes, and snippets.

@jweisman
Created July 14, 2019 18:31
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 3 You must be signed in to fork a gist
  • Save jweisman/f4201edc97abcee0ab8b0321aa004599 to your computer and use it in GitHub Desktop.
Save jweisman/f4201edc97abcee0ab8b0321aa004599 to your computer and use it in GitHub Desktop.
Node.js listener for Alma webhooks
const express = require('express')
const bodyParser = require('body-parser');
const crypto = require('crypto');
const app = express()
const port = 8000
const webhook_secret = process.env.WEBHOOK_SECRET || '1234'
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.listen(port, (err) => {
if (err) {
return console.log('something bad happened', err)
}
console.log(`server is listening on ${port}`)
})
app.get('/', (request, response) => {
response.send('Hello from Express!')
})
function validateSignature(body, secret, signature) {
var hash = crypto.createHmac('SHA256', secret)
.update(JSON.stringify(body))
.digest('base64');
return (hash === signature);
}
/*
GET - Challenge
*/
app.get('/webhook', function(req, res, next) {
res.json({ challenge: req.query.challenge });
});
/*
POST - Handle webhook
*/
app.post('/webhook', function(req, res, next) {
console.log('Received webhook request:', JSON.stringify(req.body));
console.log(req.get('X-Exl-Signature'));
// Validate signature
if (!validateSignature(req.body,
webhook_secret,
req.get('X-Exl-Signature'))) {
return res.status(401).send({errorMessage: 'Invalid Signature'});
}
// Handle webhook
var action = req.body.action.toLowerCase();
switch (action) {
default:
console.log('No handler for type', action);
}
res.status(204).send();
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment