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 Flask
Bonaventure OgetoBy Bonaventure Ogeto|Updated July 20, 2026

Handle Paystack Webhooks in Flask

To handle Paystack webhooks in Flask, create a POST route that reads request.data (raw bytes), computes an HMAC SHA-512 hash using your secret key, and compares it to the X-Paystack-Signature header. Parse the JSON and process the event. Return an empty response with status 200.

In this article

  1. 1. Webhook Route
  2. 2. Process Events
  3. 3. Testing Webhooks
  4. 4. Local Development with ngrok
  5. 5. Production Notes
  6. 6. Ship Payments Faster

Webhook Route

# app.py
import hmac
import hashlib
import json
import os
from flask import Flask, request

app = Flask(__name__)
PAYSTACK_SECRET = os.environ.get('PAYSTACK_SECRET_KEY')

@app.route('/webhooks/paystack', methods=['POST'])
def paystack_webhook():
    signature = request.headers.get('X-Paystack-Signature', '')

    if not signature:
        return 'Missing signature', 400

    computed_hash = hmac.new(
        PAYSTACK_SECRET.encode('utf-8'),
        msg=request.data,
        digestmod=hashlib.sha512,
    ).hexdigest()

    if not hmac.compare_digest(computed_hash, signature):
        return 'Invalid signature', 400

    event = json.loads(request.data)
    process_event(event)

    return '', 200

request.data in Flask gives you the raw bytes of the request body. This is exactly what you need for HMAC computation. No special middleware or configuration is required.

Process Events

def process_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':
        print('Payment failed: ' + str(data.get('reference')))
    elif event_type == 'subscription.create':
        handle_new_subscription(data)
    elif event_type == 'invoice.payment_failed':
        handle_failed_renewal(data)

def handle_successful_payment(data):
    from helpers import verify_and_fulfill
    reference = data.get('reference')
    if reference:
        verify_and_fulfill(reference, db)

Get weekly developer tips

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

No spam. Unsubscribe anytime.

Testing Webhooks

# test_webhook.py
import hmac
import hashlib
import json

def test_valid_webhook(client):
    payload = json.dumps({
        'event': 'charge.success',
        'data': {'reference': 'test_123', 'amount': 500000},
    })

    signature = hmac.new(
        b'sk_test_xxx',
        msg=payload.encode(),
        digestmod=hashlib.sha512,
    ).hexdigest()

    response = client.post(
        '/webhooks/paystack',
        data=payload,
        content_type='application/json',
        headers={'X-Paystack-Signature': signature},
    )

    assert response.status_code == 200

Local Development with ngrok

npx ngrok http 5000

Set the ngrok HTTPS URL as your webhook URL in the Paystack dashboard: https://abc123.ngrok.io/webhooks/paystack

Production Notes

  1. HTTPS required. Use gunicorn behind nginx with SSL.
  2. Respond quickly. Return 200 within seconds. Use Celery for heavy processing.
  3. Idempotent handlers. Check if the event was already processed.
  4. Log everything. Store webhook events in a database for debugging.

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

  • ✓Flask provides request.data as raw bytes, which is exactly what you need for HMAC verification.
  • ✓Use hmac.compare_digest for constant-time signature comparison.
  • ✓Return a 200 status immediately. Process events after responding if they are heavy.
  • ✓Make handlers idempotent. Paystack retries failed deliveries.
  • ✓The key events are charge.success for one-time payments and subscription.create for subscriptions.
  • ✓Flask does not have CSRF protection by default, so no special exemption is needed for webhooks.

Frequently Asked Questions

Does Flask need CSRF exemption for webhooks?
Flask does not have CSRF protection by default. If you are using Flask-WTF with CSRFProtect, you need to exempt the webhook route using csrf.exempt or the @csrf.exempt decorator.
Can I use Flask-CORS with the webhook route?
Webhooks are server-to-server calls. CORS is a browser security feature and does not apply to Paystack webhook requests. You do not need Flask-CORS for the webhook route.
How do I process webhooks asynchronously in Flask?
Use Celery with Redis or RabbitMQ. Add the event to a Celery task in your route, return 200, and let the worker process it in the background.

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

Verify Paystack Payments in Flask

Verify Paystack payments server-side in your Flask application. This guide covers calling the Paystack verify endpoint, validating amounts and currencies, building reusable verification helpers, and preventing double-granting.

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

Accepting USSD Payments Through Paystack

USSD payments let customers pay by dialing a code on their phone. No smartphone, no data connection, no card needed. This guide covers how USSD payments work on Paystack, which banks support them, and how to handle the asynchronous confirmation flow.

Read more

Paystack Card Not Supported for Recurring

When Paystack says a card is not supported for recurring charges, the card type or issuing bank blocks tokenization. This guide covers why it happens, which card types are affected, how to handle it gracefully, and alternative billing strategies.

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.