# Ricevere i webhook di WhatsApp in Django

> Verifica il webhook WhatsApp in Django 6.1, fai l'hash di request.body per X-Hub-Signature-256, salva ogni evento una volta per wamid e rispondi 200 prima del lavoro.

Published 2026-11-04. Z-API Omni team.

Ricevi i webhook della WhatsApp Cloud API in Django con una sola function view per GET e POST, marcata `@csrf_exempt`. Il GET legge `request.GET["hub.mode"]` così com'è e restituisce il challenge come testo semplice. Il POST calcola l'hash di `request.body` per `X-Hub-Signature-256`, salva ogni messaggio e ogni stato una sola volta in una tabella con chiave sul wamid e restituisce 200. Un management command fa il lavoro dopo. Il codice richiede solo Django e la libreria standard.

## Installare Django 6.1

Django 6.1.3 è l'ultima release ufficiale ([download di Django, consultato il 2026-11-04](https://www.djangoproject.com/download/)). La serie 6.1 è uscita il 5 agosto 2026 e supporta Python dalla 3.12 alla 3.15 ([note di rilascio di Django 6.1](https://docs.djangoproject.com/en/6.1/releases/6.1/)). Il framework dei task integrato, usato nell'ultima sezione, è arrivato con la 6.0. I progetti sulla 5.2 LTS non hanno `django.tasks`, e la documentazione di Django li rimanda al backport `django-tasks`.

```bash
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"
```

## Aggiungere modello, view, URL e worker

Aggiungi queste righe in fondo al file di settings generato:

```python
# 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
```

Il modello è insieme la tabella di deduplicazione e la coda di lavoro:

```python
# 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"])
```

La view risponde a entrambi i metodi:

```python
# 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},
    )
```

Instradala nell'URLconf del progetto:

```python
# 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),
]
```

Il worker è un management command:

```python
# 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
```

Crea la tabella e avvia il server:

```bash
python manage.py makemigrations whatsapp
python manage.py migrate
python manage.py runserver
```

Nell'App Dashboard, inserisci l'URL di callback con la barra finale, `https://YOUR_DOMAIN/webhooks/whatsapp/`, e iscriviti al campo `messages`.

## Leggere hub.mode direttamente da request.GET

