Handling webhook deliveries
Learn how to write code to listen for and respond to webhook deliveries.
Last updated
const express = require('express');
// This initializes a new Express application.
const app = express();
// Once you deploy your code to a server and update your webhook URL, you should change this to match the path portion of the URL for your webhook.
app.post('/PATH_TO_PAYLOAD_ENDPOINT', express.json({type: 'application/json'}), (request, response) => {
// Respond to indicate that the delivery was successfully received.
// Your server should respond with a 2XX response within 10 seconds of receiving a webhook delivery. If your server takes longer than that to respond, then Shopwaive terminates the connection and considers the delivery a failure.
response.status(202).send('Accepted');
// Check the `x-shopwaive-event` header to learn what event type was sent.
const shopwaiveEvent = request.headers['x-shopwaive-event'];
// You should add logic to handle each event type that your webhook is subscribed to.
// For example, this code handles the `available_balance` and `ping` events.
// If any events have an `action` field, you should also add logic to handle each action that you are interested in.
// For example, this code handles the `redeemed` and `adjusted` actions for the `available_balance` event.
//
if (shopwaiveEvent === 'available_balance') {
const data = request.body;
const action = data.action;
if (action === 'redeemed') {
console.log(`An available_balance was redeemed with this transactional amount: ${data.available_balance.transaction}`);
} else if (action === 'adjusted') {
console.log(`An available_balance was adjusted by this transactional amount ${data.available_balance.transaction}`);
} else {
console.log(`Unhandled action for the issue event: ${action}`);
}
} else if (shopwaiveEvent === 'ping') {
console.log('Shopwaive sent the ping event');
} else {
console.log(`Unhandled event: ${shopwaiveEvent}`);
}
});
// This defines the port where your server should listen.
// 3000 matches the port that you specified for webhook forwarding.
// Once you deploy your code to a server, you should change this to match the port where your server is listening.
const port = 3000;
// This starts the server and tells it to listen at the specified port.
app.listen(port, () => {
console.log(`Server is running on port ${port}`);
});