import { PaymentAmountMismatchError, WebhookInvalidError } from './gateway.js' import { MemoryWebhookStore, type WebhookStore } from './stores.js' /** * One-off / reference / mobile-money payments — the model used by Angolan * providers (ProxyPay, EMIS/Multicaixa, AppyPay, UNITEL Money), where there's no * card-on-file recurring charge or self-service portal. This complements * `BillingGateway` (card subscriptions). Recurring billing is modelled by * creating one payment per period (invoice → reference → webhook confirms → the * period is activated). * * **All amounts are integers in the currency's minor unit** (cents; `100 = 1.00`) * — the Stripe convention. Use the `money` helpers (`toMinor`/`formatMoney`) at * the human boundary. Drivers translate to each provider's expected format. */ /** A one-off payment request handed to a `PaymentGateway`. */ export interface PaymentRequest { /** Who is paying — a tenant/user/customer id you reconcile against. */ billableId: string /** Amount in the currency's minor unit (integer; `500000` = 5.000,00 Kz). */ amount: number /** ISO 4217. Defaults to the gateway's own (AOA for Angolan gateways). */ currency?: string /** Your order/invoice id — for idempotency and reconciliation. */ reference?: string description?: string customer?: { name?: string; email?: string; phone?: string } /** When the reference / request stops being payable (epoch ms). */ expiresAt?: number /** Passed to the gateway and echoed back on the webhook. */ metadata?: Record } /** How the customer is told to pay — a reference, a redirect, or a push. */ export interface PaymentInstruction { /** The gateway's id for this payment (status checks + reconciliation). */ id: string status: 'pending' | 'paid' | 'failed' /** Reference-based (Multicaixa/EMIS): the entity + reference to pay. */ reference?: { entity: string; reference: string; amount: number } /** Redirect-based (hosted page): send the customer here. */ url?: string /** Push-based (mobile money): a prompt was sent to this phone. */ push?: { phone: string } /** The raw gateway payload, for logging/debugging. */ raw?: unknown } /** A payment webhook, translated to domain terms — gateway payloads never leak. */ export interface PaymentEvent { /** Unique id at the gateway — for idempotent processing. */ id: string type: 'payment.succeeded' | 'payment.failed' /** The gateway payment/reference id from `createPayment`. */ paymentId: string amount: number /** From the request metadata, when the gateway echoes it back. */ billableId?: string reference?: string raw?: unknown } /** * Payment gateway driver contract for one-off / reference / mobile-money * charges. The app talks to Basalt; only drivers talk to ProxyPay / EMIS / etc. * A driver translates raw webhook payloads into `PaymentEvent`. */ export interface PaymentGateway { readonly name: string /** Create a payment — returns a reference, a redirect URL, or a push. */ createPayment(request: PaymentRequest): Promise /** * Verifies the signature and translates the payload. Throws * `WebhookInvalidError` on a bad signature; returns null for a verified event * that isn't a payment (gateways emit event types we don't act on). */ verifyWebhook(rawBody: string, signature: string | undefined): PaymentEvent | null /** Poll a payment's status — a fallback when you can't receive webhooks. */ getPayment?(id: string): Promise } /** Controllable in-process payment gateway — the test/dev driver. */ export class FakePaymentGateway implements PaymentGateway { readonly name = 'fake' readonly payments: PaymentRequest[] = [] private counter = 0 async createPayment(request: PaymentRequest): Promise { this.payments.push(request) const id = `fake_pay_${++this.counter}` return { id, status: 'pending', reference: { entity: '00000', reference: id, amount: request.amount } } } verifyWebhook(rawBody: string, signature: string | undefined): PaymentEvent { if (signature !== 'valid') throw new WebhookInvalidError() return JSON.parse(rawBody) as PaymentEvent } } export type PaymentRecordStatus = 'pending' | 'paid' | 'failed' /** A payment as tracked in your app's ledger, keyed by the gateway payment id. */ export interface PaymentRecord { /** Gateway payment id — `PaymentInstruction.id` / `PaymentEvent.paymentId`. */ id: string status: PaymentRecordStatus amount: number billableId?: string reference?: string /** Epoch ms. */ createdAt: number updatedAt: number raw?: unknown } /** Input to record a freshly-created (pending) payment. */ export interface NewPayment { id: string amount: number billableId?: string reference?: string raw?: unknown } /** * A ledger of payments keyed by the gateway payment id. Apps record a payment * as `pending` on `createPayment` and let the webhook flip it to `paid`/`failed` * — no more hand-rolling this per app. A memory implementation ships here; back * it with your database in production (a `Payment` table keyed by `id`). */ export interface PaymentStore { /** Insert a pending payment. Idempotent: a no-op if the id already exists. */ create(payment: NewPayment): Promise /** Apply a terminal status; upserts if the payment wasn't recorded first. */ setStatus( id: string, status: PaymentRecordStatus, patch?: { amount?: number; raw?: unknown }, ): Promise get(id: string): Promise } /** In-memory `PaymentStore` — per-process; swap for a durable one in production. */ export class MemoryPaymentStore implements PaymentStore { private readonly records = new Map() async create(payment: NewPayment): Promise { if (this.records.has(payment.id)) return const now = Date.now() this.records.set(payment.id, { id: payment.id, status: 'pending', amount: payment.amount, ...(payment.billableId ? { billableId: payment.billableId } : {}), ...(payment.reference ? { reference: payment.reference } : {}), createdAt: now, updatedAt: now, ...(payment.raw !== undefined ? { raw: payment.raw } : {}), }) } async setStatus( id: string, status: PaymentRecordStatus, patch: { amount?: number; raw?: unknown } = {}, ): Promise { const now = Date.now() const rec: PaymentRecord = this.records.get(id) ?? { id, status, amount: patch.amount ?? 0, createdAt: now, updatedAt: now, } rec.status = status rec.updatedAt = now if (patch.amount != null) rec.amount = patch.amount if (patch.raw !== undefined) rec.raw = patch.raw this.records.set(id, rec) } async get(id: string): Promise { return this.records.get(id) } } /** Result of applying a `PaymentEvent` to the ledger. */ export interface PaymentApplyResult { /** * false = nothing was applied: this event id was already processed (deduped), * or the payment is already `paid` (a later event cannot change a settled * payment — see {@link PaymentLedger.apply}). You did nothing. */ fresh: boolean record?: PaymentRecord } /** Lifecycle events emitted by the ledger — subscribe with `ledger.on(...)`. */ export interface PaymentLedgerEvents { /** A payment was recorded as pending (on `created`). */ recorded: { record: PaymentRecord | undefined; payment: NewPayment } /** A payment was confirmed paid (fresh `apply` of a `payment.succeeded`). */ confirmed: { record: PaymentRecord | undefined; event: PaymentEvent } /** A payment failed (fresh `apply` of a `payment.failed`). */ failed: { record: PaymentRecord | undefined; event: PaymentEvent } } export type PaymentLedgerEvent = keyof PaymentLedgerEvents export type PaymentLedgerListener = ( payload: PaymentLedgerEvents[K], ) => void | Promise export interface PaymentLedgerOptions { /** Where payments are stored. Default: in-memory. */ store?: PaymentStore /** * Webhook-id dedupe store. Default: in-memory. Share one durable store (e.g. * Redis) across the app so a retried callback is applied exactly once. */ webhooks?: WebhookStore /** * Called when a lifecycle listener throws. Listeners are best-effort side * effects (notifications, analytics) that never roll back a payment — a * throwing one is reported here instead. Default: swallow. */ onListenerError?: (error: unknown, event: PaymentLedgerEvent) => void } /** * Ties a `PaymentStore` to webhook idempotency so a retried callback is applied * once. Record a payment on create, then feed every verified `PaymentEvent` * through `apply` — it dedupes by `event.id` and updates the ledger. * * ```ts * const ledger = new PaymentLedger() * const inst = await gateway.createPayment(req) * await ledger.created(inst, req) // pending * // in the webhook route: * const event = gateway.verifyWebhook(raw, sig) * if (event) { * const { fresh, record } = await ledger.apply(event) * if (fresh && record?.status === 'paid') activate(record.billableId!) * } * ``` */ export class PaymentLedger { private readonly store: PaymentStore private readonly webhooks: WebhookStore private readonly onListenerError: (error: unknown, event: PaymentLedgerEvent) => void private readonly listeners: { [K in PaymentLedgerEvent]: Set> } = { recorded: new Set(), confirmed: new Set(), failed: new Set() } constructor(options: PaymentLedgerOptions = {}) { this.store = options.store ?? new MemoryPaymentStore() this.webhooks = options.webhooks ?? new MemoryWebhookStore() this.onListenerError = options.onListenerError ?? (() => {}) } /** * Subscribe to a lifecycle event (`recorded`/`confirmed`/`failed`). Listeners * are best-effort: they run after the payment is safely persisted and a * throwing one never rolls it back (it's reported via `onListenerError`). * Returns an unsubscribe function. */ on(event: K, listener: PaymentLedgerListener): () => void { this.listeners[event].add(listener) return () => { this.listeners[event].delete(listener) } } private async emit( event: K, payload: PaymentLedgerEvents[K], ): Promise { for (const listener of this.listeners[event]) { try { await listener(payload) } catch (error) { this.onListenerError(error, event) } } } /** Record a just-created payment as pending. Call after `createPayment`. */ async created(instruction: PaymentInstruction, request: PaymentRequest): Promise { const payment: NewPayment = { id: instruction.id, amount: request.amount, ...(request.billableId ? { billableId: request.billableId } : {}), ...(request.reference ? { reference: request.reference } : {}), ...(instruction.raw !== undefined ? { raw: instruction.raw } : {}), } await this.store.create(payment) await this.emit('recorded', { record: await this.store.get(instruction.id), payment }) } /** * Apply a verified `PaymentEvent` idempotently. Dedupes by `event.id`; on a * fresh event, flips the ledger record to paid/failed. If persisting fails the * dedupe claim is released so the gateway's retry can reprocess. * * `onFresh` runs **inside the idempotency claim**, after the ledger is * updated — use it for domain side effects (activate a subscription, mark a * booking paid) that must apply exactly once with the payment. If it throws, * the claim is released so the whole thing reprocesses on the gateway's retry. * * State machine: `pending → paid | failed`, `failed → paid | failed` (a retry * that succeeds), and `paid` is terminal. An event for an already-paid payment * — a late `payment.failed`, or a second `payment.succeeded` under a new event * id — changes nothing, does not run `onFresh` and returns `fresh: false`, so * a payment is never un-paid nor its side effects (activating a period) run * twice. */ async apply( event: PaymentEvent, onFresh?: (record: PaymentRecord | undefined, event: PaymentEvent) => Promise | void, ): Promise { const fresh = await this.webhooks.markProcessed(event.id) if (!fresh) return { fresh: false } let record: PaymentRecord | undefined try { const status: PaymentRecordStatus = event.type === 'payment.succeeded' ? 'paid' : 'failed' const current = await this.store.get(event.paymentId) // `paid` is terminal: keep the claim (the event is handled — by doing // nothing) and report it as not fresh. if (current?.status === 'paid') return { fresh: false, record: current } if (status === 'paid') { // Defense in depth: a confirmed payment must settle the amount that was // requested. If the webhook reports a different amount for a payment we // already recorded, refuse to mark it paid — an underpayment or a // forged / mis-routed callback settling an invoice for less. Throwing // here hits the catch below, which releases the claim so the mismatch // surfaces on every retry instead of settling into a paid state. if (current && current.amount > 0 && event.amount !== current.amount) { throw new PaymentAmountMismatchError(event.paymentId, current.amount, event.amount) } } // A failure never rewrites the requested amount: a `payment.failed` that // reports 0 would otherwise erase it and disarm the amount check above // for the retry that follows. const keepAmount = status === 'failed' && current !== undefined await this.store.setStatus(event.paymentId, status, { ...(keepAmount ? {} : { amount: event.amount }), ...(event.raw !== undefined ? { raw: event.raw } : {}), }) record = await this.store.get(event.paymentId) if (onFresh) await onFresh(record, event) } catch (error) { await this.webhooks.release(event.id) throw error } // Best-effort lifecycle emit — after the claim, so a throwing listener never // rolls back the payment (it's reported via onListenerError). await this.emit(event.type === 'payment.succeeded' ? 'confirmed' : 'failed', { record, event }) return { fresh: true, ...(record ? { record } : {}) } } get(id: string): Promise { return this.store.get(id) } }