GuidesNode.js
Accept KHQR payments in Node.js and Express
In Node.js, a KHQR payment is one fetch to Dalo's POST /v1/payments, a redirect to the returned checkout_url, and a webhook route that verifies the X-KHQR-Signature header with crypto.createHmac before marking the order paid. The file below is a complete Express server you can run as is with a test key.
1. Keys
Create a store at dalodesk.com/app, then a test API key and a webhook endpoint. For local development point the webhook at a tunnel (for example cloudflared or ngrok) to /webhooks/dalo. Then:
npm install express
export DALO_API_KEY=dk_test_...
export DALO_WEBHOOK_SECRET=whsec_...
node server.js
2. The whole server
// server.js (Node 18+, "type": "module" in package.json)
import express from "express";
import crypto from "node:crypto";
const DALO = "https://dalodesk.com";
const { DALO_API_KEY, DALO_WEBHOOK_SECRET } = process.env;
const app = express();
// Demo orders. Use your database here.
const orders = new Map([["1024", { id: "1024", total: "4.50", status: "unpaid", attempt: 1 }]]);
// 1. The webhook needs the raw body, so register it BEFORE express.json().
app.post("/webhooks/dalo", express.raw({ type: "application/json" }), (req, res) => {
const raw = req.body.toString("utf8");
if (!verifySignature(raw, req.get("X-KHQR-Signature"), DALO_WEBHOOK_SECRET)) return res.sendStatus(401);
const event = JSON.parse(raw);
res.sendStatus(200); // answer within 8 seconds, then do the work
const payment = event.data.payment;
if (event.type !== "payment.completed" || event.livemode !== true || payment.test) return;
const order = orders.get(payment.reference_id);
if (order && order.status !== "paid" && payment.amount === order.total) order.status = "paid";
});
app.use(express.json());
// 2. The customer clicks "Pay": create a KHQR payment and send them to the hosted checkout.
app.post("/checkout/:orderId", async (req, res) => {
const order = orders.get(req.params.orderId);
if (!order) return res.sendStatus(404);
const response = await fetch(`${DALO}/v1/payments`, {
method: "POST",
headers: {
Authorization: `Bearer ${DALO_API_KEY}`,
"Content-Type": "application/json",
"Idempotency-Key": `order_${order.id}_${order.attempt}`,
},
body: JSON.stringify({ amount: order.total, reference_id: order.id, success_url: "https://shop.example/checkout/return" }),
signal: AbortSignal.timeout(20000),
});
const payment = await response.json();
if (!response.ok) return res.status(502).send(`Payment could not start (${payment.error}). Please try again.`);
order.paymentId = payment.id;
res.redirect(303, payment.checkout_url);
});
// 3. The return page: the query string is only a hint, so ask Dalo for the real status.
app.get("/checkout/return", async (req, res) => {
const id = String(req.query.payment_id || "");
if (!/^pay_[\w-]{4,64}$/.test(id)) return res.status(400).send("Unknown payment");
const response = await fetch(`${DALO}/v1/payments/${id}`, { headers: { Authorization: `Bearer ${DALO_API_KEY}` } });
if (!response.ok) return res.status(404).send("Unknown payment");
const payment = await response.json();
res.send(payment.status === "paid" ? "Thank you, your payment is confirmed." : `Payment ${payment.status}.`);
});
function verifySignature(rawBody, header, secret) {
const m = /^t=(\d+),v1=([a-f0-9]{64})$/.exec(header || "");
if (!m || Math.abs(Date.now() / 1000 - Number(m[1])) > 300) return false;
const expected = crypto.createHmac("sha256", secret).update(`${m[1]}.${rawBody}`).digest("hex");
return crypto.timingSafeEqual(Buffer.from(expected, "hex"), Buffer.from(m[2], "hex"));
}
app.listen(3000, () => console.log("Shop on http://localhost:3000"));
3. What matters in that code
- Raw body for the webhook.
express.raw()on that one route, registered beforeexpress.json(). If the JSON parser runs first, the bytes change and every signature fails. - Only fulfil on
payment.completedwithlivemode: true. Test-mode events (livemode: false) and the dashboard's "Send test" sample (test: true) are acknowledged and ignored. - Check the amount against your order before marking it paid, and make the update safe to repeat: retries reuse the same
X-KHQR-Deliveryid. - Idempotency-Key per order attempt: a retry or double click returns the same payment. After a QR expires, use the next attempt number.
- Retry on 409 and 503.
409 payment_creation_in_progressand503 provider_busycome with aRetry-Afterheader; wait that many seconds and try again.
4. Test it
curl -i -X POST localhost:3000/checkout/1024 returns a 303 to the checkout. Open it and press Simulate paid: your webhook gets a real signed event with livemode: false. When you are happy, verify the store in the dashboard and switch DALO_API_KEY to the dk_live_ key.
Using Next.js? See the Next.js guide. Building a bot? See the Telegram bot guide.
Questions
Is there an npm package?
Not needed: the built-in fetch in Node 18+ and node:crypto cover the whole API, as in the server above.
Can I call Dalo from the browser?
No. The API key must stay on your server. The browser talks to your server, and your server talks to Dalo.
How do I show the QR in my own page?
Use qr_image_url as an img src, or render qr_string with any QR library. Poll your own server, which calls GET /v1/payments/{id}, every 2 to 3 seconds until the status is final.
Does it work on serverless platforms?
Yes. Any runtime that can make an HTTPS request and read a raw request body works: Vercel, Cloudflare Workers, AWS Lambda, Railway or a VPS.
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 APILaravelNext.jsDjangoTelegram botTest modeCheck payment statusFlask and FastAPIStatic websiteChoosing an API