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

Verify Paystack Payments in Django REST Framework

To verify a Paystack payment in DRF, create a verification service function that calls the Paystack verify endpoint, checks amount and currency against your Order model, and performs an atomic update to mark the order as paid. Call this service from both your callback APIView and webhook handler.

In this article

  1. 1. Reusable Verification Service
  2. 2. Verify APIView
  3. 3. Using Verification in Webhooks
  4. 4. Structured Error Responses
  5. 5. Retry Logic
  6. 6. Ship Payments Faster

Reusable Verification Service

# payments/services.py
import requests
from django.conf import settings
from django.utils import timezone
from .models import Order

def verify_paystack_payment(reference):
    """Call Paystack verify and return the parsed response."""
    response = requests.get(
        'https://api.paystack.co/transaction/verify/' + reference,
        headers={
            'Authorization': 'Bearer ' + settings.PAYSTACK_SECRET_KEY,
        },
    )
    return response.json()

def verify_and_fulfill_order(reference):
    """Verify payment and fulfill order idempotently. Returns a dict."""
    try:
        order = Order.objects.get(reference=reference)
    except Order.DoesNotExist:
        return {'success': False, 'error': 'Order not found', 'status_code': 404}

    if order.paid:
        return {'success': True, 'already_fulfilled': True}

    result = verify_paystack_payment(reference)

    if not result.get('status'):
        return {'success': False, 'error': 'Verification request failed', 'status_code': 502}

    data = result['data']

    if data['status'] != 'success':
        return {'success': False, 'error': 'Payment not successful', 'paystack_status': data['status'], 'status_code': 400}

    if data['amount'] != order.amount:
        return {'success': False, 'error': 'Amount mismatch', 'status_code': 400}

    if data['currency'] != order.currency:
        return {'success': False, 'error': 'Currency mismatch', 'status_code': 400}

    updated = Order.objects.filter(
        reference=reference, paid=False
    ).update(paid=True, paid_at=timezone.now())

    return {
        'success': True,
        'already_fulfilled': updated == 0,
        'amount': order.amount / 100,
        'currency': order.currency,
        'email': order.email,
    }

Verify APIView

# payments/views.py
from rest_framework.views import APIView
from rest_framework.response import Response
from rest_framework import status
from .services import verify_and_fulfill_order

class VerifyPaymentView(APIView):
    def get(self, request):
        reference = request.query_params.get('reference')

        if not reference:
            return Response(
                {'error': 'Missing reference'},
                status=status.HTTP_400_BAD_REQUEST,
            )

        result = verify_and_fulfill_order(reference)

        if not result['success']:
            return Response(
                {'error': result['error']},
                status=result.get('status_code', 400),
            )

        return Response({
            'success': True,
            'already_fulfilled': result.get('already_fulfilled', False),
            'amount': result.get('amount'),
            'currency': result.get('currency'),
        })

Your SPA frontend calls this after the inline popup closes or after the redirect callback. The same verify_and_fulfill_order function is called from your webhook handler for consistent behavior.

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 Webhooks

# In your webhook handler
def process_paystack_event(event):
    if event.get('event') == 'charge.success':
        reference = event['data'].get('reference')
        if reference:
            result = verify_and_fulfill_order(reference)
            if result['success']:
                print('Order fulfilled via webhook: ' + reference)

Both the webhook and the callback APIView call verify_and_fulfill_order. The filter().update() pattern ensures only one of them actually fulfills the order. The other gets already_fulfilled: True and skips.

Structured Error Responses

DRF makes it easy to return consistent error responses. Create a custom exception handler if you want a standardized error format:

# payments/exceptions.py
from rest_framework.exceptions import APIException

class PaymentVerificationError(APIException):
    status_code = 400
    default_detail = 'Payment verification failed.'
    default_code = 'payment_verification_error'

class AmountMismatchError(PaymentVerificationError):
    default_detail = 'The paid amount does not match the expected amount.'
    default_code = 'amount_mismatch'

Raise these exceptions in your service or view for consistent error handling across your API.

Retry Logic

# payments/services.py
import time

def verify_with_retry(reference, max_retries=3):
    for attempt in range(max_retries):
        try:
            result = verify_paystack_payment(reference)
            if result.get('status') is not None:
                return result
        except requests.exceptions.RequestException:
            pass

        if attempt < max_retries - 1:
            time.sleep(2 ** attempt)

    return None

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

  • ✓Create a reusable verify_and_fulfill function that both your callback APIView and webhook handler call.
  • ✓Use DRF Response objects for consistent JSON error responses across all verification failures.
  • ✓Always validate amount and currency against your database, not against client-submitted values.
  • ✓Use filter().update() for atomic, idempotent fulfillment that prevents double-granting.
  • ✓Return structured JSON responses so your SPA frontend can display appropriate success or error messages.
  • ✓If the Paystack verify call fails, retry with exponential backoff. The transaction state does not change.

Frequently Asked Questions

Should I add authentication to the verify endpoint?
It depends. If only authenticated users make payments, add authentication. If you also handle redirect callbacks (where the URL is hit directly), you may want a separate unauthenticated callback view and an authenticated verify endpoint for the SPA.
Can I use DRF throttling on the verify endpoint?
Yes. Add throttle_classes to prevent abuse. A reasonable rate is 10 requests per minute per user. This prevents malicious polling while allowing normal verification flows.
How do I return different HTTP status codes for different errors?
The service function returns a status_code field. Your APIView uses it with Response(data, status=result["status_code"]). This gives you 404 for missing orders, 400 for failed payments, and 502 for Paystack API failures.

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 Bulk Charge: Charging Many Customers at Once

When you need to charge hundreds or thousands of customers at once (subscription renewals, scheduled payments, payroll deductions), the Paystack Bulk Charge API lets you submit a batch of charges in one request and track each one individually. This guide covers the full workflow.

Read more

Paystack Callback URL Not Redirecting

Your customer pays but is not redirected back to your site. This happens when callback_url is missing, you are using popup mode instead of redirect mode, or the browser is blocking the redirect.

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.