WhatsApp official API in Django: send and webhook
Integrate the official WhatsApp API into Django via CRPRO Hub: sending with requests, a webhook view with csrf_exempt, request.body, compare_digest and tests.
In Django, the integration with CRPRO Hub has an outbound side, a function that calls the API with requests, and an inbound side, a view that receives the webhook. The Hub's Python guide shows the base; this article covers what is specific to Django: CSRF protection, the raw body in request.body, the cache used to deduplicate and tests with the framework client.
Where each piece lives
Short answer: a client module to send, a view to receive, a URL and two environment variables. None of it needs a Hub package.
Create the API key in the Hub dashboard with the messages:send and webhooks:write scopes (authentication) and store the value, which is shown only once. The webhook secret, whsec_..., is also shown once, in the POST /api/v1/webhooks response. Read both from environment variables in settings.py, never from a hard-coded value.
# settings.py
import os
CRPRO_API_KEY = os.environ["CRPRO_API_KEY"]
CRPRO_WEBHOOK_SECRET = os.environ["CRPRO_WEBHOOK_SECRET"]How to send a message with requests
Short answer: requests.post with the Authorization: Bearer header, the Idempotency-Key header and json= with to, type and text. The Hub answers 202, and raise_for_status() turns an error into an exception.
- The timeout is mandatory in practice: without it requests waits indefinitely, and a slow Hub blocks the Django worker.
- The Idempotency-Key must be stable per logical message. Repeating the call with the same key and the same body returns the original response; with a different body, the Hub answers 409 IDEMPOTENCY_KEY_REUSED.
- The recipient goes in to, with the country code and digits only.
- The limits are 60 messages per minute per channel and 120 requests per minute per organization and credential.
# crpro/cliente.py
import requests
from django.conf import settings
BASE = "https://crprohub.com/api/v1"
def enviar_texto(canal: str, para: str, texto: str, chave: str) -> str:
resposta = requests.post(
f"{BASE}/channels/{canal}/messages",
headers={
"Authorization": f"Bearer {settings.CRPRO_API_KEY}",
"Idempotency-Key": chave,
},
json={"to": para, "type": "text", "text": {"body": texto}},
timeout=10,
)
resposta.raise_for_status() # 4xx e 5xx viram HTTPError
return resposta.json()["data"]["message_id"] # 202: aceita, nao entregueIf the function is called inside a view that serves the user, prefer firing the send in a background task. Sending is fast, but the 202 response only says the message was accepted and queued; the final state arrives by webhook with the message.status event, and the history lives at GET /api/v1/channels/{id}/messages.
How to receive the webhook with csrf_exempt
Short answer: a POST view decorated with csrf_exempt, which reads request.body, checks the HMAC with hmac.compare_digest and answers 200. The Hub sends no CSRF token, and without the exemption Django answers 403 before the view runs.
Django's documentation describes csrf_exempt, imported from django.views.decorators.csrf, as marking a view as exempt from the middleware's protection. It affects only that view. The exemption is only reasonable because the caller is not a browser carrying cookies and because the view authenticates the request another way, here the signature. Never exempt a view that relies on cookie sessions.
The Hub signs timestamp.delivery_id.body with HMAC SHA-256 and sends the X-Hub-Timestamp, X-Hub-Delivery-Id, X-Hub-Signature-Version and X-Hub-Signature-256 headers. request.body returns the exact bytes, which is what the computation needs. Accessing request.POST first can prevent reading the body afterwards, so read request.body first.
# crpro/views.py
import hashlib
import hmac
import json
from django.conf import settings
from django.core.cache import cache
from django.http import HttpResponse, HttpResponseForbidden
from django.views.decorators.csrf import csrf_exempt
from django.views.decorators.http import require_POST
from .tarefas import processar_evento
def assinatura_valida(headers, corpo: bytes) -> bool:
assinado = (
f"{headers.get('X-Hub-Timestamp', '')}.{headers.get('X-Hub-Delivery-Id', '')}.".encode()
+ corpo
)
esperado = hmac.new(
settings.CRPRO_WEBHOOK_SECRET.encode(), assinado, hashlib.sha256
).hexdigest()
recebido = headers.get("X-Hub-Signature-256", "").removeprefix("sha256=")
return hmac.compare_digest(esperado.encode(), recebido.encode())
@csrf_exempt
@require_POST
def webhook_crprohub(request):
corpo = request.body # bytes exatos; leia antes de tocar em request.POST
if not assinatura_valida(request.headers, corpo):
return HttpResponseForbidden()
evento = json.loads(corpo)
# O id do corpo se repete na retentativa e no replay.
if cache.add(f"crprohub:evento:{evento['id']}", 1, timeout=86400):
processar_evento(evento) # coloque numa fila se demorar
return HttpResponse(status=200)# crpro/urls.py
from django.urls import path
from . import views
urlpatterns = [path("webhooks/crprohub/", views.webhook_crprohub)]curl -X POST https://crprohub.com/api/v1/webhooks \
-H "Authorization: Bearer hub_pk_EXEMPLO_NAO_REAL" \
-H "Content-Type: application/json" \
-d '{"name":"Recebimento","url":"https://your-app.com/webhooks/crprohub/","event_types":["message.received"]}'{
"id": "6f1f0f6a-3b2c-4d1e-9a8b-0c1d2e3f4a5b",
"event": "message.received",
"channel_id": "9f6a9c1e-2f3d-4a5b-8c7d-1e2f3a4b5c6d",
"occurred_at": "2026-08-21T12:00:00.000Z",
"data": {
"message_id": "wamid.EXEMPLO123",
"from": "5521999999999",
"type": "text",
"text": "Oi, ainda tem em estoque?"
}
}Duplicates, queue and a fast response
Short answer: answer 200 quickly and deduplicate on the body id. The Hub expects a 2xx within 10 seconds, repeats a delivery up to nine times over about four days and, after 20 consecutive failures, pauses the endpoint.
The example's cache.add writes the key only if it does not exist and returns false on repeats. It depends on the cache backend: the local-memory cache is per process, so with several workers a repeat can slip through. Use a shared cache, or a table with a unique constraint on the id, if duplicates are costly. There is also the opposite risk: if processing fails after the id is marked, the Hub's retry will be discarded; in that case record the id as done at the end of processing.
| View response | When | Effect on the Hub |
|---|---|---|
| 403 | Invalid or missing signature | Counts as a failure |
| 200 | New or repeated event | Delivery complete |
| 405 | Method other than POST (require_POST) | Counts as a failure |
| 500 | Unhandled exception | Retry |
If deliveries stop, reactivate the endpoint with PATCH /api/v1/webhooks/{id} and {"status":"active"}. The diagnosis walkthrough is on the webhooks page.
How to test with the Django test client
Short answer: sign a test body with the same formula as the view and send it with self.client.post, passing the headers as HTTP_X_HUB_*. Two tests are enough: a correct signature returns 200, a swapped one returns 403.
# crpro/tests.py
import hashlib, hmac, json, time
from django.test import TestCase, override_settings
@override_settings(CRPRO_WEBHOOK_SECRET="whsec_teste")
class WebhookTest(TestCase):
def assinar(self, corpo: bytes):
ts, entrega = str(int(time.time())), "d-1"
assinado = f"{ts}.{entrega}.".encode() + corpo
sig = hmac.new(b"whsec_teste", assinado, hashlib.sha256).hexdigest()
return {"HTTP_X_HUB_TIMESTAMP": ts, "HTTP_X_HUB_DELIVERY_ID": entrega,
"HTTP_X_HUB_SIGNATURE_256": "sha256=" + sig}
def test_assinatura_certa(self):
corpo = json.dumps({"id": "e1", "event": "message.received"}).encode()
r = self.client.post("/webhooks/crprohub/", corpo, content_type="application/json", **self.assinar(corpo))
self.assertEqual(r.status_code, 200)
def test_assinatura_trocada(self):
corpo = b'{"id":"e2"}'
h = self.assinar(corpo); h["HTTP_X_HUB_SIGNATURE_256"] = "sha256=" + "0" * 64
r = self.client.post("/webhooks/crprohub/", corpo, content_type="application/json", **h)
self.assertEqual(r.status_code, 403)In the test client, custom headers go in as arguments with the HTTP_ prefix and dashes replaced by underscores, hence HTTP_X_HUB_SIGNATURE_256. In production, Django's request.headers already handles names case-insensitively. For an end-to-end test, the POST /api/v1/webhooks/{id}/test endpoint sends a real event, up to 10 times per hour per endpoint. The quickstart shows the first call end to end.
Frequently asked questions
Why does Django answer 403 to the Hub webhook?
Most likely because of CSRF protection. The Hub sends no CSRF token, so the view needs @csrf_exempt and another form of authentication, here the HMAC signature.
Can I use request.POST or request.data for the signature?
No. The signature covers the exact body bytes. Use request.body, read before any other access to the body.
Is Django's in-memory cache good enough to deduplicate?
Only with a single process. With several workers each has its own; use a shared cache or a unique constraint in the database.
What does the 202 on send mean?
That the message was accepted and queued for Meta, not that it arrived. The final state comes through the message.status webhook and the channel history.
Fontes
Documentação oficial da Meta, conferida em 31 de outubro de 2026.