Skip to content

REST API for developers

Guide: build a webhook receiver

A complete receiver in Python and Node.js: verify the signature, ignore duplicates, answer at once and process afterwards.

Contents

Goal and prerequisites

At the end, your system receives invoice events, accepts only signed messages and processes each message once.

  • Webhooks are included from the Pro plan.
  • For deliveries: an address of your receiver that can be reached from the internet via HTTPS. For the local test in step 4, your own computer is enough.
  • Python 3.9 or later with Flask (pip install flask), or Node.js 18 or later with Express (npm install express).

Events, data, headers and retries are described on the page Webhooks.

1. Set up the endpoint

In your account under Webhooks, add an endpoint with the HTTPS address of your receiver and choose the events. Copy the signing secret (it starts with whsec_) into the environment variable WEBHOOK_SECRET of your receiver; keep it out of the source code.

Shell
read -rs WEBHOOK_SECRET && export WEBHOOK_SECRET

2. Write the receiver

The receiver does four things for each request:

  1. Verify the signature over the raw body, before parsing the JSON. Messages with an invalid signature or a timestamp older than five minutes are rejected with 401.
  2. Recognise duplicates by the ID of the message (id, the same as the header Webhook-Id). The same message can arrive more than once.
  3. Answer at once with a 2xx status, here 204, also for duplicates. An attempt without a 2xx answer within 10 seconds counts as failed and is repeated.
  4. Process afterwards, outside the request: here in a queue that a background thread or the event loop works through.
Python (Flask) Full script: webhook_receiver_flask.py
"""Webhook receiver for the account webhooks (Python 3.9+, Flask).

    pip install flask
    export WEBHOOK_SECRET="whsec_..."   # signing secret of the endpoint
    python webhook_receiver_flask.py    # listens on http://localhost:8000/webhooks/e-invoice

Verifies the signature, ignores duplicates, answers at once with 204 and processes the message afterwards
in a background thread.
"""
import hashlib
import hmac
import json
import os
import queue
import threading
import time

from flask import Flask, request

SECRET = os.environ.get("WEBHOOK_SECRET", "")
TOLERANCE_SECONDS = 300  # reject older messages (replay protection)

app = Flask(__name__)
jobs = queue.Queue()
# IDs of messages already received. In production, store them in your database with a unique key,
# so that duplicates are also recognised after a restart and with several processes.
seen_ids = set()
seen_lock = threading.Lock()


def verify_signature(secret, timestamp, signature, body, now=None):
    """True if the header Webhook-Signature matches the raw body and the timestamp is recent."""
    try:
        sent = int(timestamp)
    except (TypeError, ValueError):
        return False
    now = time.time() if now is None else now
    if abs(now - sent) > TOLERANCE_SECONDS:
        return False
    expected = hmac.new(secret.encode(), timestamp.encode() + b"." + body, hashlib.sha256).hexdigest()
    received = (signature or "").removeprefix("v1=")
    # compare bytes: a header with non-ASCII characters is simply wrong, not an error
    return hmac.compare_digest(expected.encode(), received.encode())


def first_time(message_id):
    """True the first time a message ID arrives, False for duplicates."""
    with seen_lock:
        if message_id in seen_ids:
            return False
        seen_ids.add(message_id)
        return True


@app.post("/webhooks/e-invoice")
def receive():
    body = request.get_data()  # the raw body: the signature covers exactly these bytes
    timestamp = request.headers.get("Webhook-Timestamp", "")
    signature = request.headers.get("Webhook-Signature", "")
    if not SECRET or not verify_signature(SECRET, timestamp, signature, body):
        return "invalid signature", 401
    message = json.loads(body)
    if first_time(message["id"]):
        jobs.put(message)  # process later, answer now
    return "", 204


def handle(message):
    """Your processing, outside the request. Ignore events you do not know."""
    event, data = message["event"], message["data"]
    if event == "webhook.test":
        print("test event for endpoint", data["endpoint_id"])
    elif event in ("invoice.paid", "invoice.overdue", "invoice.exported", "incoming_invoice.imported"):
        # e.g. GET /api/v1/managed-invoices/{managed_invoice_id}/ for the current state
        print(event, "invoice", data["managed_invoice_id"], "status", data["status"])


