What you need first
- A Meta business account and an app in Meta for Developers with the WhatsApp product.
- A phone number connected to the Cloud API and its Phone number ID.
- A permanent system-user access token – not the temporary test token that expires.
- The app’s App Secret for checking signatures, and a Verify Token you make up.
- An approved template. Templates are reviewed automatically, can take up to 24 hours and must have status APPROVED.
Keep the keys in environment variables or a .env file – never in code and never in URLs. We moved bot tokens out of URLs in 36 HTTP nodes across 12 n8n workflows into credentials and environment variables. Test only on your own number until everything works.
1. Send a template with curl
The template below is called bekraeftelse_tid and has two fields in the body: name and time. The language is Danish (da). The Graph API version was v27.0 on 19.11.2026; check the latest in Meta’s changelog before going live.
# .env: WA_TOKEN, PHONE_NUMBER_ID – never in git
export GRAPH_VERSION="v27.0"
curl -s -X POST "https://graph.facebook.com/$GRAPH_VERSION/$PHONE_NUMBER_ID/messages" \
-H "Authorization: Bearer $WA_TOKEN" \
-H "Content-Type: application/json" \
-d '{
"messaging_product": "whatsapp",
"recipient_type": "individual",
"to": "45XXXXXXXX",
"type": "template",
"template": {
"name": "bekraeftelse_tid",
"language": { "code": "da" },
"components": [
{
"type": "body",
"parameters": [
{ "type": "text", "text": "Anna" },
{ "type": "text", "text": "Thursday 10:00" }
]
}
]
}
}'
The response contains a message id starting with wamid.. Store it: status updates (sent, delivered, read, failed) arrive on the webhook with that id, and that is how you know the message actually got through. A utility template like this costs €0.0142 to a Danish number. Our own interface sends text, images, reactions and templates through exactly this endpoint.
2. Webhook in Node: reject anything Meta hasn’t signed
Meta signs every event with SHA256 and the app’s App Secret and sends the signature in the X-Hub-Signature-256 header with the prefix sha256=. When you save the webhook URL, Meta first sends a GET with hub.mode, hub.verify_token and hub.challenge, and you must reply with the challenge value. The key point is to compute the signature on the raw bytes. If you parse the JSON first and serialise it again, the signature won’t match.
// server.mjs – Node 20+, npm install express
import express from "express";
import crypto from "node:crypto";
const APP_SECRET = process.env.META_APP_SECRET; // App Dashboard → Settings → Basic
const VERIFY_TOKEN = process.env.META_VERIFY_TOKEN; // a long random string you choose
const app = express();
// 1) Meta's verification when you save the webhook URL
app.get("/webhooks/whatsapp", (req, res) => {
if (req.query["hub.mode"] === "subscribe" && req.query["hub.verify_token"] === VERIFY_TOKEN) {
return res.status(200).send(req.query["hub.challenge"]);
}
return res.sendStatus(403);
});
// 2) Events: check the signature on the raw bytes BEFORE parsing JSON
app.post("/webhooks/whatsapp", express.raw({ type: "application/json", limit: "3mb" }), (req, res) => {
if (!Buffer.isBuffer(req.body)) return res.sendStatus(400);
const received = Buffer.from(req.get("x-hub-signature-256") || "");
const expected = Buffer.from(
"sha256=" + crypto.createHmac("sha256", APP_SECRET).update(req.body).digest("hex")
);
if (received.length !== expected.length || !crypto.timingSafeEqual(received, expected)) {
return res.sendStatus(403); // unsigned or tampered: reject
}
const payload = JSON.parse(req.body.toString("utf8"));
res.sendStatus(200); // answer fast – Meta retries for up to 7 days
handle(payload); // queue, database or n8n
});
function handle(payload) {
for (const entry of payload.entry ?? []) {
for (const change of entry.changes ?? []) {
for (const msg of change.value?.messages ?? []) {
// Store with msg.id as a unique key – the same message can arrive twice
console.log(msg.id, msg.type);
}
}
}
}
app.listen(3000, () => console.log("listening on port 3000"));
3. The same webhook in Python (FastAPI)
# app.py – pip install fastapi uvicorn ; uvicorn app:app --port 3000
import hashlib
import hmac
import json
import os
from fastapi import FastAPI, Request, Response
APP_SECRET = os.environ["META_APP_SECRET"].encode()
VERIFY_TOKEN = os.environ["META_VERIFY_TOKEN"]
app = FastAPI()
@app.get("/webhooks/whatsapp")
def verify(request: Request) -> Response:
q = request.query_params
if q.get("hub.mode") == "subscribe" and q.get("hub.verify_token") == VERIFY_TOKEN:
return Response(q.get("hub.challenge", ""), media_type="text/plain")
return Response(status_code=403)
@app.post("/webhooks/whatsapp")
async def receive(request: Request) -> Response:
raw = await request.body() # the raw bytes – not request.json()
received = request.headers.get("x-hub-signature-256", "").encode()
expected = b"sha256=" + hmac.new(APP_SECRET, raw, hashlib.sha256).hexdigest().encode()
if not hmac.compare_digest(received, expected):
return Response(status_code=403) # unsigned or tampered: reject
payload = json.loads(raw)
for entry in payload.get("entry", []):
for change in entry.get("changes", []):
for msg in change.get("value", {}).get("messages", []):
# Store with msg["id"] as a unique key – the same message can arrive twice
print(msg["id"], msg["type"])
return Response(status_code=200)
Both versions answer 200 at once and process the message afterwards. If Meta doesn’t get a 200, it retries with decreasing frequency for up to seven days, which can create duplicates. So we store with the message id as a unique key, and the same message is never inserted twice. Our WhatsApp hub was built with idempotent ingest from day one.
4. Test the signature without Meta
BODY='{"object":"whatsapp_business_account","entry":[{"changes":[{"value":{"messages":[{"id":"wamid.TEST","type":"text"}]}}]}]}'
SIG=$(printf '%s' "$BODY" | openssl dgst -sha256 -hmac "$META_APP_SECRET" | awk '{print $NF}')
# Correct signature: expect 200
curl -s -o /dev/null -w "%{http_code}\n" -X POST "http://localhost:3000/webhooks/whatsapp" \
-H "Content-Type: application/json" -H "X-Hub-Signature-256: sha256=$SIG" --data "$BODY"
# Changed body with the old signature: expect 403
curl -s -o /dev/null -w "%{http_code}\n" -X POST "http://localhost:3000/webhooks/whatsapp" \
-H "Content-Type: application/json" -H "X-Hub-Signature-256: sha256=$SIG" --data "${BODY/TEST/FAKE}"
We ran both versions against exactly these calls on 19.11.2026: 200 with the correct signature, 403 with a changed body, 403 without a signature, and the verification returned the challenge value. It is the same rule our n8n instances enforce on every WhatsApp, Facebook and Instagram webhook.
5. Fetch photos as soon as they arrive
When a customer sends a photo, the webhook gives you only a media id. With the id you get a URL, and with the URL and your token you download the file. The URL expires after five minutes, and media ids from webhooks expire after seven days.
# 1) URL for the media (valid for 5 minutes)
curl -s "https://graph.facebook.com/$GRAPH_VERSION/$MEDIA_ID" \
-H "Authorization: Bearer $WA_TOKEN"
# 2) The file itself – same token – saved to your own storage
curl -s -L "$MEDIA_URL" -H "Authorization: Bearer $WA_TOKEN" -o "media/$MEDIA_ID.jpg"
Do it while handling the webhook, not when someone opens the chat. We learned this the hard way: a photo received eight days earlier returned 400, and while we only fetched photos when a staff member opened the chat, we lost 40 of 42. In our WhatsApp hub media therefore lives in MinIO next to PostgreSQL.
In n8n instead of your own server
If you run n8n, you can do all of this without a separate server: a Webhook node with raw body enabled, a Code node computing the same HMAC, and a “Respond to Webhook” node that answers 403 when the signature doesn’t match. We run two n8n instances in Docker Compose ourselves. One caution: a run with status “success” doesn’t mean the message was sent. In a salon workflow 12 of 207 SMS were never sent because the JSON was built by gluing strings together and a \ in a service name broke it. Build JSON with JSON.stringify and check the API response. For managed n8n in the EU, see n8n-hosting.best-choice.dk.
Sources
- Meta – Graph API webhooks, getting started — X-Hub-Signature-256, verification, checked 19.11.2026
- Meta – WhatsApp webhooks overview — retries for 7 days, 3 MB, mTLS, checked 19.11.2026
- Meta – templates overview — template structure, checked 19.11.2026
- Meta – media — 5 minutes, 7 days, 30 days, checked 19.11.2026
- Meta – Graph API changelog — v27.0 from 4.11.2026, checked 19.11.2026
Questions about the Cloud API code
Why do we always get 403 even though the App Secret is right?
Almost always because the signature is computed on JSON that was parsed and re-serialised. Use the raw request bytes, as in the code above.
Do we need a provider (BSP) to use the Cloud API?
No. We use the Cloud API directly from n8n and our own interface. A provider gives you a ready inbox and setup help, but Meta’s message prices come on top – respond.io, for example, says WhatsApp fees are not included in its plans.
Why are there duplicates in our database?
Meta retries when your server doesn’t answer 200 in time, which can deliver the same event several times. Store with the message id as a unique key.
How long does Meta keep photos customers send?
Media stays at Meta for up to 30 days, but the webhook’s media id expires after seven days and the URL after five minutes. Copy them immediately.
Fixed price, no commitment
Get a free WhatsApp check and a fixed price
Tell us briefly what you use today and what you want to achieve. A person answers by e-mail with a proposal and a fixed price before any work starts.
- A fixed price before we start
- An answer by e-mail, no calls
- Your details are used only to answer you