REST-API für Entwickler
Anleitung: Webhook-Empfänger bauen
Ein vollständiger Empfänger in Python und Node.js: Signatur prüfen, Duplikate ignorieren, sofort antworten und danach verarbeiten.
Inhalt
Ziel und Voraussetzungen
Am Ende empfängt Ihr System Rechnungsereignisse, nimmt nur signierte Nachrichten an und verarbeitet jede Nachricht einmal.
- Webhooks sind ab dem Plan Pro enthalten.
- Für Zustellungen: eine Adresse Ihres Empfängers, die aus dem Internet per HTTPS erreichbar ist. Für den lokalen Test in Schritt 4 genügt Ihr eigener Rechner.
- Python 3.9 oder neuer mit Flask (
pip install flask) oder Node.js 18 oder neuer mit Express (npm install express).
Ereignisse, Daten, Header und Wiederholungen beschreibt die Seite Webhooks.
1. Ziel einrichten
Legen Sie in Ihrem Konto unter Webhooks ein Ziel mit der HTTPS-Adresse Ihres Empfängers an und wählen Sie die Ereignisse. Kopieren Sie das Signatur-Geheimnis (beginnt mit whsec_) in die Umgebungsvariable WEBHOOK_SECRET Ihres Empfängers; halten Sie es aus dem Quellcode heraus.
read -rs WEBHOOK_SECRET && export WEBHOOK_SECRET
2. Empfänger schreiben
Der Empfänger erledigt für jede Anfrage vier Dinge:
- Signatur prüfen über den unveränderten Rumpf der Anfrage, bevor das JSON gelesen wird. Nachrichten mit ungültiger Signatur oder einem Zeitstempel, der älter als fünf Minuten ist, werden mit
401abgewiesen. - Duplikate erkennen an der ID der Nachricht (
id, gleich dem HeaderWebhook-Id). Dieselbe Nachricht kann mehrmals ankommen. -
Sofort antworten mit einem 2xx-Status, hier
204, auch bei Duplikaten. Ein Versuch ohne 2xx-Antwort innerhalb von 10 Sekunden gilt als gescheitert und wird wiederholt. - Danach verarbeiten, außerhalb der Anfrage: hier in einer Warteschlange, die ein Hintergrund-Thread bzw. die Event-Loop abarbeitet.
"""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)
// 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"));
}
Die Beispiele halten die IDs empfangener Nachrichten im Speicher. Speichern Sie sie im Betrieb in Ihrer Datenbank mit eindeutigem Schlüssel, damit Duplikate auch nach einem Neustart und bei mehreren Prozessen erkannt werden.
3. Eigene Signaturprüfung testen
Mit diesen Werten muss Ihre Signaturprüfung „gültig“ ergeben, wenn Sie den Zeitstempel des Beispiels als aktuelle Zeit (now) übergeben. Die Signatur ist HMAC-SHA256 mit dem Geheimnis über den Zeitstempel, einen Punkt und den Rumpf, als Hexadezimalzeichenkette nach v1=.
{
"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. Lokal testen
Starten Sie den Empfänger und senden Sie ihm eine signierte Testnachricht mit demselben Geheimnis. Der Empfänger lauscht auf http://localhost:8000/webhooks/e-invoice.
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"
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)
Erwartetes Ergebnis: Status 204 für beide Anfragen, und der Empfänger verarbeitet die Nachricht nur einmal. Mit einem anderen Geheimnis ist der Status 401.
Vollständiges Skript auf GitHub:
webhook_send_test.sh, webhook_send_test.py
5. Testereignis und Zustellprotokoll
Zugestellt wird nur an öffentliche HTTPS-Adressen. Um Nachrichten während der Entwicklung auf Ihrem eigenen Rechner zu empfangen, machen Sie den lokalen Port mit einem Tunnel-Dienst per HTTPS erreichbar und tragen dessen Adresse als Ziel ein.
- Die Schaltfläche „Testereignis senden“ des Ziels sendet das Ereignis
webhook.test. Seindataenthält nurendpoint_id. -
Das Zustellprotokoll des Ziels zeigt jede Nachricht mit Zeit, Ereignis, Status und der Zahl der Versuche (höchstens 6). Die Spalte „Antwort“ zeigt den letzten HTTP-Status Ihres Empfängers, z. B.
HTTP 401bei falschem Geheimnis, oder den Fehler, wenn keine Antwort kam, z. B. eine Zeitüberschreitung.
Nächste Schritte
-
Rufen Sie in
handlemitmanaged_invoice_idden aktuellen Stand der Rechnung überGET /api/v1/managed-invoices/{id}/ab: Webhooks. - Ereignisse und die Daten je Ereignis: Webhooks.
- Rate-Limits und Wiederholungen Ihrer eigenen API-Anfragen: Implementierungsdetails.