Swipelux
Webhooks

Validate webhook deliveries

Learn how to validate the signatures of incoming webhook requests.

Introduction

Once your server is configured to receive payloads, it will listen for any delivery that's sent to the endpoint you configured. To ensure that your server only processes webhook deliveries that were sent by Swipelux and to ensure that the delivery was not tampered with, you should validate the webhook signature before processing the delivery further.

This will help you avoid spending server time to process deliveries that are not from Swipelux and will help avoid man-in-the-middle attacks.

Validate deliveries

Swipelux will use the secret key to create a hash signature that's sent to you with each payload. The hash signature will appear in each delivery as the value of the X-Webhook-Signature header.

See the Configure webhooks article for more information on how to configure your webhook endpoint.

In your code that handles webhook deliveries, you should calculate a hash using your secret key. Then, compare the hash that Swipelux sent with the expected hash that you calculated, and ensure that they match. For examples showing how to validate the hashes in various programming languages, see Examples.

Examples

You can use your programming language of choice to implement HMAC verification in your code. Following are some examples showing how an implementation might look in various programming languages.

Node.js example

For example, you can define the following verifyWebhookSignature function and call it in any Node.js server when you receive a webhook payload:

const crypto = require('crypto');
 
const secretKey = process.env.WEBHOOK_SECRET_KEY;
 
const verifyWebhookSignature = (payload, signature) => {
  const calculatedSignature = crypto.createHmac('sha256', secretKey).update(payload).digest('hex');
  return signature === calculatedSignature;
};

Python example

For example, you can define the following verify_webhook_signature function and call it when you receive a webhook payload:

import hmac
import hashlib
 
WEBHOOK_SECRET = os.environ['WEBHOOK_SECRET']
 
def verify_webhook_signature(payload, signature):
    hmac_obj = hmac.new(
        WEBHOOK_SECRET.encode('utf-8'),
        json.dumps(payload).encode('utf-8'),
        hashlib.sha256
    )
    return hmac.compare_digest(signature, hmac_obj.hexdigest())

PHP example

<?php
 
$WEBHOOK_SECRET = getenv('WEBHOOK_SECRET');
$payload = file_get_contents('php://input');
$headers = getallheaders();
 
$signature = $headers['X-Webhook-Signature'] ?? '';
$calculatedSignature = hash_hmac('sha256', $payload, $WEBHOOK_SECRET);
 
if (!hash_equals($signature, $calculatedSignature)) {
  http_response_code(401);
  exit;
}

On this page