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
PaymentProviderinterface (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_SECRETover the sorted, URI-encodedamountVnd, 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 publicPOST /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 thenPAYMENT_MOCK_SECRETis required at boot. Outside production an unset secret is a random key per process. Disabled meansGET /points/packssaysenabled: 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 onlypackCode+clientRequestId, and(userId, clientRequestId)is unique, so a double submit opens one purchase. - Settlement in one transaction: lock the
PointPurchaserow (SELECT … FOR UPDATE); only a PENDING purchase moves. Amount ≠ stored amount → FAILED, no points, AuditLogpoint_purchase.flagged. FAILED / CANCELLED → that status. PAID →PointsService.credit(EARN / PURCHASE, keypurchase:<id>) with the sametx, then PAID +pointEntryId+paidAt. A replayed or concurrent callback waits on the lock, finds it settled and answersgranted: 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.