def worker():
    while True:
        message = jobs.get()
        try:
            handle(message)
        except Exception as exc:  # noqa: BLE001 - keep the worker running
            print("processing failed:", message["id"], exc)
        finally:
            jobs.task_done()


if __name__ == "__main__":
    threading.Thread(target=worker, daemon=True).start()
    app.run(port=8000)
Node.js (Express) Full script: webhook_receiver_express.mjs
// Webhook receiver for the account webhooks (Node.js 18+, Express).
//
//   npm install express
//   export WEBHOOK_SECRET="whsec_..."   # signing secret of the endpoint
//   node webhook_receiver_express.mjs   # listens on http://localhost:8000/webhooks/e-invoice
//
// Verifies the signature, ignores duplicates, answers at once with 204 and processes the message afterwards.
import crypto from "node:crypto";
import { fileURLToPath } from "node:url";
import express from "express";

const SECRET = process.env.WEBHOOK_SECRET ?? "";
const TOLERANCE_SECONDS = 300; // reject older messages (replay protection)

// IDs of messages already received. In production, store them in your database with a unique key,
// so that duplicates are also recognised after a restart and with several processes.
const seenIds = new Set();
const jobs = [];

export function verifySignature(secret, timestamp, signature, rawBody, now = Date.now() / 1000) {
  const sent = Number.parseInt(timestamp, 10);
  if (!Number.isFinite(sent) || Math.abs(now - sent) > TOLERANCE_SECONDS) return false;
  const expected = Buffer.from(
    crypto.createHmac("sha256", secret).update(`${timestamp}.`).update(rawBody).digest("hex"));
  const received = Buffer.from(String(signature ?? "").replace(/^v1=/, ""));
  // compare bytes: timingSafeEqual needs buffers of the same length (non-ASCII characters change the length)
  if (received.length !== expected.length) return false;
  return crypto.timingSafeEqual(expected, received);
}

export const app = express();

// express.raw keeps the raw body: the signature covers exactly these bytes
app.post("/webhooks/e-invoice", express.raw({ type: "application/json" }), (req, res) => {
  const body = Buffer.isBuffer(req.body) ? req.body : Buffer.alloc(0);
  const timestamp = req.get("Webhook-Timestamp");
  const signature = req.get("Webhook-Signature");
  if (!SECRET || !verifySignature(SECRET, timestamp, signature, body)) {
    return res.status(401).send("invalid signature");
  }
  const message = JSON.parse(body.toString("utf8"));
  if (!seenIds.has(message.id)) {
    seenIds.add(message.id);
    jobs.push(message); // process later, answer now
    setImmediate(processJobs);
  }
  return res.status(204).end();
});

// Your processing, outside the request. Ignore events you do not know.
async function handle(message) {
  const { event, data } = message;
  if (event === "webhook.test") {
    console.log("test event for endpoint", data.endpoint_id);
  } else if (["invoice.paid", "invoice.overdue", "invoice.exported", "incoming_invoice.imported"].includes(event)) {
    // e.g. GET /api/v1/managed-invoices/{managed_invoice_id}/ for the current state
    console.log(event, "invoice", data.managed_invoice_id, "status", data.status);
  }
}

async function processJobs() {
  while (jobs.length > 0) {
    const message = jobs.shift();
    try {
      await handle(message);
    } catch (error) {
      console.error("processing failed:", message.id, error); // keep processing the other messages
    }
  }
}

if (process.argv[1] === fileURLToPath(import.meta.url)) {
  app.listen(8000, () => console.log("listening on http://localhost:8000/webhooks/e-invoice"));
}

The examples keep the IDs of received messages in memory. In production, store them in your database with a unique key, so that duplicates are also recognised after a restart and with several processes.

3. Check your signature code