`request.GET["hub.mode"]` funziona perché Django salva le chiavi della query così come vengono analizzate. `QueryDict.__init__` esegue `parse_qsl` e chiama `self.appendlist(key, value)` con la chiave invariata ([django/http/request.py, stable/6.1.x](https://github.com/django/django/blob/stable/6.1.x/django/http/request.py)). La documentazione non parla dei punti, quindi qui il riferimento è il sorgente. PHP trasforma i punti in underscore ([Meta, webhook della Graph API, consultato il 2026-11-04](https://developers.facebook.com/docs/graph-api/webhooks/getting-started)), ed è per questo che la [guida per Laravel](/academy/it/articles/whatsapp-webhook-laravel-receive-messages/) legge `hub_mode`.

Il challenge torna indietro tramite `HttpResponse(challenge, content_type="text/plain")` come corpo nudo ([oggetti request e response](https://docs.djangoproject.com/en/6.1/ref/request-response/)). Quando il token corrisponde, Meta vuole un 200 con il valore di `hub.challenge`, e qualsiasi altra risposta lascia l'endpoint non verificato ([Meta, creare un endpoint webhook, consultato il 2026-11-04](https://developers.facebook.com/documentation/business-messaging/whatsapp/webhooks/create-webhook-endpoint)).

## csrf_exempt, poi request.body prima di tutto

La protezione CSRF di Django copre tutti i metodi tranne GET, HEAD, OPTIONS e TRACE, quindi il POST di Meta, che non porta alcun token CSRF, verrebbe rifiutato. `csrf_exempt` «contrassegna una view come esente dalla protezione garantita dal middleware» ([protezione CSRF](https://docs.djangoproject.com/en/6.1/ref/csrf/)). `require_http_methods(["GET", "POST"])` restituisce un `HttpResponseNotAllowed` per qualsiasi altro metodo ([decoratori delle view](https://docs.djangoproject.com/en/6.1/topics/http/decorators/)).

`request.body` è «il corpo grezzo della richiesta HTTP come bytestring». Leggilo prima di `request.POST` o `request.read()`. Accedere a `body` dopo una lettura dello stream solleva `RawPostDataException`. La view calcola l'hash di quei byte e poi esegue `json.loads` sugli stessi byte. L'hash di un JSON riserializzato si rompe con accenti ed emoji, come mostra la [guida alla verifica della firma](/academy/it/articles/whatsapp-webhook-signature-verification-x-hub-signature-256/).

`request.headers` non distingue maiuscole e minuscole, quindi `request.headers.get("X-Hub-Signature-256")` trova l'header con qualsiasi combinazione di lettere. La chiamata a `compare_digest` e la sua codifica dei byte sono le stesse del [receiver FastAPI](/academy/it/articles/whatsapp-webhook-python-fastapi-receive-messages/).

## Alzare DATA_UPLOAD_MAX_MEMORY_SIZE oltre 3 MB

`DATA_UPLOAD_MAX_MEMORY_SIZE` vale per default 2,5 MB. Django lo controlla «quando accedi a `request.body` o `request.POST`», contando l'intero payload grezzo, e solleva `RequestDataTooBig` quando viene superato ([settings](https://docs.djangoproject.com/en/6.1/ref/settings/)). Meta dice che i suoi payload webhook «possono arrivare fino a 3 MB» ([Meta, panoramica dei webhook, consultato il 2026-11-04](https://developers.facebook.com/documentation/business-messaging/whatsapp/webhooks/overview)).

Con il default, un batch grande fallisce alla prima riga del ramo POST, prima del controllo della firma. Meta riceve un non-200 e ritenta quella consegna per un massimo di 7 giorni, e ogni nuovo tentativo fallisce di nuovo. I 4 MiB nei settings qui sopra sono una scelta di questo articolo.

## Salvare una volta, restituire 200, elaborare dopo

La pagina sul throughput di Meta chiede una «latenza mediana non superiore a 250 ms» per le risposte ai webhook, con meno dell'1% oltre un secondo ([Meta, throughput](https://developers.facebook.com/documentation/business-messaging/whatsapp/throughput)). Il POST scrive una riga per ogni messaggio o stato dentro una transazione e risponde. Le chiamate al CRM e all'AI vengono eseguite dopo, nel command.

I nuovi tentativi «possono generare notifiche webhook duplicate», quindi la tabella deduplica sugli ID. `get_or_create` restituisce `(object, created)` ed è «atomico a condizione che il database imponga l'unicità degli argomenti keyword» ([API di QuerySet](https://docs.djangoproject.com/en/6.1/ref/models/querysets/)). Senza `unique=True` su `event_id`, due nuovi tentativi concorrenti potrebbero inserire due righe. Un messaggio usa `msg:<wamid>`. Gli stati aggiungono lo stato, perché sent, delivered e read arrivano con lo stesso wamid come eventi separati. Meta non documenta una lunghezza massima del wamid, quindi `max_length=255` è un margine.

La riga rende anche l'evento durevole. Un task in background nello stesso processo muore con il processo dopo il suo 200, mentre una riga con commit sopravvive a un riavvio. Esegui `python manage.py process_whatsapp_events --loop` sotto il tuo process manager. Eseguine una sola copia, perché due copie possono prendere le stesse righe in sospeso. Un evento il cui `handle()` solleva un'eccezione resta in sospeso e viene ritentato a ogni passata, quindi tieni d'occhio stderr. [Architettura a coda per i webhook](/academy/it/articles/whatsapp-webhook-queue-architecture-workers/) spiega il passaggio a una vera coda con più worker.

`contact` contiene `from`, oppure `from_user_id` quando `from` manca. Meta dice che `from` «viene omesso se il numero di telefono non può essere incluso». I BSUID «hanno iniziato a comparire nei webhook all'inizio di aprile 2026» ([Meta, business-scoped user ID, consultato il 2026-11-04](https://developers.facebook.com/documentation/business-messaging/whatsapp/business-scoped-user-ids)). Gli stati usano `recipient_id`, poi `recipient_user_id`. [Business-scoped user ID](/academy/it/articles/whatsapp-usernames-business-scoped-user-ids/) copre la tabella dei contatti.

## Il framework dei task di Django al posto del command

La documentazione di Django dice che il framework «non fornisce un meccanismo di worker per eseguire i Task», e che l'esecuzione «deve essere gestita da un'infrastruttura esterna a Django» ([task di Django](https://docs.djangoproject.com/en/6.1/topics/tasks/)). Il default è `ImmediateBackend`, che «esegue subito i Task accodati, invece che in background». Senza un setting `TASKS`, `.enqueue()` esegue `handle()` dentro la richiesta, e il 200 lo aspetta. I backend integrati «sono solo per sviluppo e test».

Per usarlo, definisci un task e accodalo una volta che la riga ha ricevuto il commit. Gli argomenti devono essere serializzabili in JSON, quindi passa la chiave primaria, non l'istanza del modello:

```python
# 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()
```

Poi sostituisci `save_event` in `views.py` con questa versione. La view esegue già `store()` dentro `transaction.atomic()`, quindi il task viene accodato solo dopo il commit della riga:

```python
# 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
```

In produzione serve un backend con «un processo worker e un'implementazione di coda durevole». La pagina sull'ecosistema di Django elenca django-tasks-db (basato sull'ORM), django-tasks-rq e huey ([ecosistema di Django](https://www.djangoproject.com/community/ecosystem/)). Installalo con `python -m pip install django-tasks-db` e aggiungi `"django_tasks_db"` a `INSTALLED_APPS`, come mostra il suo README ([README di django-tasks-db, consultato il 2026-11-04](https://github.com/RealOrangeOne/django-tasks-db)):

```python
# config/settings.py
INSTALLED_APPS.append("django_tasks_db")
TASKS = {"default": {"BACKEND": "django_tasks_db.DatabaseBackend", "QUEUES": ["default"]}}
```

Esegui `python manage.py migrate`, come per qualsiasi app ORM, poi esegui `./manage.py db_worker` al posto del management command. Il README non indica né una versione né un intervallo di versioni di Django supportate, quindi controlla la sua pagina delle release prima di fissarla.

## Provarlo

Avvia il server e controlla il GET. Dovrebbe stampare `123`:

```bash
curl "http://localhost:8000/webhooks/whatsapp/?hub.mode=subscribe&hub.verify_token=$VERIFY_TOKEN&hub.challenge=123"
```

Firma l'esempio di webhook di testo di Meta, compattato su una riga, e invialo:

```bash
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
```

Il POST restituisce 200 e il command stampa la riga del messaggio. Invia di nuovo lo stesso file e riesegui il command. Il POST restituisce 200 e il command non stampa nulla, perché `event_id` esiste già. Modifica un carattere di `sample.json` senza firmarlo di nuovo e il POST restituisce 401. Per provare il fallback, rinomina `"from"` in `"from_user_id"`, cambia l'ID del messaggio, poi firma di nuovo e invia.

*Il team di Z-API Omni*
