Context
Students buy points (PTS-04). ADR-0042 put the gateway behind PaymentProvider and shipped a signed mock. #130 adds the VNPay sandbox (test cards, no real money). VNPay reports a payment twice: the Return URL (the buyer's browser, which may never arrive) and the IPN (VNPay's server calling ours, retried until we answer 00 or 02). Points must be granted once even when both arrive, and a forged, tampered, wrong-amount or unknown result must change nothing.
Sources (official VNPay docs, read 2026-11-22): payment API (parameters, checksum, IPN codes, retry policy, response codes) and sandbox test cards.
Decision
VnpayPaymentProvider(modules/points/payments), chosen byPAYMENT_PROVIDER=vnpay.createCheckoutbuildsVNPAY_PAY_URL?…withvnp_Version=2.1.0,vnp_Command=pay,vnp_TmnCode,vnp_Amount(đồng × 100),vnp_CurrCode=VND,vnp_TxnRef(ourproviderTxnRef),vnp_OrderInfo(unaccented, letters/digits/spaces only),vnp_OrderType=other,vnp_Locale=vn,vnp_ReturnUrl,vnp_IpAddr(the visitor the BFF vouches for, elsereq.ip),vnp_CreateDateandvnp_ExpireDatein GMT+7yyyyMMddHHmmss. Both dates derive from the purchase'screatedAt, so a replayed checkout builds the same URL.- Signature (
vnpay-signature.ts): everyvnp_*field exceptvnp_SecureHash[Type], sorted by name,urlencode(name)=urlencode(value)joined by&, HMAC-SHA512 underVNPAY_HASH_SECRET, hex.urlencodeis the docs' PHP sample: space →+, only letters, digits and-_.kept, everything else%XXof its UTF-8 bytes. The Node sample (encodeURIComponent,%20→+) and the Java sample agree on every value we send; they differ only on!'()*~, which our values never contain. Inbound, the samples disagree on whether an empty-valued field is signed (PHP/Node keep it, Java drops it), so both forms are accepted — each needs the secret. Hex is compared case-insensitively in constant time. The merchant code must be ours. - Payment window:
vnp_ExpireDate=createdAt+PAYMENT_PENDING_TIMEOUT_MINUTESminusmin(5, max(1, ⌊timeout/3⌋))minutes (30 → 25, 5 → 4). VNPay closes its page before our expiry (ADR-0045), so the IPN for a last-second payment lands while the purchase is PENDING. - Outcome: PAID only for
vnp_ResponseCode=00andvnp_TransactionStatus=00;24→ CANCELLED; anything else (including07, debited but suspect) → FAILED, no points; an admin reconciles a07with VNPay and an ADJUST. - The IPN grants —
GET /api/v1/payments/vnpay/ipn, public, answers VNPay's JSON (never the envelope), through the same locked, idempotent settlement as ADR-0042, in VNPay's order of checks: bad signature or foreignvnp_TmnCode→97; unknownvnp_TxnRef→01; amount ≠ stored (whatever the status, so VNPay's retries keep getting it; the first one marks FAILED and auditspoint_purchase.flagged) →04; already settled — a replay, a concurrent duplicate, or an IPN after expiry (auditedpoint_purchase.late_callback) →02; moved out of PENDING now →00; any unexpected failure (database down) or a caller outsideVNPAY_IPN_ALLOWED_IPS→99, so VNPay retries (up to 10 times, 5 minutes apart). - The Return URL shows, never grants — the web page
/learn/points/purchase-resultforwards VNPay's query toPOST /api/v1/payments/vnpay/return(via/bff/payments/vnpay/return), which verifies the signature (400PAYMENT_SIGNATURE_INVALID), reads the purchase (404 if unknown; a stale PENDING one expires first) and answers it with VNPay'sreportedOutcome. A PENDING purchase withreportedOutcome: PAIDmeans "paid, waiting for the IPN": the page polls every 3 s (20 times at most). This is VNPay's own rule (the Return URL must not update the order) and keeps a single writer for money. - Local development without a tunnel: VNPay's IPN cannot reach
localhost. Preferred: a tunnel (cloudflared tunnel --url http://localhost:4000orngrok http 4000), and register<tunnel>/api/v1/payments/vnpay/ipnas the IPN URL for the sandbox terminal in VNPay's merchant portal (the IPN URL is configured there, not per request). Fallback:VNPAY_SETTLE_ON_RETURN=truelets the verified return settle through the IPN's exact path (same row lock, same ledger key, so return + IPN still grant once). It is refused at boot in production. - Config (validated in
env.ts, listed in.env.example, secrets empty):VNPAY_TMN_CODE,VNPAY_HASH_SECRET,VNPAY_PAY_URL(sandbox default),VNPAY_RETURN_URL(defaultWEB_URL/learn/points/purchase-result),VNPAY_IPN_ALLOWED_IPS(optional), andVNPAY_SETTLE_ON_RETURN.PAYMENT_PROVIDER=vnpaywithout code or secret refuses to boot. - No secret in logs: the provider never logs; the request logger and the error filter redact
vnp_SecureHash,vnp_SecureHashTypeandsignaturein URLs (the IPN is a GET); the signed checkout URL is returned only to its buyer.
Manual sandbox checklist (when the team has credentials)
- Register a sandbox merchant (link on the payment API page above); put the emailed terminal code and hash secret in
.env.local(PAYMENT_PROVIDER=vnpay,VNPAY_TMN_CODE,VNPAY_HASH_SECRET) — never in chat, a commit or a ticket. - Start a tunnel to the API and set the IPN URL in the sandbox merchant portal; or, local only,
VNPAY_SETTLE_ON_RETURN=true. - Buy
PACK_100in the wallet; the browser lands onsandbox.vnpayment.vn. Pay with the NCB test card9704198526191432198, holderNGUYEN VAN A, issued07/15, OTP123456. - Expect: the result page shows "Đã thanh toán, đang chờ VNPay xác nhận" then "Thanh toán thành công"; the API log shows the IPN with
vnp_SecureHash=[redacted]; onePointLedgerrowpurchase:<id>;PointPurchasePAID with VNPay'svnp_TransactionNo. - Cancel on VNPay's page → CANCELLED, no points. Insufficient-funds card
9704195798459170488→ FAILED. Pay, then wait past the purchase timeout before the IPN (stop the tunnel) → EXPIRED,02, auditpoint_purchase.late_callback. - Use VNPay's IPN re-send in the merchant portal →
02, balance unchanged.
Consequences
Proven without credentials: known-answer signature vectors computed by an independent implementation of the PHP sample (tests/roles/student/pts-vnpay), every RspCode branch, e2e over the shipped app, and on real Postgres 10 concurrent identical IPNs and IPNs racing the return → one ledger row (apps/api/test/integration/vnpay-payments.int-spec.ts). A live sandbox payment is still pending: VNPay's exact echo of vnp_OrderInfo and of empty fields is the one thing a known-answer test written from the docs cannot settle. The mock stays the default provider; switching is one env var. No schema change: PaymentProviderKind.VNPAY already existed. Refunds and the QueryDR reconciliation API are out of scope.