Bonaventure OgetoBy Bonaventure Ogeto|

Handle Paystack Webhooks in Django

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.

Create the Webhook View

# 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.

Process Webhook Events

# 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.

URL Configuration

# 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.

Async Processing with Celery

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.

Testing Webhooks Locally

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)

Production Checklist

  1. HTTPS required. Your webhook URL must use HTTPS. Configure SSL with your web server (nginx, Apache).
  2. ALLOWED_HOSTS. Make sure your production domain is in Django's ALLOWED_HOSTS setting.
  3. Respond quickly. Return 200 within a few seconds. Use Celery for heavy processing.
  4. Log events. Store every webhook event in a database table for debugging.
  5. Monitor. Check the Paystack dashboard webhook logs for failed deliveries.

Ship Payments Faster

Key Takeaways

  • Decorate your webhook view with @csrf_exempt. Paystack requests do not include Django CSRF tokens.
  • Use request.body (raw bytes) for HMAC computation. Do not use json.loads() first, as that could change the byte representation.
  • Django provides the Paystack signature header as request.META["HTTP_X_PAYSTACK_SIGNATURE"].
  • Return HttpResponse(status=200) immediately. Process events asynchronously if they involve heavy work.
  • Make handlers idempotent. Paystack may retry and send the same event multiple times.
  • The most important event for payments is charge.success. Handle subscription events if you use recurring billing.

Frequently Asked Questions

Why does my webhook return 403 Forbidden?
You probably forgot to add @csrf_exempt to your webhook view. Django CSRF protection blocks POST requests without a valid CSRF token. Paystack webhook requests do not include Django CSRF tokens.
Can I use Django REST Framework for the webhook view?
Yes. See our dedicated guide on handling Paystack webhooks in Django REST Framework. The main difference is using APIView with authentication_classes = [] and permission_classes = [] instead of @csrf_exempt.
How do I test webhooks in Django without ngrok?
Write a test that constructs the webhook payload, computes the HMAC signature with your test secret key, and POSTs to your webhook URL using Django test client. The test in this guide shows the full pattern.
Does Django parse the request body before my view runs?
Django does not parse JSON request bodies automatically like Express does. request.body gives you the raw bytes, which is exactly what you need for HMAC verification. No special middleware configuration is needed.

Ready to build real-world apps?

Join the McTaba Labs full-stack marathon (4 months full-time · 6 months part-time). Learn M-Pesa, USSD, and WhatsApp engineering while shipping 8 production apps.

Apply to the McTaba Marathon