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

Verify Paystack Payments in NestJS

To verify a Paystack payment in NestJS, inject your PaystackService and call the verify endpoint with the transaction reference. Check that data.data.status is "success", the amount matches your stored price, and the currency is correct. Use an idempotent database update to prevent double-granting.

In this article

  1. 1. Verification in the PaystackService
  2. 2. Full Verification with Amount Check
  3. 3. Using Verification in Controllers
  4. 4. Error Handling with Filters
  5. 5. Testing Verification
  6. 6. Ship Payments Faster

Verification in the PaystackService

Add a typed verification method to your PaystackService:

// In paystack.service.ts
async verifyTransaction(reference: string): Promise<{
  success: boolean;
  amount?: number;
  currency?: string;
  email?: string;
  reference?: string;
  status?: string;
}> {
  var response = await fetch(
    'https://api.paystack.co/transaction/verify/' + encodeURIComponent(reference),
    {
      headers: {
        Authorization: 'Bearer ' + this.secretKey,
      },
    }
  );

  var data = await response.json();

  if (!data.status || data.data.status !== 'success') {
    return {
      success: false,
      status: data.data ? data.data.status : 'unknown',
    };
  }

  return {
    success: true,
    amount: data.data.amount,
    currency: data.data.currency,
    email: data.data.customer.email,
    reference: data.data.reference,
  };
}

This returns a clean typed object your controllers can use without knowing the Paystack API response shape.

Full Verification with Amount Check

Create a dedicated fulfillment method that combines verification with database checks:

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

@Injectable()
export class PaymentService {
  constructor(private paystackService: PaystackService) {}

  async fulfillOrder(reference: string) {
    // 1. Look up the order
    var order = await this.orderRepository.findOne({ where: { reference } });

    if (!order) {
      return { error: 'Order not found' };
    }

    if (order.paid) {
      return { success: true, alreadyFulfilled: true };
    }

    // 2. Verify with Paystack
    var result = await this.paystackService.verifyTransaction(reference);

    if (!result.success) {
      return { error: 'Payment not successful', status: result.status };
    }

    // 3. Check amount (stored in kobo)
    if (result.amount !== order.amountInKobo) {
      return { error: 'Amount mismatch' };
    }

    // 4. Check currency
    if (result.currency !== order.currency) {
      return { error: 'Currency mismatch' };
    }

    // 5. Idempotent fulfillment
    var updated = await this.orderRepository.update(
      { reference: reference, paid: false },
      { paid: true, paidAt: new Date() }
    );

    if (updated.affected === 0) {
      return { success: true, alreadyFulfilled: true };
    }

    // 6. Deliver value
    await this.sendConfirmationEmail(order.email, order);

    return { success: true, alreadyFulfilled: false };
  }
}

Get weekly developer tips

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

No spam. Unsubscribe anytime.

Using Verification in Controllers

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

  var result = await this.paymentService.fulfillOrder(reference);

  if (result.error) {
    return res.redirect('/payment/failed?error=' + encodeURIComponent(result.error));
  }

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

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

  return this.paymentService.fulfillOrder(reference);
}

Both the callback handler (for redirect checkout) and the verify endpoint (for inline popup) use the same fulfillOrder method. This ensures consistent verification logic across all payment paths.

Error Handling with Filters

Create a custom exception filter for payment-related errors:

// src/payment/filters/payment-exception.filter.ts
import { ExceptionFilter, Catch, ArgumentsHost, HttpException } from '@nestjs/common';

export class PaymentVerificationException extends HttpException {
  constructor(message: string) {
    super({ error: 'Payment verification failed', message: message }, 400);
  }
}

@Catch(PaymentVerificationException)
export class PaymentExceptionFilter implements ExceptionFilter {
  catch(exception: PaymentVerificationException, host: ArgumentsHost) {
    var ctx = host.switchToHttp();
    var response = ctx.getResponse();

    response.status(400).json({
      success: false,
      error: exception.message,
    });
  }
}

This gives you a consistent error response format for all payment verification failures.

Testing Verification

Unit test the verification by mocking the PaystackService:

// src/payment/__tests__/payment.service.spec.ts
describe('PaymentService', function() {
  it('should fulfill order on successful verification', async function() {
    var mockPaystackService = {
      verifyTransaction: jest.fn().mockResolvedValue({
        success: true,
        amount: 500000,
        currency: 'NGN',
        email: 'test@example.com',
        reference: 'test_ref',
      }),
    };

    // Inject mock service and test fulfillOrder
  });

  it('should reject on amount mismatch', async function() {
    var mockPaystackService = {
      verifyTransaction: jest.fn().mockResolvedValue({
        success: true,
        amount: 100000, // Different from stored amount
        currency: 'NGN',
      }),
    };

    // Verify the service returns an amount mismatch error
  });
});

Mock the fetch calls rather than hitting the real Paystack API in tests. Use Paystack test keys for integration tests only.

Ship Payments Faster

This guide is part of the Paystack integration guides by language and framework series. For webhook handling, see Handle Paystack Webhooks in NestJS.

Sign up for the McTaba newsletter

Key Takeaways

  • ✓Verification is a GET request to Paystack. Wrap it in a service method that returns a typed response.
  • ✓Always check three things: status equals "success", amount matches your stored price, and currency is correct.
  • ✓Use NestJS interceptors or pipes to handle common verification errors consistently across controllers.
  • ✓The redirect callback is not proof of payment. Always call the verify endpoint server-side.
  • ✓Both webhook and callback can fire for the same transaction. Use atomic database updates for idempotent fulfillment.
  • ✓Inject the PaystackService into both your callback controller and webhook handler for consistent verification logic.

Frequently Asked Questions

Should I verify in the webhook handler or the callback handler?
Both. Each handler should call the same fulfillOrder method that verifies with Paystack and uses an idempotent database update. Whichever fires first fulfills the order. The other is a no-op.
Can I use NestJS Guards for payment verification?
Guards are better suited for authentication checks. Payment verification involves business logic (amount matching, database updates) that belongs in a service, not a guard.
What if the Paystack verify endpoint is down?
Retry with exponential backoff. The transaction state on Paystack does not change. If all retries fail, the webhook handler will independently deliver the event and can fulfill the order through that path.

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

Using Paystack Custom Fields to Collect Extra Checkout Information

Paystack custom fields let you attach structured, human-readable data to a transaction that shows up on the checkout page, in your dashboard, and in webhook payloads. This guide covers display_name vs variable_name, common field patterns, and how to extract custom field data when the webhook arrives.

Read more

Paystack "Declined by Financial Institution" Error

The "Declined by financial institution" response means the customer's bank rejected the transaction. This is not a Paystack error or a bug in your code. The bank made the decision, and neither you nor Paystack can override it.

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.