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

Accept Payments with Paystack in Flask

To accept Paystack payments in Flask, create a route that initializes a transaction with the Paystack API using the requests library, redirects the customer to Paystack checkout, and verifies the payment in a callback route before granting value.

In this article

  1. 1. Project Setup
  2. 2. Initialize a Transaction
  3. 3. Handle the Callback
  4. 4. JSON API for SPA Frontends
  5. 5. Production Checklist
  6. 6. Ship Payments Faster

Project Setup

pip install flask requests python-dotenv
# app.py
import os
import uuid
import requests as http_requests
from flask import Flask, request, redirect, render_template, jsonify
from dotenv import load_dotenv

load_dotenv()

app = Flask(__name__)
PAYSTACK_SECRET = os.environ.get('PAYSTACK_SECRET_KEY')
BASE_URL = os.environ.get('BASE_URL', 'http://localhost:5000')

Initialize a Transaction

@app.route('/pay', methods=['POST'])
def initialize_payment():
    email = request.form.get('email')
    amount = float(request.form.get('amount', 5000))
    reference = 'order_' + uuid.uuid4().hex[:12]

    response = http_requests.post(
        'https://api.paystack.co/transaction/initialize',
        json={
            'email': email,
            'amount': int(amount * 100),
            'reference': reference,
            'callback_url': BASE_URL + '/payment/callback',
        },
        headers={
            'Authorization': 'Bearer ' + PAYSTACK_SECRET,
            'Content-Type': 'application/json',
        },
    )

    data = response.json()

    if data.get('status'):
        # TODO: Save order to database
        return redirect(data['data']['authorization_url'])

    return 'Initialization failed: ' + data.get('message', 'Unknown error'), 400

Get weekly developer tips

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

No spam. Unsubscribe anytime.

Handle the Callback

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

    if not reference:
        return 'Missing reference', 400

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

    data = response.json()

    if data.get('status') and data['data']['status'] == 'success':
        amount = data['data']['amount'] / 100
        currency = data['data']['currency']

        # TODO: Verify amount matches database, mark order as paid
        return 'Payment successful! ' + currency + ' ' + str(amount)

    return 'Payment not successful', 400

JSON API for SPA Frontends

If your frontend is a separate SPA (React, Vue, etc.), return JSON instead of redirecting:

@app.route('/api/pay', methods=['POST'])
def api_initialize():
    data = request.get_json()
    email = data.get('email')
    amount = data.get('amount', 5000)
    reference = 'order_' + uuid.uuid4().hex[:12]

    response = http_requests.post(
        'https://api.paystack.co/transaction/initialize',
        json={
            'email': email,
            'amount': int(amount * 100),
            'reference': reference,
        },
        headers={
            'Authorization': 'Bearer ' + PAYSTACK_SECRET,
            'Content-Type': 'application/json',
        },
    )

    result = response.json()

    if result.get('status'):
        return jsonify({
            'authorization_url': result['data']['authorization_url'],
            'access_code': result['data']['access_code'],
            'reference': result['data']['reference'],
        })

    return jsonify({'error': result.get('message')}), 400

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

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

    data = response.json()

    if data.get('status') and data['data']['status'] == 'success':
        return jsonify({
            'success': True,
            'amount': data['data']['amount'] / 100,
            'currency': data['data']['currency'],
        })

    return jsonify({'success': False}), 400

Production Checklist

  1. Use gunicorn. Do not run Flask's development server in production. Use gunicorn behind nginx.
  2. HTTPS required. Paystack requires HTTPS for callback and webhook URLs.
  3. CORS. Install flask-cors if your frontend is on a different domain.
  4. Set up webhooks. See Handle Paystack Webhooks in Flask.
  5. Validate amounts. Check amounts against your database, not client input.
  6. Switch keys. Use sk_live_ in production.

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 routes handle the Paystack API calls server-side. Use the requests library for HTTP calls.
  • ✓Store your Paystack secret key in environment variables. Access it with os.environ or Flask config.
  • ✓Amounts are in kobo (NGN), pesewas (GHS), or cents. Multiply by 100 before sending to Paystack.
  • ✓Always verify the transaction server-side after the redirect callback.
  • ✓Flask is minimal by design. You bring your own database, ORM, and templating as needed.
  • ✓For production, use a WSGI server like gunicorn behind nginx with HTTPS.

Frequently Asked Questions

Is Flask too minimal for payment processing?
No. Flask is a web framework. The Paystack integration is HTTP calls with the requests library. Flask handles routing and request/response. What matters is your server-side verification logic, which is the same regardless of framework.
Do I need Flask-SQLAlchemy for payments?
You need some way to store orders and track payment status. Flask-SQLAlchemy is a popular choice. You could also use plain SQLite, MongoDB, or any other database.
Can I use Flask async with Paystack?
Flask 2.0+ supports async views with async def. Use httpx instead of requests for async HTTP calls. The Paystack API endpoints and logic are the same.

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 Gateway Responses: Reading What the Bank Told You

When a payment fails on Paystack, the gateway_response field tells you exactly what the bank said. Approved. Declined. Insufficient Funds. Timeout. This guide decodes the most common gateway responses, explains what they mean for your integration, and shows you how to turn cryptic bank codes into messages your customers can act on.

Read more

Paystack Subscription Not Charging

Your Paystack subscription exists but recurring charges are not happening. The subscription might be disabled, the authorization code might not be reusable, the card might have expired, the plan amount might have changed, or the subscription might be in arrears. This guide walks through every cause with a systematic debug checklist.

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.