Receive WhatsApp Cloud API webhooks in Django with one function view for GET and POST, marked @csrf_exempt. The GET reads request.GET["hub.mode"] as is and returns the challenge as plain text. The POST hashes request.body for X-Hub-Signature-256, stores each message and status once in a table keyed on the wamid and returns 200. A management command does the work afterwards. The code needs Django and the standard library only.
Install Django 6.1
Django 6.1.3 is the latest official release (Django download, accessed 2026-11-04). The 6.1 series came out on August 5, 2026 and supports Python 3.12 to 3.15 (Django 6.1 release notes). The built-in tasks framework in the last section arrived in 6.0. Projects on 5.2 LTS don’t have django.tasks, and Django’s docs point them to the django-tasks backport.
python3 -m venv .venv && . .venv/bin/activate
python -m pip install "Django>=6.1,<6.2"
django-admin startproject config .
python manage.py startapp whatsapp
mkdir -p whatsapp/management/commands
touch whatsapp/management/__init__.py whatsapp/management/commands/__init__.py
export APP_SECRET="APP_SECRET"
export VERIFY_TOKEN="VERIFY_TOKEN"
Add the model, view, URL and worker
Add these lines to the end of the generated settings file:
# config/settings.py, at the end
INSTALLED_APPS.append("whatsapp")
DATA_UPLOAD_MAX_MEMORY_SIZE = 4 * 1024 * 1024 # Meta sends up to 3 MB; Django's default is 2.5 MB
The model is the dedupe table and the work queue at once:
# whatsapp/models.py
from django.db import models
from django.utils import timezone
class WebhookEvent(models.Model):
# msg:<wamid> for messages, status:<wamid>:<status> for statuses
event_id = models.CharField(max_length=255, unique=True)
kind = models.CharField(max_length=8) # "message" or "status"
phone_number_id = models.CharField(max_length=64, blank=True) # your business number
contact = models.CharField(max_length=255, blank=True) # the user's phone number or BSUID
payload = models.JSONField() # the message or status object as Meta sent it
received_at = models.DateTimeField(auto_now_add=True)
processed_at = models.DateTimeField(null=True, blank=True)
def handle(self):
"""Your business logic goes here. Printing stands in for it."""
data = self.payload
if self.kind == "message":
kind = data.get("type")
text = data.get("text", {}).get("body") if kind == "text" else f"[{kind}]"
print(f"message {data['id']} from {self.contact} at {data.get('timestamp')}: {text}", flush=True)
else:
print(f"status {data['status']} for {data['id']} to {self.contact}", flush=True)
if data["status"] == "failed":
print(data.get("errors", []), flush=True)
self.processed_at = timezone.now()
self.save(update_fields=["processed_at"])
The view answers both methods:
# whatsapp/views.py
import hashlib
import hmac
import json
import os
from django.db import transaction
from django.http import HttpResponse, HttpResponseBadRequest, HttpResponseForbidden
from django.views.decorators.csrf import csrf_exempt
from django.views.decorators.http import require_http_methods
from .models import WebhookEvent
# .get() so manage.py commands still run without the secrets set
APP_SECRET = os.environ.get("APP_SECRET", "").encode()
VERIFY_TOKEN = os.environ.get("VERIFY_TOKEN", "")
@csrf_exempt
@require_http_methods(["GET", "POST"])
def whatsapp_webhook(request):
if request.method == "GET":
return verify(request)
raw = request.body # read first: the exact bytes Meta signed
if not valid_signature(raw, request.headers.get("X-Hub-Signature-256")):
return HttpResponse(status=401)
try:
payload = json.loads(raw)
except ValueError:
return HttpResponseBadRequest()
with transaction.atomic():
store(payload)
return HttpResponse(status=200)
def verify(request):
mode = request.GET.get("hub.mode") # Django keeps the dots in query keys
token = request.GET.get("hub.verify_token")
challenge = request.GET.get("hub.challenge")
if VERIFY_TOKEN and mode == "subscribe" and token == VERIFY_TOKEN and challenge is not None:
return HttpResponse(challenge, content_type="text/plain")
return HttpResponseForbidden()
def valid_signature(raw, header):
if not APP_SECRET or not header or not header.startswith("sha256="):
return False # an empty secret would let anyone sign
expected = hmac.new(APP_SECRET, raw, hashlib.sha256).hexdigest()
return hmac.compare_digest(expected.encode(), header[7:].encode("utf-8", "replace"))
def store(payload):
if payload.get("object") != "whatsapp_business_account":
return
for entry in payload.get("entry", []):
for change in entry.get("changes", []):
if change.get("field") != "messages":
continue
value = change.get("value", {})
number = value.get("metadata", {}).get("phone_number_id", "")
for msg in value.get("messages", []):
sender = msg.get("from") or msg.get("from_user_id")
save_event(f"msg:{msg['id']}", "message", number, sender, msg)
for st in value.get("statuses", []):
recipient = st.get("recipient_id") or st.get("recipient_user_id")
save_event(f"status:{st['id']}:{st['status']}", "status", number, recipient, st)
def save_event(event_id, kind, number, contact, data):
return WebhookEvent.objects.get_or_create(
event_id=event_id,
defaults={"kind": kind, "phone_number_id": number, "contact": contact or "", "payload": data},
)
Route it in the project URLconf:
# config/urls.py
from django.contrib import admin
from django.urls import path
from whatsapp import views
urlpatterns = [
path("admin/", admin.site.urls),
path("webhooks/whatsapp/", views.whatsapp_webhook),
]
The worker is a management command:
# whatsapp/management/commands/process_whatsapp_events.py
import time
from django.core.management.base import BaseCommand
from whatsapp.models import WebhookEvent
class Command(BaseCommand):
help = "Process stored WhatsApp webhook events that have no processed_at yet."
def add_arguments(self, parser):
parser.add_argument("--loop", action="store_true", help="keep polling when nothing is pending")
def handle(self, *args, **options):
while True:
batch = list(WebhookEvent.objects.filter(processed_at__isnull=True).order_by("id")[:100])
done = 0
for event in batch:
try:
event.handle()
done += 1
except Exception as exc: # the event stays pending for the next run
self.stderr.write(f"{event.event_id}: {exc!r}")
if done == 0: # nothing new, or only failing events
if not options["loop"]:
break
time.sleep(2) # wait instead of spinning
Create the table and start the server:
python manage.py makemigrations whatsapp
python manage.py migrate
python manage.py runserver
In the App Dashboard, enter the callback URL with the trailing slash, https://YOUR_DOMAIN/webhooks/whatsapp/, and subscribe to the messages field.
Read hub.mode straight from request.GET
request.GET["hub.mode"] works because Django stores query keys as parsed. QueryDict.__init__ runs parse_qsl and calls self.appendlist(key, value) with the key unchanged (django/http/request.py, stable/6.1.x). The prose docs don’t mention dots, so the source is the reference here. PHP turns the periods into underscores (Meta Graph API webhooks, accessed 2026-11-04), which is why the Laravel guide reads hub_mode.
The challenge goes back through HttpResponse(challenge, content_type="text/plain") as the bare body (request and response objects). When the token matches, Meta wants a 200 with the hub.challenge value, and any other answer leaves the endpoint unverified (Meta create a webhook endpoint, accessed 2026-11-04).
csrf_exempt, then request.body before anything else
Django’s CSRF protection covers every method other than GET, HEAD, OPTIONS and TRACE, so Meta’s POST, which carries no CSRF token, would be rejected. csrf_exempt “marks a view as being exempt from the protection ensured by the middleware” (CSRF protection). require_http_methods(["GET", "POST"]) returns an HttpResponseNotAllowed for anything else (view decorators).
request.body is “The raw HTTP request body as a bytestring”. Read it before request.POST or request.read(). Accessing body after a stream read raises RawPostDataException. The view hashes those bytes and then runs json.loads on the same bytes. A hash of re-serialized JSON breaks on accents and emoji, as the signature verification guide shows.
request.headers is case insensitive, so request.headers.get("X-Hub-Signature-256") finds the header in any letter case. The compare_digest call and its byte encoding match the FastAPI receiver.
Raise DATA_UPLOAD_MAX_MEMORY_SIZE above 3 MB
DATA_UPLOAD_MAX_MEMORY_SIZE defaults to 2.5 MB. Django checks it “when you access request.body or request.POST”, counting the whole raw payload, and raises RequestDataTooBig when it’s exceeded (settings). Meta says its webhook payloads “can be up to 3 MB” (Meta webhooks overview, accessed 2026-11-04).
With the default, a large batch fails at the first line of the POST branch, before the signature check. Meta gets a non-200 and retries that delivery for up to 7 days, and every retry fails again. The 4 MiB in the settings above is this post’s choice.
Store once, return 200, process later
Meta’s throughput page asks for a “Median latency not to exceed 250ms” on webhook responses, with fewer than 1% above one second (Meta throughput). The POST writes one row per message or status inside a transaction and answers. CRM and AI calls run later in the command.
Retries “can result in duplicate webhook notifications”, so the table dedupes on IDs. get_or_create returns (object, created) and is “atomic assuming that the database enforces uniqueness of the keyword arguments” (QuerySet API). Without unique=True on event_id, two concurrent retries could insert two rows. A message uses msg:<wamid>. Statuses add the status, because sent, delivered and read arrive with the same wamid as separate events. Meta documents no maximum wamid length, so max_length=255 is a margin.
The row also makes the event durable. An in-process background task dies with the process after its 200, but a committed row survives a restart. Run python manage.py process_whatsapp_events --loop under your process manager. Run only one copy, because two copies can pick the same pending rows. An event whose handle() raises stays pending and is retried on every pass, so watch stderr. Webhook queue architecture covers moving to a real queue with several workers.
contact holds from, or from_user_id when from is missing. Meta says from “Will be omitted if the phone number cannot be included”. BSUIDs “began appearing in webhooks in early April 2026” (Meta business-scoped user IDs, accessed 2026-11-04). Statuses use recipient_id, then recipient_user_id. Business-scoped user IDs covers the contact table.
Django’s tasks framework instead of the command
Django’s docs say the framework “does not provide a worker mechanism to run Tasks”, and execution “must be handled by infrastructure outside Django” (Django tasks). The default is ImmediateBackend, which “runs enqueued Tasks immediately, rather than in the background”. With no TASKS setting, .enqueue() runs handle() inside the request, and the 200 waits for it. The built-in backends “are for development and testing only”.
To use it, define a task and enqueue it once the row is committed. Arguments must be JSON-serializable, so pass the primary key, not the model instance:
# whatsapp/tasks.py
from django.tasks import task
from .models import WebhookEvent
@task
def process_event(event_pk: int) -> None:
event = WebhookEvent.objects.get(pk=event_pk)
if event.processed_at is None:
event.handle()
Then replace save_event in views.py with this version. The view already runs store() inside transaction.atomic(), so the task is enqueued only after the row commits:
# whatsapp/views.py: replaces save_event
from functools import partial
from .tasks import process_event
def save_event(event_id, kind, number, contact, data):
event, created = WebhookEvent.objects.get_or_create(
event_id=event_id,
defaults={"kind": kind, "phone_number_id": number, "contact": contact or "", "payload": data},
)
if created:
transaction.on_commit(partial(process_event.enqueue, event_pk=event.pk))
return event, created
Production needs a backend with “a worker process and a durable queue implementation”. Django’s ecosystem page lists django-tasks-db (ORM-based), django-tasks-rq and huey (Django ecosystem). Install it with python -m pip install django-tasks-db and add "django_tasks_db" to INSTALLED_APPS, as its README shows (django-tasks-db README, accessed 2026-11-04):
# config/settings.py
INSTALLED_APPS.append("django_tasks_db")
TASKS = {"default": {"BACKEND": "django_tasks_db.DatabaseBackend", "QUEUES": ["default"]}}
Run python manage.py migrate, as for any ORM app, then run ./manage.py db_worker in place of the management command. The README shows no version or supported Django range, so check its release page before you pin it.
Test it
Run the server and check the GET. It should print 123:
curl "http://localhost:8000/webhooks/whatsapp/?hub.mode=subscribe&hub.verify_token=$VERIFY_TOKEN&hub.challenge=123"
Sign Meta’s text webhook sample, compacted to one line, and post it:
cat > sample.json <<'EOF'
{"object":"whatsapp_business_account","entry":[{"id":"102290129340398","changes":[{"value":{"messaging_product":"whatsapp","metadata":{"display_phone_number":"15550783881","phone_number_id":"106540352242922"},"contacts":[{"profile":{"name":"Sheena Nelson"},"wa_id":"16505551234"}],"messages":[{"from":"16505551234","id":"wamid.HBgLMTY1MDM4Nzk0MzkVAgASGBQzQTRBNjU5OUFFRTAzODEwMTQ0RgA=","timestamp":"1749416383","type":"text","text":{"body":"Does it come in another color?"}}]},"field":"messages"}]}]}
EOF
SIG=$(openssl dgst -sha256 -hmac "$APP_SECRET" sample.json | awk '{print $NF}')
curl -i -X POST http://localhost:8000/webhooks/whatsapp/ \
-H "Content-Type: application/json" \
-H "X-Hub-Signature-256: sha256=$SIG" \
--data-binary @sample.json
python manage.py process_whatsapp_events
The POST returns 200 and the command prints the message line. Post the same file again and rerun the command. The POST returns 200 and the command prints nothing, because event_id already exists. Edit one character of sample.json without re-signing and the POST returns 401. To exercise the fallback, rename "from" to "from_user_id", change the message ID, then re-sign and post.
Z-API Omni team