Django: integrate Senfenico (checkout and webhook)
Collect Orange Money and Moov Money in a Django payments app with requests, from the checkout to reconciliation scheduled by cron.
You need Python 3.10+, Django 4.2+ and pip install requests. Keys come from the environment, never from Git.
1. Settings and models
Section titled “1. Settings and models”import os
SENFENICO_SECRET_KEY = os.environ["SENFENICO_SECRET_KEY"] # sk_test_...SENFENICO_WEBHOOK_SECRET = os.environ["SENFENICO_WEBHOOK_SECRET"]SENFENICO_WEBHOOK_SECRET is the Signing secret shown on the dashboard’s Developer › Webhooks page.
from django.db import models
class Order(models.Model): PENDING, PAID, EXPIRED = "pending", "paid", "expired"
amount = models.PositiveIntegerField() # XOF, integer status = models.CharField(max_length=20, default=PENDING) # opaque reference: don't test its format senfenico_reference = models.CharField( max_length=200, null=True, blank=True, unique=True ) checkout_url = models.URLField(max_length=500, blank=True) created_at = models.DateTimeField(auto_now_add=True)
class WebhookDelivery(models.Model): # value of X-Senfenico-Delivery id = models.CharField(max_length=100, primary_key=True) received_at = models.DateTimeField(auto_now_add=True)python manage.py makemigrations payments && python manage.py migrate2. The client and confirmation
Section titled “2. The client and confirmation”import logging
import requestsfrom django.conf import settings
from .models import Order
BASE_URL = "https://api.senfenico.com/v1/payment"log = logging.getLogger(__name__)_session = requests.Session()
class SenfenicoError(Exception): def __init__(self, message, http=0, code=None, errors=None): super().__init__(message) self.http = http # 0 = no HTTP response self.code = code # API error_code self.errors = errors or {}
def call(method, path, *, json=None, params=None): """Calls the API; returns the envelope or raises SenfenicoError.""" # a create call may wait for the operator's answer timeout = (10, 20 if method == "GET" else 90) try: resp = _session.request( method, BASE_URL + path, json=json, params=params, headers={ "X-API-KEY": settings.SENFENICO_SECRET_KEY, "Accept": "application/json", }, timeout=timeout, ) except requests.RequestException as exc: raise SenfenicoError(f"Network: {exc}") from exc
try: body = resp.json() except ValueError: # e.g. HTML 500 page body = {} if not isinstance(body, dict): body = {}
# Success = HTTP 2xx AND status strictly True if resp.ok and body.get("status") is True: return body raise SenfenicoError( body.get("message") or f"HTTP {resp.status_code}", resp.status_code, body.get("error_code"), body.get("errors"), )
def confirm_order(order: Order) -> bool: """Verifies the payment with the API and marks the order paid.""" if order.status == Order.PAID: return True
chk = call("GET", f"/checkouts/{order.senfenico_reference}/")["data"]
# The checkout can stay "pending" while its charge # succeeded: check the charge too. paid = chk["status"] == "success" if not paid and chk.get("charge_reference"): charge = call("GET", f"/charges/{chk['charge_reference']}/") paid = charge["data"]["status"] == "success" if not paid: return False
if int(chk["amount"]) != order.amount: log.critical("Senfenico: amount mismatch, order %s", order.pk) return False
# Conditional update: the order can only be fulfilled once updated = Order.objects.filter( pk=order.pk, status__in=[Order.PENDING, Order.EXPIRED] ).update(status=Order.PAID) if updated == 1: fulfill_order(order) return True
def fulfill_order(order: Order) -> None: pass # send the email, unlock the product, etc.call() requires resp.ok and status is True, because an invalid key returns "status": "False" as a string (see Missing or invalid key).
3. Views
Section titled “3. Views”import hashlibimport hmacimport jsonimport loggingimport time
from django.conf import settingsfrom django.db import transactionfrom django.http import HttpResponsefrom django.shortcuts import get_object_or_404, redirect, renderfrom django.urls import reversefrom django.views.decorators.csrf import csrf_exemptfrom django.views.decorators.http import require_POST
from . import senfenicofrom .models import Order, WebhookDelivery
log = logging.getLogger(__name__)
@require_POSTdef pay_order(request, order_id): # also check that the order belongs to the user order = get_object_or_404(Order, pk=order_id, status=Order.PENDING)
# A checkout already exists: reuse it if order.checkout_url: return redirect(order.checkout_url)
try: body = senfenico.call("POST", "/checkouts/initialize/", json={ "amount": order.amount, # integer, min. 100 # No "?": Senfenico appends ?reference=... "success_url": request.build_absolute_uri( reverse("payments:return")), "cancel_url": request.build_absolute_uri( reverse("payments:cancel")), }) except senfenico.SenfenicoError as exc: log.error("Checkout: %s (%s)", exc, exc.code) return HttpResponse("Payment unavailable, please retry.", status=502)
order.senfenico_reference = body["data"]["reference"] order.checkout_url = body["data"]["authorization_url"] order.save(update_fields=["senfenico_reference", "checkout_url"]) return redirect(order.checkout_url)
def checkout_return(request): # ?reference= finds the order; it does not prove payment, # so we verify with the API. order = get_object_or_404( Order, senfenico_reference=request.GET.get("reference", "") ) try: paid = senfenico.confirm_order(order) except senfenico.SenfenicoError as exc: log.warning("Verification: %s", exc) paid = False # the webhook or reconciliation will take over return render(request, "payments/return.html", {"order": order, "paid": paid})
def checkout_cancel(request): order = get_object_or_404( Order, senfenico_reference=request.GET.get("reference", "") ) return render(request, "payments/cancel.html", {"order": order})
# ---- Webhook ------------------------------------------------
def verify_senfenico(raw_body: bytes, timestamp, signature, secret: str, tolerance: int = 300) -> bool: if not timestamp or not signature \ or not signature.startswith("v1="): return False try: ts = int(timestamp) except ValueError: return False if abs(time.time() - ts) > tolerance: return False expected = hmac.new(secret.encode(), timestamp.encode() + b"." + raw_body, hashlib.sha256).hexdigest() return hmac.compare_digest(expected, signature[3:])
@csrf_exempt@require_POSTdef senfenico_webhook(request): raw = request.body # raw body if not verify_senfenico( raw, request.headers.get("X-Senfenico-Timestamp"), request.headers.get("X-Senfenico-Signature"), settings.SENFENICO_WEBHOOK_SECRET, ): return HttpResponse(status=400)
event = json.loads(raw) data = (json.loads(event["data"]) # data is a JSON string if isinstance(event["data"], str) else event["data"]) delivery = request.headers.get("X-Senfenico-Delivery", "")
try: # If processing fails, the WebhookDelivery row is rolled # back and Senfenico's retry will be processed. with transaction.atomic(): if delivery: _, created = WebhookDelivery.objects.get_or_create( id=delivery) if not created: return HttpResponse(status=200) # duplicate handle_event(event["event"], data) except Exception: log.exception("Senfenico webhook") return HttpResponse(status=500) return HttpResponse(status=200)
def handle_event(name: str, data: dict) -> None: checkout_ref = None if name == "checkout.success": checkout_ref = data["reference"] elif name == "charge.success": # was the charge created by a checkout? found = senfenico.call("GET", "/checkouts/", params={ "charge_reference": data["reference"], })["data"] checkout_ref = found[0]["reference"] if found else None if not checkout_ref: return # other events ignored
order = Order.objects.filter( senfenico_reference=checkout_ref).first() if order: senfenico.confirm_order(order)from django.urls import path
from . import views
app_name = "payments"urlpatterns = [ path("orders/<int:order_id>/pay/", views.pay_order, name="pay"), path("checkout/return/", views.checkout_return, name="return"), path("checkout/cancel/", views.checkout_cancel, name="cancel"), path("webhooks/senfenico/", views.senfenico_webhook, name="webhook"),]The webhook view processes the event during the request (two GET calls at most). Senfenico expects an answer within 5 seconds. If your processing grows (emails, PDF invoice), move handle_event into a Celery task and answer 200 right away.
4. API responses
Section titled “4. API responses”POST /v1/payment/checkouts/initialize/ (HTTP 201):
{ "status": true, "message": "Checkout initialized", "data": { "reference": "CHK261126-101431--3f9a0c1d2e", "authorization_url": "https://api.senfenico.com/v1/checkout_payment/payment_page/CHK261126-101431--3f9a0c1d2e/", "live_mode": false }}GET /v1/payment/checkouts/{reference}/ after payment:
{ "status": true, "message": "Checkout details retrieved", "data": { "email": null, "reference": "CHK261126-101431--3f9a0c1d2e", "charge_reference": "CH261126-101502-ORANGE_BF-8b41079ee8", "amount": 1000, "success_url": "https://shop.example/checkout/return/", "cancel_url": "https://shop.example/checkout/cancel/", "phone": "76000000", "provider": "orange_bf", "live_mode": false, "created_at": "2026-11-26T10:14:31.512345Z", "updated_at": "2026-11-26T10:15:02.104512Z", "status": "success" }}Checkout accepts neither ext_id nor metadata, so the reference stored on the order is your only link to the payment.
5. Subscribe the webhook
Section titled “5. Subscribe the webhook”On the dashboard Developer › Webhooks page, add https://shop.example/webhooks/senfenico/ for checkout.success and charge.success, in test mode then live mode. Keep the trailing /, since a 301 redirect counts as a failure. Confirm the payment server-side explains why checkout.success alone is not enough.
6. Scheduled reconciliation
Section titled “6. Scheduled reconciliation”from datetime import timedelta
from django.core.management.base import BaseCommandfrom django.utils import timezone
from payments.models import Orderfrom payments.senfenico import SenfenicoError, confirm_order
class Command(BaseCommand): help = "Re-check pending Senfenico orders"
def handle(self, *args, **options): now = timezone.now() pending = Order.objects.filter( status=Order.PENDING, senfenico_reference__isnull=False, created_at__lt=now - timedelta(minutes=10), created_at__gt=now - timedelta(days=2), ) for order in pending.iterator(): try: confirm_order(order) except SenfenicoError as exc: self.stderr.write(f"{order.pk}: {exc}")
# Too old: expired. A late payment still moves it # to "paid" (see confirm_order). Order.objects.filter( status=Order.PENDING, created_at__lte=now - timedelta(days=2), ).update(status=Order.EXPIRED)# crontab*/15 * * * * cd /srv/app && python manage.py senfenico_reconcileThe 2-day window is this example’s choice, not a Senfenico rule.
7. Test
Section titled “7. Test”With an sk_test_ key, create an order for the amount paired with a test number and pay on the page:
The order should be paid on the return page, and your webhook view should receive checkout.success.