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. Accept Payments with Paystack in NestJS
Bonaventure OgetoBy Bonaventure Ogeto|Updated July 20, 2026

Accept Payments with Paystack in NestJS

To accept Paystack payments in NestJS, create a PaystackService that wraps the Paystack REST API calls. Inject it into a PaymentController that exposes endpoints for initialization and verification. Use ConfigService to manage your secret key. Initialize transactions server-side and redirect customers to Paystack checkout.

In this article

  1. 1. Project Setup
  2. 2. Create the Paystack Service
  3. 3. Create the Payment Controller
  4. 4. Wire Up the Module
  5. 5. Add DTO Validation
  6. 6. Security and Production Notes
  7. 7. Ship Payments Faster

Project Setup

Create a new NestJS project or use an existing one:

npx @nestjs/cli new paystack-nestjs
cd paystack-nestjs
npm install @nestjs/config

Add your Paystack keys to a .env file:

PAYSTACK_SECRET_KEY=sk_test_xxxxxxxxxxxxxxxxxxxxx
BASE_URL=http://localhost:3000

Register ConfigModule in your AppModule:

// src/app.module.ts
import { Module } from '@nestjs/common';
import { ConfigModule } from '@nestjs/config';
import { PaymentModule } from './payment/payment.module';

@Module({
  imports: [
    ConfigModule.forRoot({ isGlobal: true }),
    PaymentModule,
  ],
})
export class AppModule {}

Create the Paystack Service

Create a service that wraps the Paystack API calls:

// src/payment/paystack.service.ts
import { Injectable } from '@nestjs/common';
import { ConfigService } from '@nestjs/config';

@Injectable()
export class PaystackService {
  private readonly secretKey: string;
  private readonly baseUrl = 'https://api.paystack.co';

  constructor(private configService: ConfigService) {
    this.secretKey = this.configService.get('PAYSTACK_SECRET_KEY');
  }

  async initializeTransaction(email: string, amount: number, reference: string, callbackUrl: string) {
    var response = await fetch(this.baseUrl + '/transaction/initialize', {
      method: 'POST',
      headers: {
        Authorization: 'Bearer ' + this.secretKey,
        'Content-Type': 'application/json',
      },
      body: JSON.stringify({
        email: email,
        amount: Math.round(amount * 100),
        reference: reference,
        callback_url: callbackUrl,
      }),
    });

    return response.json();
  }

  async verifyTransaction(reference: string) {
    var response = await fetch(
      this.baseUrl + '/transaction/verify/' + encodeURIComponent(reference),
      {
        headers: {
          Authorization: 'Bearer ' + this.secretKey,
        },
      }
    );

    return response.json();
  }
}

Get weekly developer tips

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

No spam. Unsubscribe anytime.

Create the Payment Controller

// src/payment/payment.controller.ts
import { Controller, Post, Get, Body, Query, Res } from '@nestjs/common';
import { ConfigService } from '@nestjs/config';
import { Response } from 'express';
import { PaystackService } from './paystack.service';

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

  @Post('initialize')
  async initialize(@Body() body: { email: string; amount: number }) {
    var reference = 'order_' + Date.now() + '_' + Math.random().toString(36).slice(2, 8);
    var callbackUrl = this.configService.get('BASE_URL') + '/api/payment/callback';

    var data = await this.paystackService.initializeTransaction(
      body.email,
      body.amount,
      reference,
      callbackUrl,
    );

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

    // TODO: Save reference + amount to database

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

  @Get('callback')
  async callback(@Query('reference') reference: string, @Res() res: Response) {
    if (!reference) {
      return res.redirect('/payment/failed?error=missing_reference');
    }

    var data = await this.paystackService.verifyTransaction(reference);

    if (data.status && data.data.status === 'success') {
      // TODO: Verify amount matches, mark order as paid
      return res.redirect('/payment/success?reference=' + reference);
    }

    return res.redirect('/payment/failed?reference=' + reference);
  }

  @Get('verify')
  async verify(@Query('reference') reference: string) {
    if (!reference) {
      return { error: 'Missing reference' };
    }

    var data = await this.paystackService.verifyTransaction(reference);

    if (data.status && data.data.status === 'success') {
      return {
        success: true,
        amount: data.data.amount / 100,
        currency: data.data.currency,
      };
    }

    return { success: false };
  }
}

