Relocate the ~6k-file docs tree from the repo root into plugins/document-navigator/docs/ so the plugin is self-contained and portable. docs/superpowers/ (specs and plans) stays at the repo root. Moved via cp+rm rather than git mv because directory rename() fails with EPERM on this WSL /mnt DrvFs mount; git rename-detection pairs the identical-content files at commit time. Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
10 KiB
10 KiB
@suaveplan/payment - Universal payment intent lifecycle, state-machine enforcement, webhook signature verification, receipt generation, fraud scoring, refund tracking, tax calculation, retry orchestration, reconciliation, and card tokenization. Provider-agnostic — concrete gateway adapters (Stripe, PayPal, Test) ship in this package; bring-your-own PaymentProvider for everything else.
Universal payment intent lifecycle, webhook signature verification,
receipt generation, fraud scoring, refund tracking, tax calculation, retry
orchestration, reconciliation, and PCI-conscious card tokenisation.
Provider-agnostic — drop in TestGateway, StripeGateway, PayPalGateway,
or any custom PaymentProvider. Zero browser- or Node-only imports; runs
on Bun, Node ≥ 18, modern browsers, and Web Workers.
Documentation tree
- engine — Orchestrates the full payment intent lifecycle on top of an injected
PaymentProvider. Owns the state machine (`VALID_…- engine — Orchestrates the full payment intent lifecycle on top of an injected
PaymentProvider. Owns the state machine (`VALID_…
- engine — Orchestrates the full payment intent lifecycle on top of an injected
- error-codes — Stable, namespaced error registry and discriminated
PaymentErrorclass for the payment package. Every failure path in…- error-codes — Stable, namespaced error registry and discriminated
PaymentErrorclass for the payment package. Every failure path in…
- error-codes — Stable, namespaced error registry and discriminated
- fraud — Risk-scoring helper that flags suspicious payment attempts before they reach the provider. Four built-in rules — veloci…
- fraud — Risk-scoring helper that flags suspicious payment attempts before they reach the provider. Four built-in rules — veloci…
- paypal — PayPal REST adapter for the abstract
PaymentGatewaycontract. Talks to the Orders API v2 via injectedfetch, caches… - stripe — Stripe REST adapter for the abstract
PaymentGatewaycontract. Talks to the Payment Intents API directly via injected… - test — In-memory
PaymentGatewayimplementation used by tests, fixtures, and local development. Records every operation in ch… - types — Defines the abstract
PaymentGatewaycontract every concrete adapter (the in-memoryTestGateway, the Stripe REST ada… - hooks — Tiny generic hooks bus owned by the payment package. It powers the
payment:processingpipeline that fires inside `Pay…- hooks — Tiny generic hooks bus owned by the payment package. It powers the
payment:processingpipeline that fires inside `Pay…
- hooks — Tiny generic hooks bus owned by the payment package. It powers the
- receipt — Generates structured
Receiptobjects fromPaymentIntentplus caller- supplied line items, then provides a minimal p…- receipt — Generates structured
Receiptobjects fromPaymentIntentplus caller- supplied line items, then provides a minimal p…
- receipt — Generates structured
- reconciliation — Reconciles a batch of internal payment records against gateway transaction records, matches them by id, surfaces amount…
- reconciliation — Reconciles a batch of internal payment records against gateway transaction records, matches them by id, surfaces amount…
- refund — Tracks per-intent refund history with balance validation, partial-refund support, and reason categorisation. The `Refun…
- refund — Tracks per-intent refund history with balance validation, partial-refund support, and reason categorisation. The `Refun…
- retry — Generic retry helper for payment operations. Wraps any async function with exponential backoff + jitter, honours a non-…
- retry — Generic retry helper for payment operations. Wraps any async function with exponential backoff + jitter, honours a non-…
- tax — In-memory tax-rate registry and line-item calculator. Supports tax-inclusive (price-includes-tax) and tax-exclusive (pr…
- tax — In-memory tax-rate registry and line-item calculator. Supports tax-inclusive (price-includes-tax) and tax-exclusive (pr…
- tokenization — PCI-conscious card tokeniser. Validates the PAN with the Luhn check, rejects malformed expiry data and expired cards as…
- tokenization — PCI-conscious card tokeniser. Validates the PAN with the Luhn check, rejects malformed expiry data and expired cards as…
- types — Shared type contracts for the payment lifecycle: status union, payment-method descriptors, refund and dispute records,…
- payment — Shared type contracts for the payment lifecycle: status union, payment-method descriptors, refund and dispute records,…
- webhook — Universal webhook signature verifier. Computes an HMAC over a
timestamp.bodyenvelope using `@suaveplan/crypto-h…- webhook — Universal webhook signature verifier. Computes an HMAC over a
timestamp.bodyenvelope using `@suaveplan/crypto-h…
- webhook — Universal webhook signature verifier. Computes an HMAC over a
Install
bun add @suaveplan/payment
Quick start
import {
PaymentEngine,
ReceiptGenerator,
TestGateway,
WebhookVerifier,
} from "@suaveplan/payment";
const gateway = new TestGateway();
const engine = new PaymentEngine({
provider: {
name: gateway.name,
createIntent: async (input) => ({
id: "pi_001",
status: "created",
amount: input.amount,
capturedAmount: { amount: 0n, currency: input.amount.currency },
refundedAmount: { amount: 0n, currency: input.amount.currency },
captureMethod: input.captureMethod ?? "automatic",
refunds: [],
createdAt: new Date().toISOString(),
updatedAt: new Date().toISOString(),
}),
confirmIntent: async () => {
throw new Error("not used in quick start");
},
captureIntent: async () => {
throw new Error("not used in quick start");
},
cancelIntent: async () => {
throw new Error("not used in quick start");
},
refund: async () => {
throw new Error("not used in quick start");
},
getIntent: async () => {
throw new Error("not used in quick start");
},
},
});
engine.on("intent.created", (intent) =>
console.log("created", intent.id, intent.amount)
);
const intent = await engine.createIntent({
amount: { amount: 5000n, currency: "USD" },
captureMethod: "automatic",
});
const verifier = new WebhookVerifier({ secret: "whsec_test" });
const ts = Date.now();
const body = JSON.stringify({
id: "evt_001",
type: "payment.captured",
timestamp: ts,
data: { intentId: intent.id },
});
const sig = verifier.sign(body, ts);
const { payload } = verifier.verify(body, sig, ts);
const receiptGen = new ReceiptGenerator({ merchantName: "Acme" });
const receipt = receiptGen.generate({
intent,
lineItems: [
{
description: "Widget",
quantity: 1,
unitPrice: intent.amount,
total: intent.amount,
},
],
subtotal: intent.amount,
total: intent.amount,
});
console.log(receiptGen.toPlainText(receipt), payload.type);
Modules
engine/engine—PaymentEngine, state-machine enforcement, lifecycle events.webhook/webhook—WebhookVerifier(HMAC + replay window).receipt/receipt—ReceiptGeneratorand plain-text renderer.gateway/types—PaymentGatewayabstract contract.gateway/test— in-memoryTestGateway.gateway/stripe— Stripe REST adapter.gateway/paypal— PayPal REST adapter.fraud/fraud—FraudDetectorscoring.refund/refund—RefundManagerledger.retry/retry—PaymentRetrierwith backoff + jitter.tax/tax—TaxCalculatorjurisdiction registry.tokenization/tokenization—CardTokenizer(Luhn + HMAC).reconciliation/reconciliation—PaymentReconciliationmatcher / report.hooks/hooks—Hooks+paymentHookssingleton +payment:processingpipeline.error-codes/error-codes—PAYMENT_CODES,PaymentError, factory functions.types/payment—PaymentIntent,PaymentProvider,PaymentEventMap,VALID_TRANSITIONS.
Features
- Payment intent lifecycle — 9-state machine (
created→pending→authorized→captured→partially_refunded/refunded/disputed/canceled/failed) withVALID_TRANSITIONSenforcement. - Typed lifecycle events —
intent.created,intent.confirmed,intent.captured,intent.canceled,intent.failed,refund.created,refund.succeeded,refund.failed,dispute.opened,dispute.closed. - Webhook verification — HMAC over
timestamp.body, configurable algorithm (SHA-256/384/512), constant-time compare, replay window. - Receipt generation — structured records + plain-text fallback.
- Concrete gateway adapters —
StripeGateway(Payment Intents API),PayPalGateway(Orders API v2 + OAuth token cache),TestGatewayin-memory. - Fraud scoring — velocity, amount, customer, new-method heuristics.
- Refund manager — partial refunds, balance ledger, reason filtering.
- Retry orchestration — exponential backoff + jitter, non-retryable blocklist.
- Tax calculator — region/country lookup, inclusive + exclusive pricing, exempt items.
- Card tokenisation — Luhn check, brand detection, HMAC-SHA-256 token via Web Crypto.
- Reconciliation — match / discrepancy / unmatched report with normalised status compare.
- Typed errors —
PaymentError extends SuaveplanError<PaymentErrorCode>carrying optionalintentId/currentStatus/targetStatus/ageMsdiscriminants.
License
MIT