With these values, your signature check must return true if you pass the timestamp of the example as the current time (now). The signature is HMAC-SHA256 with the secret over the timestamp, a dot and the body, as a hexadecimal string after v1=.

webhook_signature_example.json Full script: webhook_signature_example.json
{
  "secret": "whsec_example_secret_only_for_testing",
  "timestamp": "1795601700",
  "body": "{\"id\":\"5f0c6c1e-3c1b-4c7e-9a43-0d6c2b7f1a2e\",\"event\":\"invoice.paid\",\"created_at\":\"2026-11-25T10:15:00.123456+00:00\",\"data\":{\"managed_invoice_id\":1234,\"invoice_id\":\"b3a9e2d4-7f61-4f0e-8a51-2c4d9e0f6a77\",\"direction\":\"outgoing\",\"status\":\"paid\"}}",
  "signature": "v1=5126fcd1bbd70bc6e7ffde57486e0999cae7cca7e7cf0943faa0d97a9114d098"
}

4. Test locally

Start the receiver and send it a signed test message with the same secret. The receiver listens on http://localhost:8000/webhooks/e-invoice.

curl (Shell)
MESSAGE_ID=$(uuidgen)
BODY='{"id":"'"$MESSAGE_ID"'","event":"webhook.test","created_at":"2026-11-25T10:15:00+00:00","data":{"endpoint_id":42}}'
TIMESTAMP=$(date +%s)
SIGNATURE=$(printf '%s.%s' "$TIMESTAMP" "$BODY" | openssl dgst -sha256 -hmac "$WEBHOOK_SECRET" | sed 's/^.*= //')

curl -sS -i -X POST "http://localhost:8000/webhooks/e-invoice" \
  -H "Content-Type: application/json" \
  -H "Webhook-Id: $MESSAGE_ID" \
  -H "Webhook-Event: webhook.test" \
  -H "Webhook-Timestamp: $TIMESTAMP" \
  -H "Webhook-Signature: v1=$SIGNATURE" \
  -d "$BODY"
Python (requests)
import hashlib
import hmac
import json
import os
import time
import uuid

import requests

SECRET = os.environ["WEBHOOK_SECRET"]

message_id = str(uuid.uuid4())
body = json.dumps({"id": message_id, "event": "webhook.test", "created_at": "2026-11-25T10:15:00+00:00",
                   "data": {"endpoint_id": 42}}, separators=(",", ":")).encode()
timestamp = str(int(time.time()))
signature = hmac.new(SECRET.encode(), timestamp.encode() + b"." + body, hashlib.sha256).hexdigest()
headers = {
    "Content-Type": "application/json",
    "Webhook-Id": message_id,
    "Webhook-Event": "webhook.test",
    "Webhook-Timestamp": timestamp,
    "Webhook-Signature": f"v1={signature}",
}
for attempt in (1, 2):  # the second request is a duplicate: answered, but not processed again
    response = requests.post("http://localhost:8000/webhooks/e-invoice", data=body, headers=headers, timeout=10)
    print(attempt, response.status_code)

Expected result: status 204 for both requests, and the receiver processes the message only once. With a different secret, the status is 401.

Complete script on GitHub: webhook_send_test.sh, webhook_send_test.py

5. Test event and delivery log

Deliveries go only to public HTTPS addresses. To receive them on your own computer during development, make the local port reachable via HTTPS with a tunnel service and enter its address as the endpoint.

  • The button “Send test event” of the endpoint sends the event webhook.test. Its data contains only endpoint_id.
  • The delivery log of the endpoint shows each message with time, event, status and the number of attempts (at most 6). The column “Response” shows the last HTTP status of your receiver, e.g. HTTP 401 for a wrong secret, or the error if there was no answer, e.g. a timeout.

Next steps

  • In handle, retrieve the current state of the invoice with GET /api/v1/managed-invoices/{id}/ and managed_invoice_id: Webhooks.
  • Events and the data of each event: Webhooks.
  • Rate limits and retries of your own API requests: Implementation details.