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.

Illustration: a Django project tree next to a phone receiving a WhatsApp order update (sample data)

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 with hmac.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:

FileWhat it does
settings.pyReads the token, phone number ID, app secret and verify token from the environment
whatsapp/client.pyOne send() function for every message type, raising an error with Meta’s code
whatsapp/models.pyA WhatsAppMessage model keyed on Meta’s message ID
whatsapp/views.pyThe webhook: Meta’s GET handshake and signed POSTs
whatsapp/management/commands/send_order_update.pySends 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):

Indentsettings.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:

Indentwhatsapp/client.py
import requests
from django.conf import settings
class WhatsAppError(Exception):
4def __init__(self, message, code=None, status=None):
8super().__init__(message)
8self.code = code
8self.status = status
_session = requests.Session()
def send(payload):
4url = f"https://graph.facebook.com/{settings.WHATSAPP_API_VERSION}/{settings.WHATSAPP_PHONE_NUMBER_ID}/messages"
4body = {"messaging_product": "whatsapp", "recipient_type": "individual", **payload}
4r = _session.post(url, json=body, headers={"Authorization": f"Bearer {settings.WHATSAPP_TOKEN}"}, timeout=10)
4try:
8data = r.json()
4except ValueError:
8data = {}
4if not r.ok:
8err = data.get("error", {})
8raise WhatsAppError(err.get("message", f"HTTP {r.status_code}"), err.get("code"), r.status_code)
4return 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:

Indentwhatsapp/models.py
from django.db import models
class WhatsAppMessage(models.Model):
4wamid = models.CharField(max_length=255, unique=True)
4direction = models.CharField(max_length=3, choices=[("in", "Incoming"), ("out", "Outgoing")])
4contact = models.CharField(max_length=160)
4type = models.CharField(max_length=32)
4body = models.TextField(blank=True)
4status = models.CharField(max_length=16, blank=True)
4created_at = models.DateTimeField(auto_now_add=True)
  • contact holds 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.
  • status follows your outgoing messages: Meta sends sent, delivered, read, played (a voice message was played) and failed.
  • Run python manage.py makemigrations whatsapp and python manage.py migrate, and register the model in admin.py if 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:

Indentwhatsapp/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):
4if request.method == "GET":
8token = request.GET.get("hub.verify_token", "")
8if request.GET.get("hub.mode") == "subscribe" and hmac.compare_digest(token.encode(), settings.WHATSAPP_VERIFY_TOKEN.encode()):
12return HttpResponse(request.GET.get("hub.challenge", ""), content_type="text/plain")
8return HttpResponseForbidden()
4expected = "sha256=" + hmac.new(settings.WHATSAPP_APP_SECRET.encode(), request.body, hashlib.sha256).hexdigest()
4given = request.headers.get("X-Hub-Signature-256", "")
4if not hmac.compare_digest(given.encode(), expected.encode()):
8return HttpResponseForbidden()
4try:
8payload = json.loads(request.body)
4except ValueError:
8return HttpResponseBadRequest()
4for entry in payload.get("entry", []):
8for change in entry.get("changes", []):
12if change.get("field") == "messages":
16save_change(change.get("value", {}))
4return HttpResponse("OK")
RANK = {"sent": 1, "delivered": 2, "read": 3, "played": 4, "failed": 9}
def save_change(value):
4for m in value.get("messages", []):
8sender = m.get("from") or m.get("from_user_id", "")
8text = m.get("text", {}).get("body", "")
8msg, created = WhatsAppMessage.objects.get_or_create(wamid=m["id"], defaults={"direction": "in", "contact": sender, "type": m.get("type", ""), "body": text})
8if created:
12print("new message", msg.pk) # queue your reply here; a retry has created == False
4for s in value.get("statuses", []):
8row, _ = WhatsAppMessage.objects.get_or_create(wamid=s["id"], defaults={"direction": "out", "contact": s.get("recipient_id") or s.get("recipient_user_id", ""), "type": ""})
8if RANK.get(s.get("status"), 0) > RANK.get(row.status, 0):
12row.status = s["status"]
12row.save(update_fields=["status"])
  1. The handshake. When you save the callback URL, Meta sends a GET with hub.mode=subscribe, your hub.verify_token and a hub.challenge. The view returns the challenge as plain text with status 200, which is what Meta expects.
  2. request.body before anything else. It’s the raw request body as bytes, which is exactly what Meta signed. Don’t read request.POST or the request stream first: Django raises RawPostDataException if you touch body after reading the stream.
  3. The comparison. hmac.compare_digest compares in constant time. Encoding both sides to bytes means a strange header can’t raise an error; it simply fails.
  4. Saving. get_or_create on the unique wamid turns a retried delivery into a no-op, and its created flag 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 to from_user_id, because Meta can leave from out for users who have a username.
  5. Statuses only move forward. Webhooks aren’t promised to arrive in order, so RANK stops a late delivered from overwriting read, while failed always 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 an errors list with a code and error_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:

Indenturls.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:

  1. Deploy behind HTTPS with a valid certificate. Meta doesn’t support self-signed certificates, and runserver is for development only, so use your normal production setup.
  2. Add your domain to ALLOWED_HOSTS, or Django answers Meta with a 400 error.
  3. 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’s APPEND_SLASH redirect can’t pass Meta’s POST body along.
  4. Subscribe to the messages field and make sure your app is subscribed to your WhatsApp Business Account.
  5. 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):

Indentsend_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):
4help = "Send the order_update template to one customer"
4def add_arguments(self, parser):
8parser.add_argument("to")
8parser.add_argument("name")
8parser.add_argument("order")
4def handle(self, *args, **options):
8params = [{"type": "text", "text": options["name"]}, {"type": "text", "text": options["order"]}]
8payload = {"to": options["to"], "type": "template", "template": {"name": "order_update", "language": {"code": "en"}, "components": [{"type": "body", "parameters": params}]}}
8try:
12data = send(payload)
8except WhatsAppError as e:
12raise CommandError(f"WhatsApp error {e.code}: {e}")
8wamid = data["messages"][0]["id"]
8WhatsAppMessage.objects.update_or_create(wamid=wamid, defaults={"direction": "out", "contact": options["to"], "type": "template"})
8self.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 CommandErrorMeaningFix
190Token expired or invalidUse a permanent system-user token
131047More than 24 hours since the customer last messagedSend a template, not free text
132001Template name or language not found or not approvedCopy both exactly from WhatsApp Manager
130429Throughput limit reachedSlow 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(), using m["from"] as the to number. If only from_user_id came, Meta lets you send to it with a recipient field in place of to.
  • 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

  1. Meta: Send messages
  2. Meta: Templates overview
  3. Meta: Create a webhook endpoint
  4. Meta: Messages webhook reference
  5. Meta: Graph API changelog
  6. Django: How to use CSRF protection
  7. Django: Request and response objects
  8. 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.