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.
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.
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
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.
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