Sample code for handling webhook events in Node.js.
Handling Events (Node.js)
The below example illustrates how to securely handle webhook events within your own applications. Each webhook call from the API includes a secure X-Terminal-Signature which is generated using your SECRET_KEY. To ensure integrity of each request you receive, you can complete a simple verification task as shown in the example below:
const crypto = require('crypto');
const SECRET_KEY = ""; //Your secret key
// Handle webhook event
const handleEvent = (req, res) => {
try{
res.sendStatus(200);
let webhook_signature = req.headers['X-Terminal-Signature']; //retrieve the request signature
let {body} = req; // Retrieve the request's body
let request_validation = verifyWebhookRequest(webhook_signature, SECRET_KEY, body); //Validate webhook request
if(request_validation.status){
let {data, event} = body; //retrieve event type and data payload
switch(event){
case "shipment.created":
//Handle successful shipment creation event
break;
case "address.updated":
//Handle successful address update event
break;
default:
//Handle unknown event received
}
}else{
//request is not valid API webhook
}
}catch(e){
console.log("Error occurred - %O", e)
}
}
/**
* Verifies validity of webhook request.
* @params - signature - Signature hash received via webhook.
* @params - secret_key - API secret key.
* @params - body - Request payload received via webhook.
*/
const verifyWebhookRequest = (signature, secret_key, body={}) => {
try{
let manual_hash_signature = crypto.createHmac('sha512', secret_key).update(JSON.stringify(body)).digest('hex'); //regenerate hash using secret key and webhook payload
let request_valid = (signature === manual_hash_signature); //verify signature from webhook matches manual hash
let valid_message = (request_valid) ? "Webhook request is valid" : "Invalid webhook request received";
return {
status: request_valid,
message: valid_message
}
}catch(e){
console.log("An error occurred %O", e);
return {
status: false,
message: "Unable to verify request"
}
}
}