> ## Documentation Index
> Fetch the complete documentation index at: https://docs.newlead.ai/llms.txt
> Use this file to discover all available pages before exploring further.

# Verify webhook signatures

> Confirm that a delivery comes from NewLead before you process it.

Each delivery carries these headers:

| Header | Value |
| - | - |
| `X-Webhook-Signature` | `t=<unix-timestamp>,v1=<hex-signature>` |
| `X-Webhook-Event` | The event name |
| `X-Webhook-Delivery` | The delivery ID, the same on every retry |

`v1` is an HMAC-SHA256 of `{t}.{raw_body}`, keyed with the endpoint secret (`whsec_...`). Each attempt is signed again with a new `t`.

> [!WARNING]
>
> Verify the raw body, exactly as it arrives. If you parse the JSON and serialize it again, the signature no longer matches.

## Verify a delivery

**1. Read the header**

Split `X-Webhook-Signature` on the comma and read `t` and `v1`.

**2. Compute the signature**

Calculate the HMAC-SHA256 of `t`, a period and the raw body, using the endpoint secret as the key.

**3. Compare the signatures**

Compare your result with `v1` in constant time.

**4. Check the timestamp**

Reject the delivery if `t` is more than 5 minutes from your clock. This stops a captured request from being replayed.

```javascript Node.js theme={null}
import crypto from "node:crypto";
import express from "express";

const TOLERANCE_SECONDS = 300;

function verifyWebhookSignature(rawBody, header, secret) {
  if (typeof rawBody !== "string" && !Buffer.isBuffer(rawBody)) return false;
  if (typeof header !== "string" || typeof secret !== "string" || secret === "") return false;

  const fields = new Map(header.split(",").map((part) => part.trim().split("=", 2)));
  const timestamp = fields.get("t") ?? "";
  const signature = fields.get("v1") ?? "";
  if (!/^\d{1,12}$/.test(timestamp) || !/^[0-9a-f]{64}$/.test(signature)) return false;
  if (Math.abs(Date.now() / 1000 - Number(timestamp)) > TOLERANCE_SECONDS) return false;

  const expected = crypto
    .createHmac("sha256", secret)
    .update(`${timestamp}.`)
    .update(rawBody)
    .digest();

  return crypto.timingSafeEqual(expected, Buffer.from(signature, "hex"));
}

const app = express();

app.post("/webhooks/newlead", express.raw({ type: "application/json" }), (req, res) => {
  const valid = verifyWebhookSignature(
    req.body,
    req.get("X-Webhook-Signature"),
    process.env.NEWLEAD_WEBHOOK_SECRET,
  );
  if (!valid) return res.sendStatus(400);

  const event = JSON.parse(req.body);
  console.log(event.event, req.get("X-Webhook-Delivery"));
  res.sendStatus(200);
});

app.listen(3000);
```

```python Python theme={null}
import hashlib
import hmac
import os
import re
import time

from flask import Flask, abort, request

TOLERANCE_SECONDS = 300


def verify_webhook_signature(raw_body, header, secret):
    if not isinstance(raw_body, bytes):
        return False
    if not isinstance(header, str) or not isinstance(secret, str) or not secret:
        return False

    fields = dict(
        part.strip().split("=", 1) for part in header.split(",") if "=" in part
    )
    timestamp = fields.get("t", "")
    signature = fields.get("v1", "")
    if not re.fullmatch(r"[0-9]{1,12}", timestamp):
        return False
    if not re.fullmatch(r"[0-9a-f]{64}", signature):
        return False
    if abs(time.time() - int(timestamp)) > TOLERANCE_SECONDS:
        return False

    signed_payload = timestamp.encode() + b"." + raw_body
    expected = hmac.new(secret.encode(), signed_payload, hashlib.sha256).hexdigest()
    return hmac.compare_digest(expected, signature)


app = Flask(__name__)


@app.post("/webhooks/newlead")
def newlead_webhook():
    valid = verify_webhook_signature(
        request.get_data(),
        request.headers.get("X-Webhook-Signature"),
        os.environ["NEWLEAD_WEBHOOK_SECRET"],
    )
    if not valid:
        abort(400)

    event = request.get_json()
    print(event["event"], request.headers.get("X-Webhook-Delivery"))
    return "", 200
```

## Keep the secret safe

Each endpoint has its own secret. The API shows it only once, when you create the endpoint. If you lose it, delete the endpoint and create a new one.


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.