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

Kiến trúc · ADR 0042

Buying points: a payment-provider interface, a signed mock gateway, a one-transaction grant

Trạng thái
accepted
Ngày
2026-11-21
Người quyết định
Tín (#126)

Context

Students buy points with money (PTS-04). The first gateway is a mock for the demo; the VNPay sandbox replaces it next (#130). Money must turn into points exactly once, even when a gateway retries its callback, sends it twice (VNPay: return URL and IPN) or a student edits a URL.

Decision

  • PaymentProvider interface (modules/points/payments): `createCheckout(purchase) →

{ redirectUrl } and verifyCallback(params) → { txnRef, outcome, providerTxnNo, amountVnd }, which throws PaymentSignatureError instead of returning an unverified result. The active one is the DI token PAYMENT_PROVIDER, chosen by env PAYMENT_PROVIDER (mock` today). VNPay adds a class, a value and its routes; the purchase flow and the grant do not change.

  • The mock signs like VNPay: HMAC-SHA256 under PAYMENT_MOCK_SECRET over the sorted, URI-encoded amountVnd, outcome, txnNo, txnRef. The API plays the gateway's server (POST /payments/mock/checkout/:txnRef, buyer only, PENDING only) and returns a return URL carrying the signed result; the web return page forwards it to the public POST /payments/mock/callback. A forged, tampered or unsigned result is `400

PAYMENT_SIGNATURE_INVALID` and changes nothing.

  • MOCK is off in production unless PAYMENT_MOCK_ENABLED=true (demo deploys), and then PAYMENT_MOCK_SECRET is required at boot. Outside production an unset secret is a random key per process. Disabled means GET /points/packs says enabled: false, checkout is `503

PAYMENTS_DISABLED`, and the gateway routes are 404.

  • Price from the server: packs are a constant in packages/shared (placeholders until #123); the client sends only packCode + clientRequestId, and (userId, clientRequestId) is unique, so a double submit opens one purchase.
  • Settlement in one transaction: lock the PointPurchase row (SELECT … FOR UPDATE); only a PENDING purchase moves. Amount ≠ stored amount → FAILED, no points, AuditLog point_purchase.flagged. FAILED / CANCELLED → that status. PAID → PointsService.credit (EARN / PURCHASE, key purchase:<id>) with the same tx, then PAID + pointEntryId + paidAt. A replayed or concurrent callback waits on the lock, finds it settled and answers granted: false; the ledger key is a second guard.

Consequences

Proven on real Postgres by apps/api/test/integration/point-purchases.int-spec.ts (10 concurrent PAID callbacks → one ledger row). No schema change: PointPurchase and the payment enums already existed. A PENDING purchase never expires yet; #142 adds EXPIRED and the admin view. Refunds are out of scope.