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

Build Paystack Subscriptions in NestJS

To build Paystack subscriptions in NestJS, create a plan via the Paystack API, initialize a transaction with the plan code, and handle subscription webhooks. Paystack manages all recurring billing. Your NestJS app tracks subscription status via webhook events and provides endpoints for customers to view and cancel their subscriptions.

In this article

  1. 1. Plan Management Service
  2. 2. Subscription Controller
  3. 3. Subscription Webhook Events
  4. 4. Subscription Access Guard
  5. 5. Handling Failed Renewals and Grace Periods
  6. 6. Ship Payments Faster

Plan Management Service

Add plan creation and listing methods to your PaystackService:

// In paystack.service.ts
async createPlan(name: string, amount: number, interval: string) {
  var response = await fetch('https://api.paystack.co/plan', {
    method: 'POST',
    headers: {
      Authorization: 'Bearer ' + this.secretKey,
      'Content-Type': 'application/json',
    },
    body: JSON.stringify({
      name: name,
      amount: Math.round(amount * 100),
      interval: interval,
      currency: 'NGN',
    }),
  });

  return response.json();
}

async listPlans() {
  var response = await fetch('https://api.paystack.co/plan', {
    headers: { Authorization: 'Bearer ' + this.secretKey },
  });

  return response.json();
}

async getSubscription(code: string) {
  var response = await fetch(
    'https://api.paystack.co/subscription/' + encodeURIComponent(code),
    { headers: { Authorization: 'Bearer ' + this.secretKey } }
  );

  return response.json();
}

async disableSubscription(code: string, emailToken: string) {
  var response = await fetch('https://api.paystack.co/subscription/disable', {
    method: 'POST',
    headers: {
      Authorization: 'Bearer ' + this.secretKey,
      'Content-Type': 'application/json',
    },
    body: JSON.stringify({ code: code, token: emailToken }),
  });

  return response.json();
}

Subscription Controller

// src/payment/subscription.controller.ts
import { Controller, Post, Get, Body, Param, Delete } from '@nestjs/common';
import { PaystackService } from './paystack.service';
import { ConfigService } from '@nestjs/config';

@Controller('api/subscriptions')
export class SubscriptionController {
  constructor(
    private paystackService: PaystackService,
    private configService: ConfigService,
  ) {}

  @Post('subscribe')
  async subscribe(@Body() body: { email: string; planCode: string }) {
    var reference = 'sub_' + Date.now() + '_' + Math.random().toString(36).slice(2, 8);

    var data = await this.paystackService.initializeTransaction(
      body.email,
      0, // Amount comes from the plan
      reference,
      this.configService.get('BASE_URL') + '/subscription/callback',
    );

    // Override: pass plan parameter
    var response = await fetch('https://api.paystack.co/transaction/initialize', {
      method: 'POST',
      headers: {
        Authorization: 'Bearer ' + this.configService.get('PAYSTACK_SECRET_KEY'),
        'Content-Type': 'application/json',
      },
      body: JSON.stringify({
        email: body.email,
        plan: body.planCode,
        reference: reference,
        callback_url: this.configService.get('BASE_URL') + '/subscription/callback',
      }),
    });

    var result = await response.json();

    if (!result.status) {
      return { error: result.message };
    }

    return {
      authorization_url: result.data.authorization_url,
      reference: result.data.reference,
    };
  }

  @Get(':code')
  async getSubscription(@Param('code') code: string) {
    var data = await this.paystackService.getSubscription(code);
    if (!data.status) return { error: data.message };

    return {
      status: data.data.status,
      plan: data.data.plan.name,
      next_payment_date: data.data.next_payment_date,
    };
  }

  @Delete(':code')
  async cancelSubscription(
    @Param('code') code: string,
    @Body() body: { emailToken: string },
  ) {
    var data = await this.paystackService.disableSubscription(code, body.emailToken);
    if (!data.status) return { error: data.message };

    return { message: 'Subscription cancelled' };
  }
}

Get weekly developer tips

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

No spam. Unsubscribe anytime.

Subscription Webhook Events

Extend your webhook handler to process subscription events:

