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

Build Paystack Subscriptions in Flask

To build Paystack subscriptions in Flask, create a plan via the Paystack API, initialize a transaction with the plan code, handle subscription webhooks to track status, and provide routes for customers to view and cancel their subscriptions.

In this article

  1. 1. Subscribe Route
  2. 2. Subscription Webhook Handlers
  3. 3. Cancel Subscription
  4. 4. Gate Content Behind Subscription
  5. 5. Subscription Status
  6. 6. Ship Payments Faster

Subscribe Route

@app.route('/subscribe', methods=['POST'])
def subscribe():
    plan_code = request.form.get('plan_code')
    email = request.form.get('email')

    response = http_requests.post(
        'https://api.paystack.co/transaction/initialize',
        json={
            'email': email,
            'plan': plan_code,
            'callback_url': BASE_URL + '/subscription/callback',
        },
        headers={
            'Authorization': 'Bearer ' + PAYSTACK_SECRET,
            'Content-Type': 'application/json',
        },
    )

    data = response.json()

    if data.get('status'):
        return redirect(data['data']['authorization_url'])

    return 'Subscription failed: ' + data.get('message', ''), 400

Subscription Webhook Handlers

def handle_new_subscription(data):
    db.save_subscription({
        'subscription_code': data['subscription_code'],
        'customer_email': data['customer']['email'],
        'plan_code': data['plan']['plan_code'],
        'email_token': data.get('email_token', ''),
        'status': 'active',
        'next_payment_date': data.get('next_payment_date'),
    })

def handle_failed_renewal(data):
    sub_code = data.get('subscription', {}).get('subscription_code')
    if sub_code:
        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.

Cancel Subscription

@app.route('/subscription/cancel', methods=['POST'])
def cancel_subscription():
    sub = db.get_user_subscription(current_user.email)

    if not sub:
        return 'No subscription found', 404

    response = http_requests.post(
        'https://api.paystack.co/subscription/disable',
        json={'code': sub['subscription_code'], 'token': sub['email_token']},
        headers={
            'Authorization': 'Bearer ' + PAYSTACK_SECRET,
            'Content-Type': 'application/json',
        },
    )

    data = response.json()

    if data.get('status'):
        db.update_subscription_status(sub['subscription_code'], 'cancelled')
        return redirect('/dashboard')

    return 'Cancellation failed', 400

Gate Content Behind Subscription

from functools import wraps

def subscription_required(f):
    @wraps(f)
    def decorated(*args, **kwargs):
        sub = db.get_user_subscription(current_user.email)
        if not sub or sub['status'] != 'active':
            return redirect('/subscribe')
        return f(*args, **kwargs)
    return decorated

@app.route('/premium')
@subscription_required
def premium_content():
    return render_template('premium.html')

Subscription Status

@app.route('/api/subscription/status')
def subscription_status():
    sub = db.get_user_subscription(current_user.email)

    if not sub:
        return jsonify({'has_subscription': False})

    return jsonify({
        'has_subscription': True,
        'status': sub['status'],
        'plan_code': sub['plan_code'],
        'next_payment_date': sub.get('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. Create plans once and reuse them.
  • ✓The first payment creates the subscription. No separate subscription API call is needed.
  • ✓Webhook events drive subscription state. Handle subscription.create, charge.success, and invoice.payment_failed.
  • ✓Store subscription_code and email_token for managing subscriptions via the API.
  • ✓Use Flask decorators or before_request hooks to gate content behind active subscriptions.
  • ✓Flask-Login or Flask-JWT-Extended pair well with subscription checks for authenticated access control.

Frequently Asked Questions

How do I create plans in Flask?
You can create plans via the Paystack dashboard or by calling POST https://api.paystack.co/plan with the plan name, amount, and interval. Most teams create plans in the dashboard and store the plan codes in their app config.
Can I offer both monthly and yearly plans?
Yes. Create separate plans with different intervals and amounts. Let the user choose on your pricing page.
What happens when a renewal fails?
Paystack retries the charge. You get an invoice.payment_failed webhook. Update the subscription status to past_due and notify the customer to update their payment method.

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

Verify Paystack Payments in Flask

Verify Paystack payments server-side in your Flask application. This guide covers calling the Paystack verify endpoint, validating amounts and currencies, building reusable verification helpers, and preventing double-granting.

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

Accepting Bank Transfer Payments Through Paystack

Bank transfer is the fastest-growing payment channel in Nigeria. The customer transfers to a temporary account number and Paystack confirms the payment. This guide covers how it works under the hood, how to handle the wait for confirmation, and the differences between temporary and dedicated virtual accounts.

Read more

Paystack Refund Failed or Stuck

Paystack refunds can fail or stay stuck at "pending" for specific, diagnosable reasons. This guide covers every failure cause, what to do when a refund stays pending, and how to use manual transfers as a fallback.

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.