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.
# 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,
}
# 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.
# 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.
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.
# 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
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