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

Build Paystack Subscriptions in FastAPI

To build Paystack subscriptions in FastAPI, create a plan via the API, initialize a transaction with the plan code using an async endpoint, handle subscription webhooks to track status, and use FastAPI dependencies to gate premium endpoints behind active subscription checks.

In this article

  1. 1. Subscribe Endpoint
  2. 2. Subscription Webhook Handlers
  3. 3. Subscription Access Dependency
  4. 4. Cancel Subscription
  5. 5. Subscription Status Endpoint
  6. 6. Ship Payments Faster

Subscribe Endpoint

@app.post('/api/subscribe')
async def subscribe(plan_code: str, current_user = Depends(get_current_user)):
    async with httpx.AsyncClient() as client:
        response = await client.post(
            'https://api.paystack.co/transaction/initialize',
            json={
                'email': current_user.email,
                'plan': plan_code,
                'callback_url': BASE_URL + '/subscription/callback',
            },
            headers={
                'Authorization': 'Bearer ' + PAYSTACK_SECRET,
                'Content-Type': 'application/json',
            },
        )

    data = response.json()

    if not data.get('status'):
        raise HTTPException(status_code=400, detail=data.get('message'))

    return {
        'authorization_url': data['data']['authorization_url'],
        'reference': data['data']['reference'],
    }

Subscription Webhook Handlers

async def handle_subscription_create(data: dict):
    email = data['customer']['email']
    user = await db.get_user_by_email(email)
    if not user:
        return

    await db.upsert_subscription({
        'user_id': user.id,
        'subscription_code': data['subscription_code'],
        'plan_code': data['plan']['plan_code'],
        'email_token': data.get('email_token', ''),
        'status': 'active',
        'next_payment_date': data.get('next_payment_date'),
    })

async def handle_invoice_failed(data: dict):
    sub_code = data.get('subscription', {}).get('subscription_code')
    if sub_code:
        await db.update_subscription_status(sub_code, 'past_due')

Get weekly developer tips

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

No spam. Unsubscribe anytime.

Subscription Access Dependency

# dependencies.py
async def require_active_subscription(current_user = Depends(get_current_user)):
    subscription = await db.get_subscription(current_user.id)

    if not subscription or subscription.status != 'active':
        raise HTTPException(
            status_code=403,
            detail='An active subscription is required',
        )

    return subscription

# Usage:
@app.get('/api/premium')
async def premium_content(sub = Depends(require_active_subscription)):
    return {'content': 'Premium data', 'plan': sub.plan_code}

Cancel Subscription

@app.post('/api/subscription/cancel')
async def cancel_subscription(current_user = Depends(get_current_user)):
    subscription = await db.get_subscription(current_user.id)

    if not subscription:
        raise HTTPException(status_code=404, detail='No subscription found')

    async with httpx.AsyncClient() as client:
        response = await client.post(
            'https://api.paystack.co/subscription/disable',
            json={
                'code': subscription.subscription_code,
                'token': subscription.email_token,
            },
            headers={
                'Authorization': 'Bearer ' + PAYSTACK_SECRET,
                'Content-Type': 'application/json',
            },
        )

    data = response.json()

    if data.get('status'):
        await db.update_subscription_status(subscription.subscription_code, 'cancelled')
        return {'message': 'Subscription cancelled'}

    raise HTTPException(status_code=400, detail=data.get('message'))

Subscription Status Endpoint

from pydantic import BaseModel
from typing import Optional
from datetime import datetime

class SubscriptionStatus(BaseModel):
    has_subscription: bool
    status: Optional[str] = None
    plan_code: Optional[str] = None
    next_payment_date: Optional[datetime] = None

@app.get('/api/subscription/status', response_model=SubscriptionStatus)
async def subscription_status(current_user = Depends(get_current_user)):
    subscription = await db.get_subscription(current_user.id)

    if not subscription:
        return SubscriptionStatus(has_subscription=False)

    return SubscriptionStatus(
        has_subscription=True,
        status=subscription.status,
        plan_code=subscription.plan_code,
        next_payment_date=subscription.next_payment_date,
    )

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

  • ✓Paystack handles all recurring billing. You create plans, subscribe customers, and Paystack charges them automatically.
  • ✓Use async httpx calls for all Paystack API interactions in FastAPI.
  • ✓Webhook events drive subscription state. Handle subscription.create, charge.success, and invoice.payment_failed.
  • ✓FastAPI dependencies work well for subscription access control. Create a dependency that checks the user has an active subscription.
  • ✓Store subscription_code and email_token from the webhook. You need both for managing subscriptions.
  • ✓Pydantic models give you type-safe subscription responses for your frontend.

Frequently Asked Questions

Can I offer free trials with Paystack and FastAPI?
Paystack does not have native free trials. Implement trials in your FastAPI app: grant access for the trial period, then initialize the subscription payment when the trial ends.
How do I handle plan upgrades?
Cancel the current subscription and create a new one on the desired plan. Handle prorating in your application logic.
What is the email_token?
The email_token is sent in the subscription.create webhook. You need it alongside the subscription_code to cancel a subscription via the Paystack API. Store it when you receive the webhook.

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 Disputes and Chargebacks: The Developer Playbook

Chargebacks cost you money, time, and sometimes your merchant standing. Paystack gives developers a Dispute API to receive, respond to, and resolve chargebacks programmatically. This guide walks through the dispute lifecycle, evidence submission, webhook events, and code for an automated response system.

Read more

Paystack Recipient Creation Failed

Your transfer recipient creation fails because the bank code, account number, or recipient type is wrong. Paystack validates these details against the bank and rejects anything that does not match. The fix is to validate account details using the Resolve Account API before creating the recipient. This guide covers every cause, the validation flow, and production-ready 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.