If you sell digital products from Vietnam, international PayPal checkout alone leaves local buyers blocked. PayPal rejects domestic Vietnam-to-Vietnam PayPal transfers, and local cards often fail on cross-border merchant accounts.
Bank transfers over VietQR solve that directly: buyers scan a QR code in their banking app, funds settle instantly in VND with zero card fees, and SePay forwards incoming transfers as HTTP webhooks. Running the checkout and webhook handler on Cloudflare Workers + D1 costs $0/mo on Cloudflare's free tier (100,000 requests/day) using only Web Crypto and SQLite.
When we added 450,000 VND VietQR checkout alongside $19 PayPal Business v2 in EdgePay Starter Kit, generating the QR image was the easy part. The real engineering work was making webhook verification fail-closed, idempotent under retries, race-safe under concurrent transfers, and free of personal data in logs.
Here are the four production patterns from src/sepay.ts that keep bank-transfer webhooks safe on Cloudflare Workers and D1.
1. Raw-Body HMAC-SHA256 + 5-Minute Drift Check
Read the request body once as raw text (await c.req.text()) before calling JSON.parse(). Never re-serialize parsed JSON to verify a signature, because whitespace or key-order changes will break HMAC matching.
Fail closed first: if SEPAY_WEBHOOK_SECRET is empty or unset, return HTTP 503 so a broken deploy never accepts unsigned callbacks. Then validate X-SePay-Timestamp (/^\d{9,12}$/ within 300 seconds of server time), parse X-SePay-Signature (/^sha256=([0-9a-f]{64})$/i), sign ${timestamp}.${rawBody} with Web Crypto, and compare in constant time:
const MAX_DRIFT_SEC = 300; async function timingSafeEqual(a: string, b: string): Promise<boolean> { const enc = new TextEncoder(); const [ah, bh] = await Promise.all([ crypto.subtle.digest('SHA-256', enc.encode(a)), crypto.subtle.digest('SHA-256', enc.encode(b)), ]); const av = new Uint8Array(ah), bv = new Uint8Array(bh); let diff = 0; for (let i = 0; i < av.length; i++) diff |= av[i] ^ bv[i]; return diff === 0; } export async function verifySepayHmac(req: Request, rawBody: string, secret: string) { const cleanSecret = secret.trim(); if (!cleanSecret) return { ok: false, status: 503 as const }; const tsRaw = (req.headers.get('x-sepay-timestamp') || '').trim(); const sigRaw = (req.headers.get('x-sepay-signature') || '').trim(); if (!/^\d{9,12}$/.test(tsRaw)) return { ok: false, status: 401 as const }; if (Math.abs(Math.floor(Date.now() / 1000) - Number(tsRaw)) > MAX_DRIFT_SEC) { return { ok: false, status: 401 as const }; } const m = /^sha256=([0-9a-f]{64})$/i.exec(sigRaw); if (!m) return { ok: false, status: 401 as const }; const enc = new TextEncoder(); const key = await crypto.subtle.importKey( 'raw', enc.encode(cleanSecret), { name: 'HMAC', hash: 'SHA-256' }, false, ['sign'] ); const mac = await crypto.subtle.sign('HMAC', key, enc.encode(`${tsRaw}.${rawBody}`)); const expected = Array.from(new Uint8Array(mac), (b) => b.toString(16).padStart(2, '0')).join(''); return (await timingSafeEqual(m[1].toLowerCase(), expected)) ? { ok: true, status: 200 as const } : { ok: false, status: 401 as const }; } Hashing both strings with SHA-256 before XORing gives fixed 32-byte constant-time equality in Workers with zero Node polyfills.
2. INSERT OR IGNORE Dedupe Preserving the First Verdict
Webhook senders retry on timeouts and transient network blips. Insert every verified event into D1 using sepay_tx_id INTEGER PRIMARY KEY before deciding anything:
const ins = await db .prepare( `INSERT OR IGNORE INTO sepay_webhook_events (sepay_tx_id, payment_code, transfer_type, transfer_amount, account_last4, status, verdict, raw_payload_json) VALUES (?, ?, ?, ?, ?, 'failed', 0, ?)` ) .bind(tx.id, tx.code, tx.transferType, tx.transferAmount, tx.accountLast4, rawBody) .run(); if (Number(ins.meta?.changes ?? 0) === 0) { const row = await db .prepare('SELECT status, verdict FROM sepay_webhook_events WHERE sepay_tx_id = ? LIMIT 1') .bind(tx.id) .first<{ status: string; verdict: number }>(); if (row && (row.status === 'processed' || row.status === 'unmatched')) { return { replay: true, verdict: Boolean(row.verdict) }; } } Once a transaction settles as 'processed' or 'unmatched', every retry returns HTTP 200 with the stored { success: verdict } without re-running fulfillment or firing duplicate alerts. If a prior invocation crashed mid-flight while still 'failed', the retry checks vietqr_orders for sepay_tx_id and recovers cleanly.
3. Atomic Conditional UPDATE Against Double-Fulfillment Races
Validate four invariants on the parsed payload before touching an order: transferType === 'in', a positive safe integer VND amount (Number.isSafeInteger), a matching destination account (accountNumber or subAccount), and a trimmed payload.code. Never regex-scrape free-text bank memos (content), where arbitrary buyer text can cause false matches.
Avoid SELECT followed by UPDATE: two parallel transfers carrying the same payment code can both read CREATED and double-fulfill. Let D1 enforce a single winner atomically:
UPDATE vietqr_orders SET status = 'COMPLETED', sepay_tx_id = ?, reference_code = ?, completed_at = datetime('now') WHERE LOWER(payment_code) = LOWER(?) AND status = 'CREATED' AND amount_vnd = ? AND datetime(expires_at) > datetime('now'); Only the single transfer with meta.changes === 1 marks sepay_webhook_events as 'processed' (verdict = 1) and returns 200 { success: true }. Any second payment, wrong amount, expired order, or unknown code hits changes === 0, logs 'unmatched' (verdict = 0) with a non-PII reason (already_paid, amount_mismatch, order_expired, or unknown_code), and returns HTTP 200 { success: false } so SePay stops retrying permanently invalid transfers.
4. Zero PII in Logs and Polling
Bank webhooks carry sensitive personal details (full account numbers, sender descriptions, and transfer memos). Restrict console.log and ops alerts to operational fields only: sepayTxId, paymentCode, amountVnd, reason, and a last-4 masked account (****9012). Never log raw memos, names, full account numbers, SEPAY_WEBHOOK_SECRET, or download tokens. Gate status polling and downloads behind separate CSPRNG tokens checked with timingSafeEqual, unlocking downloads only when status === 'COMPLETED'.
Wrapping Up
You can inspect the companion Cloudflare Workers payment helpers and checklists on GitHub:
https://github.com/buiphucminhtam/edgepay-cloudflare-paypal
For the full production codebase shipping both PayPal Business v2 ($19 USD) and SePay VietQR (450,000 VND) on Cloudflare Workers + D1 with Hono routes and Vitest tests, see EdgePay Starter Kit.