Bỏ qua, tới nội dung chính

Kiến trúc · ADR 0051

VNPay sandbox: a second payment provider, the IPN grants, the return URL shows

Trạng thái
accepted (live sandbox run pending credentials)
Ngày
2026-11-22
Người quyết định
Tín (#130)

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 by PAYMENT_PROVIDER=vnpay. createCheckout builds VNPAY_PAY_URL?… with vnp_Version=2.1.0, vnp_Command=pay, vnp_TmnCode, vnp_Amount (đồng × 100), vnp_CurrCode=VND, vnp_TxnRef (our providerTxnRef), vnp_OrderInfo (unaccented, letters/digits/spaces only), vnp_OrderType=other, vnp_Locale=vn, vnp_ReturnUrl, vnp_IpAddr (the visitor the BFF vouches for, else req.ip), vnp_CreateDate and vnp_ExpireDate in GMT+7 yyyyMMddHHmmss. Both dates derive from the purchase's createdAt, so a replayed checkout builds the same URL.
  • Signature (vnpay-signature.ts): every vnp_* field except vnp_SecureHash[Type], sorted by name, urlencode(name)=urlencode(value) joined by &, HMAC-SHA512 under VNPAY_HASH_SECRET, hex. urlencode is the docs' PHP sample: space → +, only letters, digits and -_. kept, everything else %XX of 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_MINUTES minus min(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=00 and vnp_TransactionStatus=00; 24 → CANCELLED; anything else (including 07, debited but suspect) → FAILED, no points; an admin reconciles a 07 with 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 foreign vnp_TmnCode → 97; unknown vnp_TxnRef → 01; amount ≠ stored (whatever the status, so VNPay's retries keep getting it; the first one marks FAILED and audits point_purchase.flagged) → 04; already settled — a replay, a concurrent duplicate, or an IPN after expiry (audited point_purchase.late_callback) → 02; moved out of PENDING now → 00; any unexpected failure (database down) or a caller outside VNPAY_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-result forwards VNPay's query to POST /api/v1/payments/vnpay/return (via /bff/payments/vnpay/return), which verifies the signature (400 PAYMENT_SIGNATURE_INVALID), reads the purchase (404 if unknown; a stale PENDING one expires first) and answers it with VNPay's reportedOutcome. A PENDING purchase with reportedOutcome: PAID means "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:4000 or ngrok http 4000), and register <tunnel>/api/v1/payments/vnpay/ipn as 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=true lets 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 (default WEB_URL/learn/points/purchase-result), VNPAY_IPN_ALLOWED_IPS (optional), and VNPAY_SETTLE_ON_RETURN. PAYMENT_PROVIDER=vnpay without 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_SecureHashType and signature in URLs (the IPN is a GET); the signed checkout URL is returned only to its buyer.

Manual sandbox checklist (when the team has credentials)

  1. 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.
  2. Start a tunnel to the API and set the IPN URL in the sandbox merchant portal; or, local only, VNPAY_SETTLE_ON_RETURN=true.
  3. Buy PACK_100 in the wallet; the browser lands on sandbox.vnpayment.vn. Pay with the NCB test card 9704198526191432198, holder NGUYEN VAN A, issued 07/15, OTP 123456.
  4. 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]; one PointLedger row purchase:<id>; PointPurchase PAID with VNPay's vnp_TransactionNo.
  5. 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, audit point_purchase.late_callback.
  6. 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.