GuidesStatic website
Accept KHQR payments on a static website
A static site (plain HTML, Hugo, Astro, a landing page) can take KHQR payments with one small server function, because the API key must never be in the browser. The example uses a Cloudflare Worker that serves your pages, creates the Dalo payment when the customer clicks Pay, sends them to the hosted checkout, and verifies the signed webhook with Web Crypto. The same code runs on Vercel Edge or Netlify Edge with small changes.
How it fits together
- The page calls
POST /api/paywith the item, never the price. - The Worker looks the price up, calls
POST /v1/paymentswith your secret key, and returnscheckout_url. - The customer pays on the checkout page and returns to
/thanks.html. - Dalo calls
/webhooks/dalo; the Worker checks the signature and records the paid order.
1. The Worker
// src/worker.js: a Cloudflare Worker that serves your static site and adds two routes.
// Secrets: npx wrangler secret put DALO_API_KEY and npx wrangler secret put DALO_WEBHOOK_SECRET
const DALO = "https://dalodesk.com";
const PRICES = { coffee: "2.50", tshirt: "12.00" }; // prices live on the server, never in the page
export default {
async fetch(request, env) {
const url = new URL(request.url);
if (request.method === "POST" && url.pathname === "/api/pay") {
const { item } = await request.json();
const amount = PRICES[item];
if (!amount) return Response.json({ error: "unknown_item" }, { status: 400 });
const orderId = `order_${crypto.randomUUID().slice(0, 8)}`;
const response = await fetch(`${DALO}/v1/payments`, {
method: "POST",
headers: { Authorization: `Bearer ${env.DALO_API_KEY}`, "Content-Type": "application/json", "Idempotency-Key": `${orderId}_1` },
body: JSON.stringify({ amount, reference_id: orderId, metadata: { item }, success_url: `${url.origin}/thanks.html` }),
});
const payment = await response.json();
if (!response.ok) return Response.json({ error: payment.error }, { status: 502 });
return Response.json({ checkout_url: payment.checkout_url });
}
if (request.method === "POST" && url.pathname === "/webhooks/dalo") {
const raw = await request.text();
if (!(await verifySignature(raw, request.headers.get("x-khqr-signature"), env.DALO_WEBHOOK_SECRET))) {
return new Response(null, { status: 401 });
}
const event = JSON.parse(raw);
const payment = event.data.payment;
if (event.type === "payment.completed" && event.livemode === true && !payment.test) {
// Record the paid order: Workers KV, D1, or an email to yourself.
console.log("paid", payment.reference_id, payment.amount, payment.metadata?.item);
}
return new Response(null, { status: 200 });
}
return env.ASSETS.fetch(request); // everything else: your static pages
},
};
// Web Crypto HMAC check (works in Workers, Vercel Edge, Deno and other edge runtimes).
async function verifySignature(raw, 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 key = await crypto.subtle.importKey("raw", new TextEncoder().encode(secret), { name: "HMAC", hash: "SHA-256" }, false, ["verify"]);
const signature = new Uint8Array(m[2].match(/../g).map(h => parseInt(h, 16)));
return crypto.subtle.verify("HMAC", key, signature, new TextEncoder().encode(`${m[1]}.${raw}`));
}
// wrangler.jsonc
{
"name": "my-shop",
"main": "src/worker.js",
"compatibility_date": "2026-11-01",
"assets": { "directory": "./public", "binding": "ASSETS", "run_worker_first": ["/api/*", "/webhooks/*"] }
}
run_worker_first sends only /api/* and /webhooks/* to your code; every other path is served straight from ./public.
2. The Pay button
<!-- public/index.html -->
<button id="pay">Pay $2.50 with KHQR</button>
<script>
document.getElementById("pay").onclick = async () => {
const response = await fetch("/api/pay", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ item: "coffee" }),
});
const { checkout_url, error } = await response.json();
if (checkout_url) location.href = checkout_url;
else alert("Payment could not start, please try again. (" + error + ")");
};
</script>
Then set secrets and deploy:
npx wrangler secret put DALO_API_KEY # dk_test_... while you build
npx wrangler secret put DALO_WEBHOOK_SECRET # whsec_...
npx wrangler deploy
In the Dalo dashboard, add the webhook endpoint https://your-site.com/webhooks/dalo.
3. Details that matter
- Prices on the server. The page sends
item; the Worker decides the amount. A price sent by the browser can be changed by anyone. - The thanks page is not proof.
/thanks.html?status=paidcan be typed by hand. The paid record comes from the verified webhook. - Somewhere to keep orders. Write paid orders to Workers KV or D1, or email them to yourself, from the webhook.
- Web Crypto (
crypto.subtle) verifies the HMAC in constant time and works in every edge runtime; Node'scryptomodule is not needed.
4. Test, then go live
With a dk_test_ key, click Pay and press Simulate paid on the checkout. Test events arrive with livemode: false, so the Worker logs nothing as paid; that is expected. Verify the store in the dashboard and replace the secret with a dk_live_ key to go live.
Questions
Can I accept KHQR on a site with no backend at all?
You need one small server piece, because the API key must stay secret. A Cloudflare Worker, a Vercel or Netlify function, or a single PHP file is enough.
Does this work on GitHub Pages?
GitHub Pages cannot run server code. Keep the pages there and put the Worker on its own route or subdomain, or move the whole site to Cloudflare, Vercel or Netlify.
How do I know who paid?
Put your order id in reference_id and anything else (item, customer email) in metadata. Both come back in the webhook.
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 statusFlask and FastAPIChoosing an API