Free, Open Source, Self-Hosted WhatsApp API Gateway
TypeScript apibotgatewayself-hostedwhatsappwhatsapp-apiwhatsapp-automationwhatsapp-botwhatsapp-gatewaywhatsapp-gateway-apiwhatsapp-webwhatsapp-web-api
docs: add webhook signature verification examples (#318)
hsnyvshdb8feb3f7dfe
diff --git a/docs/README.md b/docs/README.mdindex 36956a7a6..973acd368 100644--- a/docs/README.md+++ b/docs/README.md@@ -57,6 +57,13 @@| 22 | [n8n Integration](./22-n8n-integration.md) | n8n community nodes for OpenWA || 23 | [Community Integrations](./23-community-integrations.md) | Third-party adapters built on the OpenWA API |+**Examples**++| Example | Description |+| ------- | ----------- |+| [Webhook Signature Verification](./examples/webhook-signature-verification.md) | Verify signed OpenWA webhook deliveries in Node.js and Python |+| [n8n Appointment Booking Workflow](./examples/n8n-appointment-booking.md) | Build an appointment-booking flow with OpenWA and n8n |+## Quick Start### Option A: Minimal Setup (SQLite, no Docker services)diff --git a/docs/examples/webhook-signature-verification.md b/docs/examples/webhook-signature-verification.mdnew file mode 100644index 000000000..7a3da8f99--- /dev/null+++ b/docs/examples/webhook-signature-verification.md@@ -0,0 +1,111 @@+# Webhook Signature Verification++OpenWA signs webhook deliveries when a webhook is configured with a secret. Receivers should verify the signature before processing the event.++## Headers++OpenWA sends these system headers with webhook deliveries:++| Header | Description |+| ------ | ----------- |+| `X-OpenWA-Signature` | HMAC-SHA256 signature, present only when the webhook has a secret |+| `X-OpenWA-Event` | Event name, for example `message.received` |+| `X-OpenWA-Idempotency-Key` | Stable key for duplicate detection |+| `X-OpenWA-Delivery-Id` | Unique delivery attempt identifier |+| `X-OpenWA-Retry-Count` | Retry count for the current delivery |++The signature format is:++```text+sha256=<hex digest>+```++The digest is computed over the exact raw request body bytes using the webhook secret.++## Node.js / Express++Use `express.raw()` for the webhook route so the signature is checked against the raw body. Parse JSON only after verification succeeds.++```javascript+const crypto = require('crypto');+const express = require('express');++const app = express();+const WEBHOOK_SECRET = process.env.OPENWA_WEBHOOK_SECRET;++function verifyOpenWASignature(rawBody, signature, secret) {+ if (!signature || !secret) return false;++ const expected =+ 'sha256=' + crypto.createHmac('sha256', secret).update(rawBody).digest('hex');++ const signatureBuffer = Buffer.from(signature);+ const expectedBuffer = Buffer.from(expected);++ if (signatureBuffer.length !== expectedBuffer.length) return false;++ return crypto.timingSafeEqual(signatureBuffer, expectedBuffer);+}++app.post('/openwa/webhook', express.raw({ type: 'application/json' }), (req, res) => {+ const signature = req.header('X-OpenWA-Signature');++ if (!verifyOpenWASignature(req.body, signature, WEBHOOK_SECRET)) {+ return res.status(401).send('Invalid signature');+ }++ const event = JSON.parse(req.body.toString('utf8'));++ // Process event here.+ // Return a 2xx response only after the event is safely accepted.+ return res.status(200).send('OK');+});+```++## Python / FastAPI++Read the raw request body before parsing JSON.++```python+import hmac+import hashlib+import os+from fastapi import FastAPI, Request, HTTPException++app = FastAPI()+WEBHOOK_SECRET = os.environ["OPENWA_WEBHOOK_SECRET"]+++def verify_openwa_signature(raw_body: bytes, signature: str | None, secret: str) -> bool:+ if not signature:+ return False++ expected = "sha256=" + hmac.new(+ secret.encode("utf-8"), raw_body, hashlib.sha256+ ).hexdigest()++ return hmac.compare_digest(signature, expected)++[email protected]("/openwa/webhook")+async def openwa_webhook(request: Request):+ raw_body = await request.body()+ signature = request.headers.get("x-openwa-signature")++ if not verify_openwa_signature(raw_body, signature, WEBHOOK_SECRET):+ raise HTTPException(status_code=401, detail="Invalid signature")++ event = await request.json()++ # Process event here.+ return {"status": "ok"}+```++## Processing Checklist++- Verify `X-OpenWA-Signature` before trusting or parsing the event.+- Use the exact raw request body received by your HTTP server.+- Use a constant-time comparison function.+- Return `401` for invalid signatures.+- Use `X-OpenWA-Idempotency-Key` to avoid duplicate processing on retries.+- Return a `2xx` response only after the event is accepted for processing.