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.
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();
}
// 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.
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',
);
}
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' };
}
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;
}
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