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

Build Paystack Subscriptions in Django

To build Paystack subscriptions in Django, create a plan via the Paystack API, initialize a transaction with the plan code, and handle subscription webhooks. Store subscription data in a Django model. Paystack handles all recurring billing automatically.

In this article

  1. 1. Subscription Model
  2. 2. Create a Plan
  3. 3. Subscribe a Customer
  4. 4. Handle Subscription Webhooks
  5. 5. Gate Content Behind Subscription
  6. 6. Cancel a Subscription
  7. 7. Ship Payments Faster

Subscription Model

# payments/models.py
from django.db import models
from django.contrib.auth.models import User

class Subscription(models.Model):
    STATUS_CHOICES = [
        ('active', 'Active'),
        ('past_due', 'Past Due'),
        ('cancelled', 'Cancelled'),
    ]

    user = models.OneToOneField(User, on_delete=models.CASCADE, related_name='subscription')
    subscription_code = models.CharField(max_length=100, unique=True)
    customer_code = models.CharField(max_length=100)
    plan_code = models.CharField(max_length=100)
    email_token = models.CharField(max_length=100)
    status = models.CharField(max_length=20, choices=STATUS_CHOICES, default='active')
    next_payment_date = models.DateTimeField(null=True, blank=True)
    created_at = models.DateTimeField(auto_now_add=True)
    cancelled_at = models.DateTimeField(null=True, blank=True)

    def __str__(self):
        return self.subscription_code

Create a Plan

# payments/paystack.py
import requests
from django.conf import settings

PAYSTACK_BASE = 'https://api.paystack.co'

def get_headers():
    return {
        'Authorization': 'Bearer ' + settings.PAYSTACK_SECRET_KEY,
        'Content-Type': 'application/json',
    }

def create_plan(name, amount, interval):
    """Create a Paystack plan. Interval: daily, weekly, monthly, quarterly, biannually, annually."""
    response = requests.post(
        PAYSTACK_BASE + '/plan',
        json={
            'name': name,
            'amount': int(amount * 100),
            'interval': interval,
            'currency': 'NGN',
        },
        headers=get_headers(),
    )
    return response.json()

def disable_subscription(code, email_token):
    """Cancel a subscription."""
    response = requests.post(
        PAYSTACK_BASE + '/subscription/disable',
        json={'code': code, 'token': email_token},
        headers=get_headers(),
    )
    return response.json()

Create plans once through the dashboard or a management command. Store the plan codes in your settings or database.

Get weekly developer tips

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

No spam. Unsubscribe anytime.

Subscribe a Customer

# payments/views.py
import requests as http_requests
from django.conf import settings
from django.shortcuts import redirect
from django.contrib.auth.decorators import login_required

@login_required
def subscribe(request):
    if request.method == 'POST':
        plan_code = request.POST.get('plan_code')

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

        result = response.json()

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

    return render(request, 'payments/subscribe.html')

When you pass a plan parameter to the initialize endpoint, you do not need to pass amount. Paystack uses the plan's configured amount.

Handle Subscription Webhooks

# payments/webhooks.py
from django.utils import timezone
from django.contrib.auth.models import User
from .models import Subscription

def handle_subscription_create(data):
    email = data['customer']['email']
    try:
        user = User.objects.get(email=email)
    except User.DoesNotExist:
        return

    Subscription.objects.update_or_create(
        user=user,
        defaults={
            'subscription_code': data['subscription_code'],
            'customer_code': data['customer']['customer_code'],
            'plan_code': data['plan']['plan_code'],
            'email_token': data.get('email_token', ''),
            'status': 'active',
            'next_payment_date': data.get('next_payment_date'),
        },
    )

def handle_invoice_failed(data):
    sub_code = data.get('subscription', {}).get('subscription_code')
    if sub_code:
        Subscription.objects.filter(
            subscription_code=sub_code,
        ).update(status='past_due')

def handle_subscription_disable(data):
    sub_code = data.get('subscription_code')
    if sub_code:
        Subscription.objects.filter(
            subscription_code=sub_code,
        ).update(status='cancelled', cancelled_at=timezone.now())

Gate Content Behind Subscription

# payments/decorators.py
from functools import wraps
from django.shortcuts import redirect

def subscription_required(view_func):
    @wraps(view_func)
    def wrapper(request, *args, **kwargs):
        if not request.user.is_authenticated:
            return redirect('/login/')

        try:
            sub = request.user.subscription
            if sub.status == 'active':
                return view_func(request, *args, **kwargs)
        except Exception:
            pass

        return redirect('/payments/subscribe/')

    return wrapper

Use it on any view:

@subscription_required
def premium_dashboard(request):
    return render(request, 'premium/dashboard.html')

Cancel a Subscription

@login_required
def cancel_subscription(request):
    if request.method == 'POST':
        try:
            sub = request.user.subscription
        except Subscription.DoesNotExist:
            return redirect('/dashboard/')

        result = disable_subscription(sub.subscription_code, sub.email_token)

        if result.get('status'):
            sub.status = 'cancelled'
            sub.cancelled_at = timezone.now()
            sub.save()

        return redirect('/dashboard/')

    return render(request, 'payments/cancel.html')

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 recurring billing. You create plans, subscribe customers, and Paystack charges them on schedule.
  • ✓Create a Subscription model to track subscription status, plan, and the Paystack subscription_code.
  • ✓The first payment creates the subscription. No separate API call is needed.
  • ✓Webhook events drive subscription state changes. Handle subscription.create, charge.success, invoice.payment_failed, and subscription.disable.
  • ✓Store the email_token from the subscription.create webhook. You need it to cancel subscriptions via the API.
  • ✓Use Django middleware or decorators to gate premium content behind an active subscription check.

Frequently Asked Questions

Can I offer monthly and yearly plans?
Yes. Create separate plans with different intervals (monthly vs annually) and amounts. Let the customer choose on your pricing page and pass the corresponding plan_code when initializing.
How do I handle plan upgrades?
Paystack does not support direct plan changes. Cancel the current subscription and create a new one on the new plan. Handle prorating in your Django application logic.
What happens when a renewal payment fails?
Paystack retries the charge. You receive invoice.payment_failed for each failed attempt. Set the subscription status to past_due and notify the customer to update their payment method.
How do I store the email_token?
The email_token is included in the subscription.create webhook event. Save it in your Subscription model when you receive that webhook. You need it later to cancel the subscription via the API.

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 Card Preauthorization for Holds and Deposits

Preauthorization lets you verify a customer has funds and place a hold without immediately capturing the full amount. This is how ride-hailing apps, hotel bookings, and equipment rental platforms work. This guide covers how to implement card holds and deferred captures with Paystack.

Read more

Paystack CORS Errors and What They Really Mean

A CORS error on Paystack means you are calling the Paystack API directly from your frontend JavaScript. The fix is not to add CORS headers anywhere. The fix is to move the API call to your server.

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.