McTaba Labs logo
Software EngineeringThe WhiteboardProjectsEventsMasterclassesWebinarsLearn
Book Call

500+ developers already in the community

Get answers, find accountability partners, and stay ahead

Join Discord →
McTaba Labs logo

Educating 1 million students in tech by 2030.

Programs

  • HighSchool Graduates Launchpad
  • AI & Business Automation
  • Corporate Training
  • McTaba Story & Mission
  • Full-Stack Curriculum
  • Course Pricing & Plans
  • Frequently Asked Questions

Resources

  • Join Discord Community
  • Tech Events in Nairobi
  • Masterclasses
  • Free Resources
  • Learn
  • Campus
  • Africa Tech Talent Report
  • Partner With Us
  • Start a Project
  • Our Work

Contact Us

  • 124 Manyani East Road, Lavington, Nairobi
  • +254727795603
  • Book a Discovery Call

Office Hours:

Mon-Fri: 9am - 2pm EAT

Sat: 10am - 12pm EAT

© 2027 McTaba Labs - A product of Edtech Industries. All rights reserved.

Privacy PolicyTerms of ServiceRefund Policy
  1. Learn
  2. Paystack for African Developers
  3. Handle Paystack Webhooks in Django
Bonaventure OgetoBy Bonaventure Ogeto|Updated July 20, 2026

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.

In this article

  1. 1. Create the Webhook View
  2. 2. Process Webhook Events
  3. 3. URL Configuration
  4. 4. Async Processing with Celery
  5. 5. Testing Webhooks Locally
  6. 6. Production Checklist
  7. 7. Ship Payments Faster

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.

Get weekly developer tips

Join 25,000+ developers. Practical guides, job tips, and new content — straight to your inbox.

No spam. Unsubscribe anytime.

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

This guide is part of the Paystack integration guides by language and framework series.

Sign up for the McTaba newsletter

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.

Learn Paystack Integration

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

Not ready? Create Free Account

Keep reading

Paystack Integration Guides by Language and Framework

A complete directory of Paystack integration guides organized by programming language and framework. Each guide covers accepting payments, verifying transactions, handling webhooks, and building subscriptions in your specific stack.

Read more

Accept Payments with Paystack in Svelte and SvelteKit

Accept Paystack payments in SvelteKit using server endpoints for backend logic and Svelte components for the frontend. This guide covers initializing transactions, inline popup checkout, redirect checkout, and verification in a single full-stack SvelteKit project.

Read more

Handle Paystack Webhooks in Flask

Receive and verify Paystack webhooks in your Flask application. This guide covers accessing request.data for raw bytes, HMAC SHA-512 signature verification, processing charge.success events, and making handlers idempotent.

Read more

Build Paystack Subscriptions in ASP.NET Core

Implement Paystack recurring billing in ASP.NET Core. This guide covers creating plans, subscribing customers through transaction initialization, handling renewal webhooks with C#, and cancelling subscriptions.

Read more

Paystack Partial Debits Explained

Partial debit lets you attempt to charge a card and capture whatever amount is available if the full amount fails. Instead of an all-or-nothing charge, you get what the card can give. This guide covers how partial debits work, when to use them, and how to handle the resulting split.

Read more

Paystack Checkout Blocked by Content Security Policy

Your Content Security Policy is blocking Paystack from loading its checkout script or iframe. You need to whitelist js.paystack.co, standard.paystack.co, and api.paystack.co in the right CSP directives.

Read more

Explore related topics

M-Pesa & African Stack

M-Pesa Daraja API tutorials, USSD development, and WhatsApp Business API guides. The African Stack that global bootcamps do not teach.

Learn to Code in Kenya

Everything a Kenyan needs to know before writing their first line of code. Career paths, real costs, hardware requirements, and honest answers about what it takes.

Learning to Code

Roadmaps, language guides, and practical advice for learning to code and launching a programming career.

Breaking Into Tech

Practical, no-nonsense guides for anyone looking to start or change their career in tech. From choosing your first language to acing interviews.

The African Stack: Skills for This Market

The skills that make Kenyan developers hard to replace: M-Pesa, USSD, WhatsApp, fintech, and building for the African market.

Bonaventure Ogeto

Bonaventure Ogeto

Founder, McTaba Labs

Bonaventure is the founder of McTaba Labs, a coding bootcamp in Nairobi, Kenya. He has spent years building products for the African market and mentoring the next generation of developers across the continent.