// In webhook processing logic
if (eventType === 'subscription.create') {
  await this.subscriptionService.create({
    subscriptionCode: data.subscription_code,
    customerEmail: data.customer.email,
    customerCode: data.customer.customer_code,
    planCode: data.plan.plan_code,
    emailToken: data.email_token,
    status: 'active',
    nextPaymentDate: data.next_payment_date,
  });

} else if (eventType === 'charge.success' && data.plan) {
  await this.subscriptionService.updateStatus(
    data.subscription_code,
    'active',
  );

} else if (eventType === 'invoice.payment_failed') {
  await this.subscriptionService.updateStatus(
    data.subscription.subscription_code,
    'past_due',
  );
  // Send email asking customer to update payment method

} else if (eventType === 'subscription.disable') {
  await this.subscriptionService.updateStatus(
    data.subscription_code,
    'cancelled',
  );
}

Subscription Access Guard

Create a Guard to protect routes that require an active subscription:

// src/payment/guards/subscription.guard.ts
import { Injectable, CanActivate, ExecutionContext } from '@nestjs/common';

@Injectable()
export class ActiveSubscriptionGuard implements CanActivate {
  constructor(private subscriptionService: SubscriptionService) {}

  async canActivate(context: ExecutionContext): Promise<boolean> {
    var request = context.switchToHttp().getRequest();
    var userId = request.user?.id;

    if (!userId) return false;

    var subscription = await this.subscriptionService.findActiveByUser(userId);
    return subscription !== null && subscription.status === 'active';
  }
}

Apply it to any controller or route that requires a paid subscription:

@UseGuards(AuthGuard, ActiveSubscriptionGuard)
@Get('premium-content')
getPremiumContent() {
  return { content: 'This is premium content' };
}

Handling Failed Renewals and Grace Periods

When a subscription renewal fails, do not immediately revoke access. Give the customer time to fix their payment method.

// In subscription.service.ts
async checkAccess(userId: string): Promise<boolean> {
  var sub = await this.subscriptionRepository.findOne({
    where: { userId: userId },
    order: { createdAt: 'DESC' },
  });

  if (!sub) return false;
  if (sub.status === 'active') return true;

  // Allow 3-day grace period for past_due
  if (sub.status === 'past_due') {
    var daysSinceFailure = (Date.now() - sub.lastFailureDate.getTime()) / (1000 * 60 * 60 * 24);
    return daysSinceFailure <= 3;
  }

  return false;
}

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 automatically.
  • ✓Use NestJS services to encapsulate plan creation, subscription management, and Paystack API calls.
  • ✓Webhook events drive subscription state. Handle subscription.create, charge.success, invoice.payment_failed, and subscription.disable.
  • ✓Store subscription_code and email_token in your database. You need both for managing and cancelling subscriptions.
  • ✓The first payment creates the subscription. No separate subscription creation step is needed.
  • ✓Use NestJS Guards on subscription-gated endpoints to check the user has an active subscription.

Frequently Asked Questions

Can I change a subscription plan in Paystack?
Paystack does not support direct plan changes. To switch a customer to a different plan, cancel the current subscription and create a new one on the new plan. Handle prorating in your application logic.
How do I handle free trials with Paystack subscriptions?
Paystack does not have a native free trial feature. Implement trials in your NestJS app: grant access for the trial period, then initialize the subscription payment when the trial ends.
What is the email_token used for?
The email_token is a security token sent in the subscription.create webhook. You need it alongside the subscription_code to disable (cancel) a subscription via the API. Store it when you receive the webhook.
Can I pause a subscription instead of cancelling it?
Paystack does not support pausing subscriptions. To simulate a pause, cancel the subscription and create a new one when the customer wants to resume. Alternatively, continue the subscription but grant a credit or extend the access period.

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

Idempotency in Paystack Payment Flows

Duplicate charges are the nightmare scenario for any payment integration. A customer clicks pay twice, a network timeout triggers a retry, or a webhook fires before the redirect callback. Idempotency is the engineering discipline that makes sure the same payment operation produces the same result no matter how many times it runs.

Read more

Paystack Transaction Timed Out

A Paystack transaction timeout does not always mean the payment failed. Different channels time out at different points, and a webhook can still arrive minutes later. This guide covers every timeout scenario and the safe way to handle each one.

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.