WhatsApp Cloud API in Django: Messages, Webhooks and CSRF
Connect Django to the WhatsApp Cloud API: settings, a send client, a model for messages, a CSRF-exempt webhook view with a signature check, and a command.

To use the WhatsApp Cloud API in Django, keep the token and app secret in settings, send with a small requests client, and receive messages in one view marked @csrf_exempt that checks the X-Hub-Signature-256 header against request.body before doing anything else. Meta’s API is plain HTTPS and JSON, so no WhatsApp package is needed.
This guide is the Django version of our Python guide, which covers the request formats with requests and a Flask webhook. Here you get what a Django project needs: settings, a reusable client, a model that stores messages and de-duplicates retries, the webhook view and its URL, and a management command that sends a template. It uses Graph API v27.0, the latest in Meta’s changelog (released 4 November 2026).
Key takeaways
- Meta’s POST carries no CSRF token, so the webhook view needs
@csrf_exempt. The signature check takes CSRF’s place. - Hash
request.body, the raw bytes, with your app secret, and compare withhmac.compare_digest. - Store each message ID with a unique constraint: Meta retries for up to 7 days, so duplicates happen.
- Register the URL with its trailing slash, or Django’s slash redirect gets in the way of Meta’s POST.
- Send from a management command or a task, never from the browser, and only templates outside the 24-hour window.
What you’ll build
A Django app called whatsapp inside your existing project, with five pieces:
| File | What it does |
|---|---|
settings.py | Reads the token, phone number ID, app secret and verify token from the environment |
whatsapp/client.py | One send() function for every message type, raising an error with Meta’s code |
whatsapp/models.py | A WhatsAppMessage model keyed on Meta’s message ID |
whatsapp/views.py | The webhook: Meta’s GET handshake and signed POSTs |
whatsapp/management/commands/send_order_update.py | Sends a template from the command line or a scheduler |
You need a phone number ID, a permanent system-user token, your Meta app’s secret and a verify token you make up. The Cloud API setup guide shows how to get them, and Meta’s test number is the safe place to try things. Run python -m pip install requests, then python manage.py startapp whatsapp and add "whatsapp" to INSTALLED_APPS.
Python code needs exact indentation, so each code table below has an Indent column: the number of spaces before that line. Blank means none.
Settings and a send client
Add these lines to settings.py (it already imports os in most projects; add import os if not):
| Indent | settings.py |
|---|---|
WHATSAPP_TOKEN = os.environ["WHATSAPP_TOKEN"] | |
WHATSAPP_PHONE_NUMBER_ID = os.environ["WHATSAPP_PHONE_NUMBER_ID"] | |
WHATSAPP_APP_SECRET = os.environ["WHATSAPP_APP_SECRET"] | |
WHATSAPP_VERIFY_TOKEN = os.environ["WHATSAPP_VERIFY_TOKEN"] | |
WHATSAPP_API_VERSION = "v27.0" |
Then whatsapp/client.py. It adds the fields every message shares, reuses one HTTP session, and raises WhatsAppError with Meta’s numeric code when a call fails:
| Indent | whatsapp/client.py |
|---|---|
import requests | |
from django.conf import settings | |
class WhatsAppError(Exception): | |
| 4 | def __init__(self, message, code=None, status=None): |
| 8 | super().__init__(message) |
| 8 | self.code = code |
| 8 | self.status = status |
_session = requests.Session() | |
def send(payload): | |
| 4 | url = f"https://graph.facebook.com/{settings.WHATSAPP_API_VERSION}/{settings.WHATSAPP_PHONE_NUMBER_ID}/messages" |
| 4 | body = {"messaging_product": "whatsapp", "recipient_type": "individual", **payload} |
| 4 | r = _session.post(url, json=body, headers={"Authorization": f"Bearer {settings.WHATSAPP_TOKEN}"}, timeout=10) |
| 4 | try: |
| 8 | data = r.json() |
| 4 | except ValueError: |
| 8 | data = {} |
| 4 | if not r.ok: |
| 8 | err = data.get("error", {}) |
| 8 | raise WhatsAppError(err.get("message", f"HTTP {r.status_code}"), err.get("code"), r.status_code) |
| 4 | return data |
Now send({"to": "919800000000", "type": "text", "text": {"body": "Hi Priya, your order has shipped."}}) works from anywhere in the project. requests sets the JSON content type itself. On success, data["messages"][0]["id"] is the wamid… that later status webhooks refer to. A successful response only means Meta accepted the request; delivery is reported by webhook.
A model that remembers every message
Meta retries webhook deliveries for up to 7 days and can batch up to 1,000 updates in one request, so the same message can reach you more than once. A unique column on Meta’s message ID makes duplicates harmless. Put this in whatsapp/models.py:
| Indent | whatsapp/models.py |
|---|---|
from django.db import models | |
class WhatsAppMessage(models.Model): | |
| 4 | wamid = models.CharField(max_length=255, unique=True) |
| 4 | direction = models.CharField(max_length=3, choices=[("in", "Incoming"), ("out", "Outgoing")]) |
| 4 | contact = models.CharField(max_length=160) |
| 4 | type = models.CharField(max_length=32) |
| 4 | body = models.TextField(blank=True) |
| 4 | status = models.CharField(max_length=16, blank=True) |
| 4 | created_at = models.DateTimeField(auto_now_add=True) |
contactholds the customer’s WhatsApp ID, or their business-scoped user ID when Meta leaves the phone number out. A BSUID is a country code, a period and up to 128 letters and digits, so 160 characters is room enough.statusfollows your outgoing messages: Meta sendssent,delivered,read,played(a voice message was played) andfailed.- Run
python manage.py makemigrations whatsappandpython manage.py migrate, and register the model inadmin.pyif you want to browse messages in Django admin.
The webhook view: CSRF exemption and the signature check
Django’s CSRF middleware rejects any POST without a CSRF token, and Meta’s webhook calls don’t carry one. Django’s docs recommend keeping the middleware on and marking the few views that don’t need it with csrf_exempt. That’s safe here only because the view checks Meta’s signature instead. Save whatsapp/views.py:
| Indent | whatsapp/views.py |
|---|---|
import hashlib, hmac, json | |
from django.conf import settings | |
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 WhatsAppMessage | |
@csrf_exempt | |
@require_http_methods(["GET", "POST"]) | |
def webhook(request): | |
| 4 | if request.method == "GET": |
| 8 | token = request.GET.get("hub.verify_token", "") |
| 8 | if request.GET.get("hub.mode") == "subscribe" and hmac.compare_digest(token.encode(), settings.WHATSAPP_VERIFY_TOKEN.encode()): |
| 12 | return HttpResponse(request.GET.get("hub.challenge", ""), content_type="text/plain") |
| 8 | return HttpResponseForbidden() |
| 4 | expected = "sha256=" + hmac.new(settings.WHATSAPP_APP_SECRET.encode(), request.body, hashlib.sha256).hexdigest() |
| 4 | given = request.headers.get("X-Hub-Signature-256", "") |
| 4 | if not hmac.compare_digest(given.encode(), expected.encode()): |
| 8 | return HttpResponseForbidden() |
| 4 | try: |
| 8 | payload = json.loads(request.body) |
| 4 | except ValueError: |
| 8 | return HttpResponseBadRequest() |
| 4 | for entry in payload.get("entry", []): |
| 8 | for change in entry.get("changes", []): |
| 12 | if change.get("field") == "messages": |
| 16 | save_change(change.get("value", {})) |
| 4 | return HttpResponse("OK") |
RANK = {"sent": 1, "delivered": 2, "read": 3, "played": 4, "failed": 9} | |
def save_change(value): | |
| 4 | for m in value.get("messages", []): |
| 8 | sender = m.get("from") or m.get("from_user_id", "") |
| 8 | text = m.get("text", {}).get("body", "") |
| 8 | msg, created = WhatsAppMessage.objects.get_or_create(wamid=m["id"], defaults={"direction": "in", "contact": sender, "type": m.get("type", ""), "body": text}) |
| 8 | if created: |
| 12 | print("new message", msg.pk) # queue your reply here; a retry has created == False |
| 4 | for s in value.get("statuses", []): |
| 8 | row, _ = WhatsAppMessage.objects.get_or_create(wamid=s["id"], defaults={"direction": "out", "contact": s.get("recipient_id") or s.get("recipient_user_id", ""), "type": ""}) |
| 8 | if RANK.get(s.get("status"), 0) > RANK.get(row.status, 0): |
| 12 | row.status = s["status"] |
| 12 | row.save(update_fields=["status"]) |
- The handshake. When you save the callback URL, Meta sends a GET with
hub.mode=subscribe, yourhub.verify_tokenand ahub.challenge. The view returns the challenge as plain text with status 200, which is what Meta expects. request.bodybefore anything else. It’s the raw request body as bytes, which is exactly what Meta signed. Don’t readrequest.POSTor the request stream first: Django raisesRawPostDataExceptionif you touchbodyafter reading the stream.- The comparison.
hmac.compare_digestcompares in constant time. Encoding both sides to bytes means a strange header can’t raise an error; it simply fails. - Saving.
get_or_createon the uniquewamidturns a retried delivery into a no-op, and itscreatedflag tells you whether this is the first time you’ve seen the message. Only a new message should trigger a reply. The sender falls back tofrom_user_id, because Meta can leavefromout for users who have a username. - Statuses only move forward. Webhooks aren’t promised to arrive in order, so
RANKstops a latedeliveredfrom overwritingread, whilefailedalways wins. A status can also beat your own code to the database (see the next section), so the view creates the outgoing row if it isn’t there yet. Failed statuses carry anerrorslist with acodeanderror_data.details; store those to see why a message failed.
require_http_methods answers anything other than GET or POST with Django’s HttpResponseNotAllowed. Payload shapes for images, button replies and statuses are in WhatsApp Cloud API webhooks.
Wire the URL and register it with Meta
Add the route to your project’s urls.py:
| Indent | urls.py |
|---|---|
from django.urls import path | |
from whatsapp import views as whatsapp_views | |
urlpatterns = [path("whatsapp/webhook/", whatsapp_views.webhook)] |
If your project already has a urlpatterns list, add the path(...) line to it instead. Then connect it to Meta:
- Deploy behind HTTPS with a valid certificate. Meta doesn’t support self-signed certificates, and
runserveris for development only, so use your normal production setup. - Add your domain to
ALLOWED_HOSTS, or Django answers Meta with a 400 error. - In your Meta app’s dashboard, open the WhatsApp webhook settings and enter the full URL with the trailing slash, for example
https://shop.example.com/whatsapp/webhook/, plus your verify token. Without the slash, Django’sAPPEND_SLASHredirect can’t pass Meta’s POST body along. - Subscribe to the messages field and make sure your app is subscribed to your WhatsApp Business Account.
- Message your business number from your phone, then open Django admin or the database: the message should be there, once.
If the handshake works but no messages arrive, work through WhatsApp webhook not receiving messages.
Send a template from a management command
Business-started messages, such as an order update the day after a purchase, must be approved templates: they’re the only messages you can send outside a customer service window, and only to people who have opted in. A management command is a tidy home for that, because cron, a scheduler or a task can run it. Create whatsapp/management/commands/send_order_update.py (add empty __init__.py files in management and commands):
| Indent | send_order_update.py |
|---|---|
from django.core.management.base import BaseCommand, CommandError | |
from whatsapp.client import WhatsAppError, send | |
from whatsapp.models import WhatsAppMessage | |
class Command(BaseCommand): | |
| 4 | help = "Send the order_update template to one customer" |
| 4 | def add_arguments(self, parser): |
| 8 | parser.add_argument("to") |
| 8 | parser.add_argument("name") |
| 8 | parser.add_argument("order") |
| 4 | def handle(self, *args, **options): |
| 8 | params = [{"type": "text", "text": options["name"]}, {"type": "text", "text": options["order"]}] |
| 8 | payload = {"to": options["to"], "type": "template", "template": {"name": "order_update", "language": {"code": "en"}, "components": [{"type": "body", "parameters": params}]}} |
| 8 | try: |
| 12 | data = send(payload) |
| 8 | except WhatsAppError as e: |
| 12 | raise CommandError(f"WhatsApp error {e.code}: {e}") |
| 8 | wamid = data["messages"][0]["id"] |
| 8 | WhatsAppMessage.objects.update_or_create(wamid=wamid, defaults={"direction": "out", "contact": options["to"], "type": "template"}) |
| 8 | self.stdout.write(self.style.SUCCESS(f"Accepted: {wamid}")) |
Run it with python manage.py send_order_update 919800000000 Priya ORD-1042. The template here has the body “Hi {{1}}, your order {{2}} has shipped.”, so the values go in that order. The command saves with update_or_create, not create, because Meta’s sent webhook can arrive between send() returning and the row being saved; if the view got there first, the command fills in the details and keeps the status. The name and language code must match an APPROVED template exactly; for named parameters, add "parameter_name" to each value. Media headers and buttons are in how to send a WhatsApp template message with the API.
| Code in CommandError | Meaning | Fix |
|---|---|---|
| 190 | Token expired or invalid | Use a permanent system-user token |
| 131047 | More than 24 hours since the customer last messaged | Send a template, not free text |
| 132001 | Template name or language not found or not approved | Copy both exactly from WhatsApp Manager |
| 130429 | Throughput limit reached | Slow down and retry with a growing delay |
Reply to customers and keep the webhook fast
When a customer writes, the 24-hour customer service window opens and you can answer with free-form messages. The quickest auto-reply is a send() call inside save_change, but a slow call to Meta, or to anything else, delays your 200 and invites retries. Better:
- Save, then hand off. The view stores the message and returns. A background job decides on the reply and calls
send(), usingm["from"]as thetonumber. If onlyfrom_user_idcame, Meta lets you send to it with arecipientfield in place ofto. - Django 6.0 has a Tasks framework (
from django.tasks import task, then.enqueue()), but Django ships no production worker: its built-in backends either run tasks immediately or not at all. For real background work, add a third-party task backend or the task queue you already use. - Only reply once per message. Queue the reply where the view prints “new message”, under
if created:, so a retried webhook doesn’t answer twice.
Avoid packages that log in to WhatsApp Web from Python. They aren’t Meta’s API and can get the number banned; see official vs unofficial WhatsApp APIs.
Django with Automate AI
If you’d rather not run Meta’s webhook yourself, Automate AI connects your number and gives your team a shared inbox, campaigns that send approved templates, and chatbots built without code. Your Django project can still send messages and templates and manage contacts through Automate AI’s REST API, with SDKs that include Python.
Automate AI can also call a Django view when something happens, with events such as message.received and message.status.update. The same view pattern works with two changes: the header is X-Webhook-Signature, and it holds the plain hex HMAC-SHA256 of the JSON body, with no sha256= prefix, made with the webhook’s secret. The secret is shown once, when you create the webhook. The API, SDKs and webhooks are included on the AI + Automation Plan and Series 4; see the WhatsApp Business API page and pricing.
Frequently asked questions
Why does Django return 403 to Meta’s webhook?
Usually the CSRF middleware: Meta’s POST has no CSRF token. Mark the webhook view with @csrf_exempt from django.views.decorators.csrf, and check the X-Hub-Signature-256 signature inside it instead.
Is it safe to use csrf_exempt on a webhook?
Yes, if the view verifies the signature first. CSRF protects views that rely on a logged-in browser session; a webhook doesn’t, and the HMAC check with your app secret proves the request came from Meta.
Why does the signature check fail in Django?
Hash request.body exactly as received, using the app secret from your Meta app’s Basic settings (not the access token), and compare with the full header including sha256=. Don’t read request.POST or the stream first.
Do I need a Django package for the WhatsApp API?
No. The Cloud API is HTTPS and JSON, so requests, a view and a model are enough. Avoid packages that automate WhatsApp Web; they aren’t the official API.
Can I message customers who haven’t written to me from Django?
Only with an approved template, and only if they’ve agreed to hear from you. Free-form text needs an open 24-hour window.
How do I stop duplicate webhook messages in Django?
Give the message ID a unique constraint and save with get_or_create. Meta retries for up to 7 days, so a delivery can arrive more than once.
Sources
- Meta: Send messages
- Meta: Templates overview
- Meta: Create a webhook endpoint
- Meta: Messages webhook reference
- Meta: Graph API changelog
- Django: How to use CSRF protection
- Django: Request and response objects
- Django: Tasks framework (6.0)
WhatsApp rules and prices change. We check these guides against Meta’s documentation, but always confirm current terms with Meta before you rely on them. Questions? Message us on WhatsApp at +91 836 977 8812.


