How to Verify Bank-Transfer VietQR Webhooks (HMAC-SHA256 + D1 Idempotency) on $0/mo Cloudflare Workers
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…
To verify Bank-Transfer VietQR Webhooks using HMAC-SHA256 and D1 Idempotency on Cloudflare Workers and D1, follow these steps:
1. Read the request body as raw text using await c.req.text() before parsing as JSON. This prevents HMAC verification from failing due to whitespace or key-order changes in the JSON.
2. Fail closed by checking if the SEPAY_WEBHOOK_SECRET is empty or unset. If so, return HTTP 503 status to avoid accepting unsigned callbacks from a broken deployment.
3. Validate the X-SePay-Timestamp header, ensuring it matches the format of 9-12 digits and falls within a 300-second window of the server's time. If not valid, return HTTP 401 status.
4. Parse the X-SePay-Signature header, which should be formatted as "sha256=<64-character-hex-string>". If not in this format, return HTTP 401 status.
5. Sign the concatenated string of timestamp.rawBody using the Web Crypto API's SHA-256 digest algorithm with the secret key. Compare the resulting signature in constant time to the received signature. If they match, the webhook is verified successfully.
Rewritten by urgent.news; may contain errors — check the original. How we use AI.
Source: dev.to