GuidesNext.js
Accept KHQR payments in Next.js
In a Next.js App Router project, create the KHQR payment in a Route Handler (or Server Action) with your server-only API key, send the customer to checkout_url, and verify Dalo's signed webhook in a second Route Handler that reads request.text(). Four small files, all on the server. Written for Next.js 15 and later.
1. Environment
# .env.local
DALO_API_KEY=dk_test_...
DALO_WEBHOOK_SECRET=whsec_...
APP_URL=http://localhost:3000
Do not prefix these with NEXT_PUBLIC_: that would ship the key to every browser. Install server-only (npm install server-only) so an accidental client import fails the build.
2. A server-only client
// lib/dalo.ts
import "server-only";
const DALO = "https://dalodesk.com";
export async function dalo(path: string, init: RequestInit = {}) {
const response = await fetch(`${DALO}${path}`, {
...init,
headers: { Authorization: `Bearer ${process.env.DALO_API_KEY}`, "Content-Type": "application/json", ...init.headers },
cache: "no-store",
signal: AbortSignal.timeout(20000),
});
const body = await response.json();
if (!response.ok) throw new Error(`Dalo ${response.status} ${body.error}`);
return body;
}
3. Create the payment
// app/api/checkout/route.ts
import { dalo } from "@/lib/dalo";
export const runtime = "nodejs";
export async function POST(request: Request) {
const { orderId } = await request.json();
const order = await getOrder(orderId); // your database: never trust a price sent by the browser
const payment = await dalo("/v1/payments", {
method: "POST",
headers: { "Idempotency-Key": `order_${order.id}_${order.attempt}` },
body: JSON.stringify({
amount: order.total, // "4.50"
reference_id: order.id,
success_url: `${process.env.APP_URL}/checkout/return`,
}),
});
await savePaymentId(order.id, payment.id);
return Response.json({ checkout_url: payment.checkout_url });
}
On the client, POST the order id to /api/checkout and set window.location.href to the returned checkout_url. Look the price up on the server; never take it from the browser.
4. Verify the webhook
// app/api/webhooks/dalo/route.ts
import crypto from "node:crypto";
export const runtime = "nodejs";
export const dynamic = "force-dynamic";
export async function POST(request: Request) {
const raw = await request.text(); // the exact bytes; never request.json() first
const m = /^t=(\d+),v1=([a-f0-9]{64})$/.exec(request.headers.get("x-khqr-signature") ?? "");
if (!m || Math.abs(Date.now() / 1000 - Number(m[1])) > 300) return new Response(null, { status: 401 });
const expected = crypto.createHmac("sha256", process.env.DALO_WEBHOOK_SECRET!).update(`${m[1]}.${raw}`).digest("hex");
if (!crypto.timingSafeEqual(Buffer.from(expected, "hex"), Buffer.from(m[2], "hex"))) 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) {
await markOrderPaid(payment.reference_id, payment.amount); // idempotent: a repeat delivery changes nothing
}
return new Response(null, { status: 200 });
}
If middleware.ts protects routes, let /api/webhooks/dalo through without auth. Only payment.completed with livemode: true means money arrived; test events and the dashboard sample are acknowledged and ignored.
5. The return page
// app/checkout/return/page.tsx
import { dalo } from "@/lib/dalo";
export default async function ReturnPage({ searchParams }: { searchParams: Promise<{ payment_id?: string }> }) {
const { payment_id = "" } = await searchParams;
if (!/^pay_[\w-]{4,64}$/.test(payment_id)) return <p>Unknown payment.</p>;
const payment = await dalo(`/v1/payments/${payment_id}`);
return payment.status === "paid" ? <p>Thank you, your payment is confirmed.</p> : <p>Payment {payment.status}.</p>;
}
The ?status= query string is a hint for the UI only; this page asks Dalo for the real status from the server.
6. Test, then go live
With a dk_test_ key, open the checkout and press Simulate paid. Point the webhook at a tunnel to localhost:3000 while developing. To go live, verify the store in the dashboard and replace the key with dk_live_.
Questions
Does the webhook work on the Edge runtime?
Use the Node.js runtime (export const runtime = "nodejs") as shown, because the example uses node:crypto. On Edge you would verify with the Web Crypto API instead.
Can I use a Server Action instead of a Route Handler?
Yes. Call the same dalo() helper inside a Server Action and redirect() to checkout_url.
Why does the signature fail on Vercel?
Make sure you read request.text() before anything else and never request.json(). The signature covers the exact raw body.
Can I render the QR myself?
Yes. Show qr_image_url in an img tag, and poll a Route Handler of your own that calls GET /v1/payments/{id} every 2 to 3 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.jsDjangoTelegram botTest modeCheck payment statusFlask and FastAPIStatic websiteChoosing an API