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. Verify Paystack Payments in FastAPI
Bonaventure OgetoBy Bonaventure Ogeto|Updated July 20, 2026

Verify Paystack Payments in FastAPI

To verify a Paystack payment in FastAPI, make an async GET request to the Paystack verify endpoint using httpx. Check that data.status is "success", the amount matches your database, and the currency is correct. Use an async database update with a condition to prevent double-granting.

In this article

  1. 1. Verification Service
  2. 2. Verification Endpoint
  3. 3. Verification as a Dependency
  4. 4. Retry Logic
  5. 5. Common Mistakes
  6. 6. Ship Payments Faster

Verification Service

# services.py
import httpx
from decouple import config

PAYSTACK_SECRET = config('PAYSTACK_SECRET_KEY')

async def verify_paystack_transaction(reference: str) -> dict:
    async with httpx.AsyncClient() as client:
        response = await client.get(
            'https://api.paystack.co/transaction/verify/' + reference,
            headers={'Authorization': 'Bearer ' + PAYSTACK_SECRET},
        )
    return response.json()

async def verify_and_fulfill(reference: str, db) -> dict:
    order = await db.get_order(reference)
    if not order:
        return {'success': False, 'error': 'Order not found'}

    if order.paid:
        return {'success': True, 'already_fulfilled': True}

    result = await verify_paystack_transaction(reference)

    if not result.get('status') or result['data']['status'] != 'success':
        return {'success': False, 'error': 'Payment not successful'}

    if result['data']['amount'] != order.amount_in_kobo:
        return {'success': False, 'error': 'Amount mismatch'}

    if result['data']['currency'] != order.currency:
        return {'success': False, 'error': 'Currency mismatch'}

    updated = await db.fulfill_order(reference)
    if not updated:
        return {'success': True, 'already_fulfilled': True}

    return {
        'success': True,
        'already_fulfilled': False,
        'amount': order.amount_in_kobo / 100,
        'currency': order.currency,
    }

Verification Endpoint

# main.py
from fastapi import FastAPI, HTTPException, Depends

@app.get('/api/verify')
async def verify_payment(reference: str):
    result = await verify_and_fulfill(reference, db)

    if not result['success']:
        raise HTTPException(status_code=400, detail=result['error'])

    return result

Get weekly developer tips

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

No spam. Unsubscribe anytime.

Verification as a Dependency

# dependencies.py
from fastapi import Query, HTTPException

async def verified_payment(reference: str = Query(...)):
    result = await verify_paystack_transaction(reference)

    if not result.get('status') or result['data']['status'] != 'success':
        raise HTTPException(status_code=400, detail='Payment not verified')

    return result['data']

# Usage in an endpoint:
@app.get('/api/payment/confirmed')
async def payment_confirmed(payment_data: dict = Depends(verified_payment)):
    return {
        'amount': payment_data['amount'] / 100,
        'currency': payment_data['currency'],
        'email': payment_data['customer']['email'],
    }

Retry Logic

import asyncio

async def verify_with_retry(reference: str, max_retries: int = 3) -> dict:
    for attempt in range(max_retries):
        try:
            result = await verify_paystack_transaction(reference)
            if result.get('status') is not None:
                return result
        except httpx.RequestError:
            pass

        if attempt < max_retries - 1:
            await asyncio.sleep(2 ** attempt)

    return None

FastAPI async functions work naturally with asyncio.sleep. The event loop is not blocked during the wait.

Common Mistakes

  • Using requests instead of httpx. The requests library blocks the event loop in async endpoints. Use httpx.AsyncClient.
  • Not validating the amount. Always compare the Paystack amount against your database, not the client.
  • Creating a new AsyncClient per request. For production, use a shared client with connection pooling.
  • Mixing test and live keys. Both initialization and verification must use the same mode.

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 httpx.AsyncClient for non-blocking verification calls in FastAPI async endpoints.
  • ✓Create a reusable verification dependency or service function for consistent logic across endpoints.
  • ✓Always validate amount and currency against your database, not client-submitted values.
  • ✓Use conditional database updates for idempotent fulfillment that prevents double-granting.
  • ✓Share the same verification function between your callback endpoint and webhook handler.
  • ✓FastAPI Pydantic models ensure consistent response shapes for success and error cases.

Frequently Asked Questions

Can I reuse the httpx client across requests?
Yes. Create the client in a lifespan event and store it on the app state. This enables connection pooling and is more efficient than creating a new client per request.
How do I handle verification timeouts?
Set a timeout on your httpx client: httpx.AsyncClient(timeout=10.0). If the request times out, retry. The Paystack transaction state does not change.
Should I verify in the webhook handler too?
Yes. Call the same verify_and_fulfill function from both your callback endpoint and webhook handler. The idempotent fulfillment logic ensures only one of them actually processes the order.

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 Customer Objects: Create, Fetch, Update, Whitelist

Paystack creates a customer object every time a new email hits your checkout. You can also create customers explicitly, update their details, fetch their transaction history, and whitelist or blacklist them for risk control. This guide covers every operation with working Node.js code.

Read more

Paystack Transfer OTP Required Error

Your transfer call returns an OTP required error because Paystack protects every transfer with a one-time password by default. To automate transfers, you must call the disable_otp endpoint, confirm via the finalize_disable_otp endpoint, and accept the security trade-off. This guide walks through every step with code.

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.