GuidesFlask and FastAPI
Accept KHQR payments in Flask and FastAPI
In Flask, a KHQR payment is one requests.post to Dalo's /v1/payments, a redirect to the returned checkout_url, and a webhook route that checks the X-KHQR-Signature header on request.get_data() before marking the order paid. The file below is a complete Flask app; the FastAPI webhook further down uses the same signature check on await request.body().
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 (a tunnel such as cloudflared or ngrok while developing).
pip install flask requests
export DALO_API_KEY=dk_test_...
export DALO_WEBHOOK_SECRET=whsec_...
flask --app app run
2. The Flask app
# app.py: pip install flask requests
import hashlib
import hmac
import json
import os
import re
import time
import requests
from flask import Flask, abort, redirect, request
DALO = "https://dalodesk.com"
app = Flask(__name__)
orders = {"1024": {"total": "4.50", "status": "unpaid", "attempt": 1}} # demo data: use your database
def dalo(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)
response.raise_for_status()
return response.json()
def verify_signature(raw_body: bytes, header: str, secret: str) -> bool:
m = re.match(r"^t=(\d+),v1=([a-f0-9]{64})$", 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))
@app.post("/checkout/<order_id>")
def checkout(order_id):
order = orders.get(order_id) or abort(404)
payment = dalo("POST", "/v1/payments",
headers={"Idempotency-Key": f"order_{order_id}_{order['attempt']}"},
json={"amount": order["total"], "reference_id": order_id,
"success_url": request.host_url + "checkout/return"})
order["payment_id"] = payment["id"]
return redirect(payment["checkout_url"], code=303)
@app.post("/webhooks/dalo")
def dalo_webhook():
raw = request.get_data() # the exact bytes Dalo signed
if not verify_signature(raw, request.headers.get("X-KHQR-Signature", ""), os.environ["DALO_WEBHOOK_SECRET"]):
abort(401)
event = json.loads(raw)
payment = event["data"]["payment"]
if event["type"] == "payment.completed" and event["livemode"] is True and not payment.get("test"):
order = orders.get(payment["reference_id"])
if order and order["status"] != "paid" and payment["amount"] == order["total"]:
order["status"] = "paid"
return "", 200
@app.get("/checkout/return")
def checkout_return():
payment_id = request.args.get("payment_id", "")
if not re.fullmatch(r"pay_[\w-]{4,64}", payment_id):
abort(404)
payment = dalo("GET", f"/v1/payments/{payment_id}")
return "Thank you, your payment is confirmed." if payment["status"] == "paid" else f"Payment {payment['status']}."
request.get_data()gives the exact bytes Dalo signed. Verify first, thenjson.loads; never re-serialiserequest.json.- Fulfil only on
payment.completedwithlivemode: true, and check the amount. The status check keeps the handler safe when a delivery is retried. Idempotency-Keyper order attempt: a double click returns the same payment. After a QR expires, add one to the attempt.- If your app uses Flask-WTF's CSRF protection, exempt the webhook route; the signature protects it instead.
3. FastAPI
Creating the payment is the same requests call (or httpx.AsyncClient). The webhook reads the raw body with await request.body():
# FastAPI: the same webhook (verify_signature as in the Flask example)
import json
import os
from fastapi import FastAPI, Request, Response
app = FastAPI()
@app.post("/webhooks/dalo")
async def dalo_webhook(request: Request):
raw = await request.body() # bytes, before any parsing
if not verify_signature(raw, request.headers.get("x-khqr-signature", ""), os.environ["DALO_WEBHOOK_SECRET"]):
return Response(status_code=401)
event = json.loads(raw)
payment = event["data"]["payment"]
if event["type"] == "payment.completed" and event["livemode"] is True and not payment.get("test"):
await mark_order_paid(payment["reference_id"], payment["amount"]) # your code, safe to run twice
return Response(status_code=200)
4. Test, then go live
With the dk_test_ key, POST /checkout/1024, open the checkout and press Simulate paid. Your webhook receives a real signed event with livemode: false: the app acknowledges it and ships nothing. When it works, verify the store in the dashboard and switch to a dk_live_ key.
Using Django? See the Django guide.
Questions
Is there a pip package for Dalo?
Not needed: requests plus the standard library (hmac, hashlib) cover the whole API, as in the app above.
Why does the signature never match in Flask?
You are probably signing request.json re-encoded. Use request.get_data() exactly as received, and the whsec_ secret of the same endpoint.
Can I use httpx with async FastAPI?
Yes. Send the same JSON body and headers with httpx.AsyncClient().post(...) and a timeout of about 20 seconds.
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.
More guidesKHQR payment APILaravelNode.jsNext.jsDjangoTelegram botTest modeCheck payment statusStatic websiteChoosing an API