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

Handle Paystack Webhooks in FastAPI

To handle Paystack webhooks in FastAPI, create a POST endpoint that reads the raw request body with await request.body(), computes an HMAC SHA-512 hash using your secret key, and compares it to the x-paystack-signature header. Process the event in a BackgroundTask and return 200.

In this article

  1. 1. Webhook Endpoint
  2. 2. Process Events
  3. 3. Signature Verification as a Dependency
  4. 4. Testing Webhooks
  5. 5. Production Notes
  6. 6. Ship Payments Faster

Webhook Endpoint

# main.py
import hmac
import hashlib
import json
from fastapi import FastAPI, Request, BackgroundTasks, HTTPException

app = FastAPI()

PAYSTACK_SECRET = config('PAYSTACK_SECRET_KEY')

@app.post('/api/webhooks/paystack')
async def paystack_webhook(request: Request, background_tasks: BackgroundTasks):
    # 1. Get signature
    signature = request.headers.get('x-paystack-signature', '')

    if not signature:
        raise HTTPException(status_code=400, detail='Missing signature')

    # 2. Get raw body
    body = await request.body()

    # 3. Compute hash
    computed_hash = hmac.new(
        PAYSTACK_SECRET.encode('utf-8'),
        msg=body,
        digestmod=hashlib.sha512,
    ).hexdigest()

    # 4. Compare
    if not hmac.compare_digest(computed_hash, signature):
        raise HTTPException(status_code=400, detail='Invalid signature')

    # 5. Parse and process in background
    event = json.loads(body)
    background_tasks.add_task(process_event, event)

    return {'status': 'ok'}

Process Events

# webhooks.py
async def process_event(event: dict):
    event_type = event.get('event')
    data = event.get('data', {})

    if event_type == 'charge.success':
        reference = data.get('reference')
        if reference:
            await verify_and_fulfill(reference, db)

    elif event_type == 'subscription.create':
        await handle_subscription_create(data)

    elif event_type == 'invoice.payment_failed':
        await handle_invoice_failed(data)

    elif event_type == 'transfer.success':
        await handle_transfer_success(data)

Get weekly developer tips

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

No spam. Unsubscribe anytime.

Signature Verification as a Dependency

# dependencies.py
async def verify_paystack_signature(request: Request) -> dict:
    signature = request.headers.get('x-paystack-signature', '')
    if not signature:
        raise HTTPException(status_code=400, detail='Missing signature')

    body = await request.body()

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

    if not hmac.compare_digest(computed_hash, signature):
        raise HTTPException(status_code=400, detail='Invalid signature')

    return json.loads(body)

# Usage:
@app.post('/api/webhooks/paystack')
async def paystack_webhook(
    event: dict = Depends(verify_paystack_signature),
    background_tasks: BackgroundTasks = BackgroundTasks(),
):
    background_tasks.add_task(process_event, event)
    return {'status': 'ok'}

The dependency pattern keeps your endpoint clean and makes the signature verification reusable and testable.

Testing Webhooks

# tests/test_webhook.py
import hmac
import hashlib
import json
from fastapi.testclient import TestClient
from main import app

client = TestClient(app)

def test_valid_webhook():
    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(
        '/api/webhooks/paystack',
        content=payload,
        headers={
            'Content-Type': 'application/json',
            'x-paystack-signature': signature,
        },
    )

    assert response.status_code == 200

Production Notes

  1. HTTPS required. Your webhook URL must use HTTPS in production.
  2. Respond quickly. BackgroundTasks run after the response is sent. Paystack gets a fast 200.
  3. For heavy processing. Use Celery or an async task queue instead of BackgroundTasks if processing takes more than a few seconds.
  4. Log events. Store every webhook event in a database for debugging.
  5. Monitor. Check the Paystack dashboard for failed webhook 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

  • ✓Use await request.body() to get the raw bytes for HMAC verification.
  • ✓FastAPI BackgroundTasks let you return 200 immediately and process the event asynchronously.
  • ✓Use hmac.compare_digest for constant-time comparison to prevent timing attacks.
  • ✓Make handlers idempotent. Paystack retries failed webhooks.
  • ✓The most important event is charge.success. Handle subscription events if you use recurring billing.
  • ✓FastAPI does not need CSRF protection since it is an API framework, so no special exemptions are needed.

Frequently Asked Questions

Does FastAPI need CSRF exemption for webhooks?
No. FastAPI is an API framework and does not have CSRF protection by default. Unlike Django, no special decorator is needed.
Should I use BackgroundTasks or Celery for webhook processing?
BackgroundTasks are simpler and work well for lightweight processing. For heavy operations (sending emails, calling external APIs, complex database updates), use Celery with a message broker like Redis.
Can I use the same endpoint for test and live webhooks?
Yes. Use the correct secret key for each mode. Test webhooks are signed with your test key, live webhooks with your live key. If you serve both, determine the mode from the webhook data or use separate keys.

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 Refunds: Full, Partial and Programmatic

Refunds are unavoidable in any payment system. Paystack gives you a Refund API to process full refunds, partial refunds, and automated refund workflows. This guide covers the conditions, timelines, webhook events, and working Node.js code for building a refund handler.

Read more

Paystack Insufficient Balance on Transfer

Your Paystack transfer fails with an insufficient balance error because your available balance is lower than the transfer amount. This is usually not about how much money has been collected. It is about how much of that money has settled and is available for withdrawal. This guide covers the difference, how to check balances before transfers, and how to fund your account.

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.