GuidesDjango

Accept KHQR payments in Python and Django

In Python, create a KHQR payment with one requests.post to Dalo's /v1/payments, redirect the customer to checkout_url, and verify the X-KHQR-Signature header on request.body with hmac.compare_digest before marking the order paid. The client and signature check below are plain Python, so they work the same in Flask or FastAPI.

Updated 12 November 2026 · Base URL https://dalodesk.com · Full reference in the API docs

1. Keys

Create a store at dalodesk.com/app, a test API key and a webhook endpoint pointing at https://your-site.com/webhooks/dalo.

pip install requests
export DALO_API_KEY=dk_test_...
export DALO_WEBHOOK_SECRET=whsec_...

2. A small client

# payments/dalo.py
import os
import requests

DALO = "https://dalodesk.com"


class DaloError(Exception):
    def __init__(self, status, code):
        super().__init__(f"Dalo {status} {code}")
        self.status, self.code = status, code


def _call(method, path, **kwargs):
    headers = {"Authorization": f"Bearer {os.environ['DALO_API_KEY']}", **kwargs.pop("headers", {})}
    response = requests.request(method, DALO + path, headers=headers, timeout=20, **kwargs)
    body = response.json()
    if not response.ok:
        raise DaloError(response.status_code, body.get("error"))
    return body


def create_payment(amount, reference_id, success_url, idempotency_key):
    return _call("POST", "/v1/payments", headers={"Idempotency-Key": idempotency_key},
                 json={"amount": amount, "reference_id": reference_id, "success_url": success_url})


def get_payment(payment_id):
    return _call("GET", f"/v1/payments/{payment_id}")

3. Signature check

# payments/signature.py
import hashlib
import hmac
import re
import time

SIGNATURE = re.compile(r"^t=(\d+),v1=([a-f0-9]{64})$")


def verify_signature(raw_body: bytes, header: str, secret: str) -> bool:
    m = SIGNATURE.match(header or "")
    if not m or abs(time.time() - int(m.group(1))) > 300:
        return False
    expected = hmac.new(secret.encode(), m.group(1).encode() + b"." + raw_body, hashlib.sha256).hexdigest()
    return hmac.compare_digest(expected, m.group(2))

4. Views and URLs

The example assumes an Order model with total (a DecimalField), status, payment_attempt and dalo_payment_id.

# payments/views.py
import json
import os
import re

from django.http import HttpResponse, HttpResponseNotFound
from django.shortcuts import get_object_or_404, redirect, render
from django.views.decorators.csrf import csrf_exempt
from django.views.decorators.http import require_POST

from .dalo import DaloError, create_payment, get_payment
from .models import Order
from .signature import verify_signature


@require_POST
def pay(request, order_id):
    order = get_object_or_404(Order, pk=order_id)
    try:
        payment = create_payment(
            amount=f"{order.total:.2f}",
            reference_id=str(order.pk),
            success_url=request.build_absolute_uri("/checkout/return"),
            idempotency_key=f"order_{order.pk}_{order.payment_attempt}",
        )
    except DaloError:
        return render(request, "checkout/try_again.html", status=502)
    order.dalo_payment_id = payment["id"]
    order.save(update_fields=["dalo_payment_id"])
    return redirect(payment["checkout_url"])


@csrf_exempt
@require_POST
def dalo_webhook(request):
    if not verify_signature(request.body, request.headers.get("X-KHQR-Signature", ""), os.environ["DALO_WEBHOOK_SECRET"]):
        return HttpResponse(status=401)
    event = json.loads(request.body)
    payment = event["data"]["payment"]
    if event["type"] == "payment.completed" and event["livemode"] is True and not payment.get("test"):
        order = Order.objects.filter(pk=payment["reference_id"]).first()
        if order and order.status != "paid" and payment["amount"] == f"{order.total:.2f}":
            order.status = "paid"
            order.save(update_fields=["status"])
    return HttpResponse(status=200)


def checkout_return(request):
    payment_id = request.GET.get("payment_id", "")
    if not re.fullmatch(r"pay_[\w-]{4,64}", payment_id):
        return HttpResponseNotFound("Unknown payment")
    payment = get_payment(payment_id)
    return render(request, "checkout/return.html", {"paid": payment["status"] == "paid", "status": payment["status"]})
# payments/urls.py
from django.urls import path
from . import views

urlpatterns = [
    path("checkout/<int:order_id>/pay", views.pay),
    path("checkout/return", views.checkout_return),
    path("webhooks/dalo", views.dalo_webhook),
]

5. Test, then go live

With the dk_test_ key, open the checkout and press Simulate paid, or call POST /v1/payments/{id}/simulate with {"status": "paid"}. When it works, verify the store in the dashboard and switch to a dk_live_ key.

Questions

Is there a pip package?

Not needed: requests and the standard library (hmac, hashlib) cover the whole API, as shown above.

How do I read the raw body in Flask or FastAPI?

Flask: request.get_data(). FastAPI: await request.body(). Pass those bytes to verify_signature before parsing JSON.

Why does the webhook return 403?

Django's CSRF middleware is rejecting it. Keep the @csrf_exempt decorator on the webhook view; the signature check protects it instead.

Get a test key in two minutes.

Sign in with your email, create a store in test mode and copy a dk_test_ key. No merchant application, no paperwork. Free up to 50 sales a month.

Start freeRead the API docs