Wire Up the Module

// src/payment/payment.module.ts
import { Module } from '@nestjs/common';
import { PaymentController } from './payment.controller';
import { PaystackService } from './paystack.service';

@Module({
  controllers: [PaymentController],
  providers: [PaystackService],
  exports: [PaystackService],
})
export class PaymentModule {}

Exporting PaystackService lets other modules (like an OrderModule or SubscriptionModule) inject it and use it for their own payment needs.

Add DTO Validation

NestJS supports request validation with class-validator. Create a DTO for the payment initialization:

// src/payment/dto/initialize-payment.dto.ts
import { IsEmail, IsNumber, Min } from 'class-validator';

export class InitializePaymentDto {
  @IsEmail()
  email: string;

  @IsNumber()
  @Min(1)
  amount: number;
}

Install the required packages and enable the global validation pipe:

npm install class-validator class-transformer
// src/main.ts
import { ValidationPipe } from '@nestjs/common';
import { NestFactory } from '@nestjs/core';
import { AppModule } from './app.module';

async function bootstrap() {
  var app = await NestFactory.create(AppModule);
  app.useGlobalPipes(new ValidationPipe({ whitelist: true }));
  await app.listen(3000);
}
bootstrap();

Now your endpoint automatically rejects requests with invalid emails or negative amounts before your code runs.

Security and Production Notes

  1. Use ConfigService. Never hardcode your Paystack secret key. ConfigService reads from environment variables and keeps secrets out of your codebase.
  2. Verify amounts. Look up the correct price from your database. Never trust what the client sends.
  3. Set up webhooks. The redirect callback can fail if the customer closes their browser. See Handle Paystack Webhooks in NestJS.
  4. Prevent double-granting. Both webhook and callback can fire for the same transaction. Use an idempotent fulfillment function.
  5. Enable CORS. If your frontend is on a different domain, configure CORS in main.ts.

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

  • ✓NestJS services encapsulate the Paystack API calls. Inject the PaystackService into any controller that needs payment functionality.
  • ✓Use ConfigService from @nestjs/config to access your Paystack secret key. Never hardcode secrets.
  • ✓NestJS uses TypeScript by default, so you get type safety for Paystack API request and response objects.
  • ✓Amounts are in kobo (NGN), pesewas (GHS), or cents (ZAR/KES/USD). Multiply the display price by 100.
  • ✓Always verify the transaction server-side after the redirect. The redirect callback alone is not proof of payment.
  • ✓No Paystack SDK is needed. Use the built-in fetch or HttpModule from @nestjs/axios for HTTP calls.

Frequently Asked Questions

Should I use HttpModule or fetch for Paystack API calls in NestJS?
Either works. The built-in fetch in Node 18+ is simpler and requires no extra packages. HttpModule from @nestjs/axios gives you interceptors and observables if you prefer the RxJS style. The Paystack API calls are identical either way.
Can I use Guards to protect payment endpoints?
Yes. Use AuthGuard to ensure only authenticated users can initialize payments. This also lets you pull the customer email from the authenticated user instead of trusting the request body.
How do I test the PaystackService?
Mock the fetch calls in your unit tests. Create a test module with ConfigService providing test values. For integration tests, use Paystack test keys and the test card numbers from the Paystack documentation.
Does NestJS work with Paystack webhooks?
Yes. Create a webhook controller that reads the raw body, verifies the HMAC signature, and processes events. NestJS supports raw body parsing through the rawBody option in NestFactory.create. See our dedicated webhook guide.

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 Metadata: Passing Custom Data Through a Transaction

Paystack metadata lets you attach arbitrary JSON data to a transaction that flows through the entire lifecycle: from initialization to verification to webhooks. This guide shows you what to put in metadata, how to structure it for different use cases, and the limits you need to stay within.

Read more

Paystack Currency Not Supported Error

Paystack returns "Currency not supported" when you try to charge in a currency that is not enabled for your account. This guide explains which currencies each country supports, how to check and enable currencies, and common format mistakes that trigger this error.

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.