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.
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' };
}
}
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;
}
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.
Ready to build real-world apps?
Join the McTaba Labs full-stack marathon (4 months full-time · 6 months part-time). Learn M-Pesa, USSD, and WhatsApp engineering while shipping 8 production apps.
Apply to the McTaba Marathon