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

Verify Paystack Payments in Flask

To verify a Paystack payment in Flask, make a GET request to https://api.paystack.co/transaction/verify/:reference using the requests library. Check that the status is "success", the amount matches your stored order, and the currency is correct. Use a database update with a condition to prevent double-granting.

In this article

  1. 1. Verification Helper
  2. 2. Verification Route
  3. 3. Callback Route with Verification
  4. 4. Retry Logic
  5. 5. Common Mistakes
  6. 6. Ship Payments Faster

Verification Helper

# helpers.py
import os
import requests

PAYSTACK_SECRET = os.environ.get('PAYSTACK_SECRET_KEY')

def verify_transaction(reference):
    response = requests.get(
        'https://api.paystack.co/transaction/verify/' + reference,
        headers={'Authorization': 'Bearer ' + PAYSTACK_SECRET},
    )
    return response.json()

def verify_and_fulfill(reference, db):
    order = db.get_order(reference)
    if not order:
        return {'error': 'Order not found'}

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

    result = verify_transaction(reference)

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

    if result['data']['amount'] != order['amount_kobo']:
        return {'error': 'Amount mismatch'}

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

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

    return {'success': True, 'amount': order['amount_kobo'] / 100}

Verification Route

# app.py
from flask import request, jsonify
from helpers import verify_and_fulfill

@app.route('/api/verify')
def verify_payment():
    reference = request.args.get('reference')
    if not reference:
        return jsonify({'error': 'Missing reference'}), 400

    result = verify_and_fulfill(reference, db)

    if result.get('error'):
        return jsonify(result), 400

    return jsonify(result)

Get weekly developer tips

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

No spam. Unsubscribe anytime.

Callback Route with Verification

@app.route('/payment/callback')
def payment_callback():
    reference = request.args.get('reference') or request.args.get('trxref')

    if not reference:
        return 'Missing reference', 400

    result = verify_and_fulfill(reference, db)

    if result.get('success'):
        return render_template('success.html', reference=reference)

    return render_template('failed.html', error=result.get('error', 'Unknown'))

Retry Logic

import time

def verify_with_retry(reference, max_retries=3):
    for attempt in range(max_retries):
        try:
            result = verify_transaction(reference)
            if result.get('status') is not None:
                return result
        except requests.exceptions.RequestException:
            pass

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

    return None

Common Mistakes

  • Trusting form data for amounts. Always compare against your database.
  • Mixing test and live keys. Both initialization and verification must use the same mode.
  • Not checking currency. An attacker could pay in a different currency.
  • Granting value before database check. Always check if the order exists and is not already fulfilled.

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

  • ✓Verification is a single GET request to the Paystack API using the requests library.
  • ✓Create a reusable verify_and_fulfill function for consistent logic across callbacks and webhooks.
  • ✓Always check three things: status equals "success", amount matches your database, and currency is correct.
  • ✓Use conditional database updates to prevent double-granting when webhook and callback race.
  • ✓If the verify request fails, retry. The Paystack transaction state does not change.
  • ✓Never trust redirect URL parameters as proof of payment.

Frequently Asked Questions

Can I verify a transaction multiple times?
Yes. The Paystack verify endpoint is idempotent. It returns the same result every time.
What if my verification call fails?
Retry with exponential backoff. The transaction state on Paystack does not change. The webhook will also deliver the event independently.
Should I verify in the webhook handler too?
Yes. Call the same verify_and_fulfill function from both the callback route and webhook handler. The idempotent logic ensures only one fulfills 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

Apple Pay on Paystack: Setup and Domain Verification

Apple Pay on Paystack lets customers pay with a tap using cards stored in their Apple Wallet. Setting it up requires domain verification: hosting a file on your server so Apple confirms you control the domain. This guide walks through the entire setup and the code-level handling.

Read more

Paystack Authorization Code Not Reusable

When Paystack returns reusable: false on an authorization, that card cannot be charged again without the customer present. This guide covers why it happens, how to check before attempting a charge, and what to do instead.

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.