To handle Paystack webhooks in Django, create a view decorated with @csrf_exempt. Read request.body, compute an HMAC SHA-512 hash using your secret key, and compare it to the HTTP_X_PAYSTACK_SIGNATURE header. If they match, parse the JSON and process the event. Return HttpResponse with status 200.
# payments/views.py
import json
import hmac
import hashlib
from django.conf import settings
from django.http import HttpResponse, HttpResponseBadRequest
from django.views.decorators.csrf import csrf_exempt
from django.views.decorators.http import require_POST
@csrf_exempt
@require_POST
def paystack_webhook(request):
# 1. Get the signature
signature = request.META.get('HTTP_X_PAYSTACK_SIGNATURE', '')
if not signature:
return HttpResponseBadRequest('Missing signature')
# 2. Compute expected hash
secret = settings.PAYSTACK_SECRET_KEY.encode('utf-8')
computed_hash = hmac.new(
secret,
msg=request.body,
digestmod=hashlib.sha512,
).hexdigest()
# 3. Compare
if not hmac.compare_digest(computed_hash, signature):
return HttpResponseBadRequest('Invalid signature')
# 4. Parse and process
event = json.loads(request.body)
process_paystack_event(event)
return HttpResponse(status=200)
Key details:
@csrf_exempt is required because Paystack will not send a CSRF token with its webhook requests.@require_POST rejects non-POST requests to this endpoint.request.body gives you the raw bytes, which is what you need for HMAC computation.hmac.compare_digest performs a constant-time comparison to prevent timing attacks.# payments/webhooks.py
from .utils import verify_and_fulfill
def process_paystack_event(event):
event_type = event.get('event')
data = event.get('data', {})
if event_type == 'charge.success':
handle_successful_payment(data)
elif event_type == 'charge.failed':
handle_failed_payment(data)
elif event_type == 'subscription.create':
handle_new_subscription(data)
elif event_type == 'invoice.payment_failed':
handle_failed_renewal(data)
elif event_type == 'transfer.success':
handle_successful_transfer(data)
def handle_successful_payment(data):
reference = data.get('reference')
if reference:
verify_and_fulfill(reference)
def handle_failed_payment(data):
reference = data.get('reference')
# Log the failure for analysis
print('Payment failed for reference: ' + str(reference))
The verify_and_fulfill function from the verification guide handles the amount check, currency check, and idempotent database update. Reusing it here ensures consistent behavior whether the callback or webhook fires first.
Get weekly developer tips
Join 25,000+ developers. Practical guides, job tips, and new content — straight to your inbox.
No spam. Unsubscribe anytime.
# payments/urls.py
from django.urls import path
from . import views
urlpatterns = [
path('checkout/', views.initialize_payment, name='checkout'),
path('callback/', views.payment_callback, name='payment_callback'),
path('webhooks/paystack/', views.paystack_webhook, name='paystack_webhook'),
]
Set the webhook URL in your Paystack dashboard: https://yourdomain.com/payments/webhooks/paystack/
The trailing slash matters in Django. Make sure your Paystack dashboard URL matches your URL pattern exactly.
For heavy processing (sending emails, updating external services), use Celery to process events asynchronously:
# payments/tasks.py
from celery import shared_task
from .utils import verify_and_fulfill
@shared_task
def process_payment_task(reference):
verify_and_fulfill(reference)
# In your webhook view:
@csrf_exempt
@require_POST
def paystack_webhook(request):
# ... signature verification ...
event = json.loads(request.body)
if event.get('event') == 'charge.success':
reference = event['data'].get('reference')
if reference:
process_payment_task.delay(reference)
return HttpResponse(status=200)
This ensures Paystack gets a 200 response within milliseconds, while your actual processing happens in the background.
Use ngrok to expose your local Django server:
npx ngrok http 8000
Set the ngrok URL as your webhook URL in the Paystack dashboard.
For automated tests, create the HMAC signature yourself:
# payments/tests.py
import json
import hmac
import hashlib
from django.test import TestCase, Client
from django.conf import settings
class WebhookTest(TestCase):
def test_valid_webhook(self):
payload = json.dumps({
'event': 'charge.success',
'data': {
'reference': 'test_ref_123',
'amount': 500000,
'currency': 'NGN',
'status': 'success',
},
})
signature = hmac.new(
settings.PAYSTACK_SECRET_KEY.encode('utf-8'),
msg=payload.encode('utf-8'),
digestmod=hashlib.sha512,
).hexdigest()
client = Client()
response = client.post(
'/payments/webhooks/paystack/',
data=payload,
content_type='application/json',
HTTP_X_PAYSTACK_SIGNATURE=signature,
)
self.assertEqual(response.status_code, 200)
KES 2,999
The definitive guide to building payment systems with Paystack — from your first transaction to production-grade payment infrastructure across Africa. 9 modules, 47 lessons. Free preview available.
Start Paystack Course