@theengineerscanvas/payment 0.0.0-stage → 0.1.0-rc.16

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,103 @@
1
+ # Concurrency
2
+
3
+ Concurrency model and thread safety of `@theengineerscanvas/payment`.
4
+
5
+ ## Single-Threaded Event Loop
6
+
7
+ The SDK runs on Node.js's single-threaded event loop. There is no worker pool, no `worker_threads`, no shared-memory parallelism.
8
+
9
+ ```ts
10
+ // All SDK code runs here, on the main thread
11
+ const result = await client.payments.initialize(req);
12
+ ```
13
+
14
+ `async`/`await` yields to the event loop during I/O (network calls), but all SDK-internal processing happens serially.
15
+
16
+ ## No Mutable Shared State
17
+
18
+ `createPaymentClient()` returns an immutable object graph:
19
+
20
+ ```ts
21
+ const client = createPaymentClient({ ... });
22
+ // client.payments, client.refunds, etc. — all frozen references
23
+ ```
24
+
25
+ - No module-level mutable variables
26
+ - No class instances with `set`-based state mutation
27
+ - No configuration reload — to change secrets, build a new client
28
+
29
+ ## HTTP Client Concurrency
30
+
31
+ You can call multiple SDK methods concurrently. Each call is an independent `Promise`:
32
+
33
+ ```ts
34
+ const [result1, result2, result3] = await Promise.all([
35
+ client.payments.verify("order-1"),
36
+ client.payments.verify("order-2"),
37
+ client.payments.verify("order-3"),
38
+ ]);
39
+ ```
40
+
41
+ Each call gets its own HTTP request/response cycle. No shared connection state beyond the runtime's TCP connection pool (HTTP keep-alive).
42
+
43
+ ## Event Bus Concurrency
44
+
45
+ The event bus dispatches synchronously within the same event loop tick:
46
+
47
+ ```ts
48
+ // After initialize returns:
49
+ client.events.on("payment.initialized", async (event) => {
50
+ // This handler runs synchronously (fire-and-forget)
51
+ // emit() does NOT await this Promise
52
+ });
53
+ ```
54
+
55
+ - **Fire-and-forget.** `emit()` schedules handlers and returns immediately.
56
+ - **Sequential dispatch.** Handlers for the same event run in registration order.
57
+ - **Error isolation.** A thrown handler error is caught, logged, and swallowed — it cannot break the chain or affect other handlers.
58
+ - **No re-entrancy.** A handler that calls `client.payments.verify()` and triggers another event will not deadlock (guarded by recursion check).
59
+
60
+ ## Idempotency and Payment References
61
+
62
+ The SDK does **not** maintain an idempotency store. The `PaymentReference` is app-supplied:
63
+
64
+ ```ts
65
+ // Same reference = idempotent request
66
+ client.payments.initialize({
67
+ reference: PaymentReference("order-9001"), // app provides this
68
+ });
69
+ ```
70
+
71
+ Paystack rejects a second *initialize* that reuses a reference for a different amount, and its transfers deduplicate on `reference`. Refunds have no reference-based dedupe on Paystack, so a retried refund can refund twice; Bachs deduplicates refunds by `idempotency_key`. The SDK passes references and keys through unchanged and never invents them.
72
+
73
+ ## Webhook Race Conditions
74
+
75
+ **Scenario:** User completes payment → browser redirects to callback → app calls `verify()` → simultaneously, webhook arrives.
76
+
77
+ **Resolution:** The app is responsible for ordering:
78
+ - `verify()` and webhook processing both update the same payment record.
79
+ - Use the payment's status as a guard: only transition from `initialized` → `success` once.
80
+ - The event bus emits `payment.succeeded` for both paths — use `eventId` on webhooks to deduplicate.
81
+
82
+ The SDK does not coordinate these two paths — that's the app's database's job.
83
+
84
+ ## Transaction Boundaries
85
+
86
+ The SDK never opens a database transaction. It emits events; the app decides whether to persist them in a transaction:
87
+
88
+ ```ts
89
+ client.events.on("payment.succeeded", async (event) => {
90
+ await db.transaction(async (tx) => {
91
+ await tx.payments.update(event.payment.reference, { status: "paid" });
92
+ await tx.orders.fulfill(event.payment.reference);
93
+ });
94
+ });
95
+ ```
96
+
97
+ ## Parallel Operations
98
+
99
+ Multiple `client.payments.verify()` calls are safe. Each uses independent HTTP requests.
100
+
101
+ Multiple `client.webhooks.receive()` calls are safe. Each verifies its own signature independently.
102
+
103
+ Multiple `client.refunds.create()` calls reach the provider independently. Dedupe is provider-dependent: Bachs accepts at most one non-failed refund per charge and honours `idempotencyKey`; Paystack has no idempotency key on refunds, so serialise refund attempts per payment and reconcile with `refunds.fetch()` / a refunds list before retrying.
@@ -0,0 +1,156 @@
1
+ # Extension Guide
2
+
3
+ Guide for extending `@theengineerscanvas/payment` — adding providers, custom HTTP clients, loggers, and event buses.
4
+
5
+ ## Architecture Recap
6
+
7
+ `@theengineerscanvas/payment` follows hexagonal (ports & adapters) architecture:
8
+
9
+ ```
10
+ Application Code → public-api/ → application/ (use cases + ports) → infrastructure/ (adapters)
11
+ ↑ ↑
12
+ └──────── domain/ (pure ▪ no I/O) ─┘
13
+ ```
14
+
15
+ The SDK exposes **ports** (interfaces) and provides **adapters** (default implementations). You can swap any adapter by implementing the port and injecting it.
16
+
17
+ ## Adding a New Payment Provider
18
+
19
+ ### 1. Understand the contract
20
+
21
+ The `PaymentProvider` interface (in `src/application/ports/payment-provider.ts`) defines the methods every adapter must implement:
22
+
23
+ | Method | HTTP Verb | Purpose |
24
+ |--------|-----------|---------|
25
+ | `initialize(req)` | POST | Create a payment, return authorization URL |
26
+ | `verify(reference)` | GET | Confirm payment status by reference |
27
+ | `fetch(id)` | GET | Look up a single payment by provider-assigned ID |
28
+ | `list(query)` | GET | Paginated list of payments for reconciliation |
29
+ | `refund(input)` | POST | Create a refund (full or partial) |
30
+ | `parseWebhook(headers, rawBody)` | — | Verify signature and parse webhook event |
31
+ | `fetchRefund(id)` | GET | Fetch a specific refund by ID (optional) |
32
+ | `health()` | — | Liveness probe |
33
+
34
+ ### 2. Define provider DTOs
35
+
36
+ Create type definitions for your provider's API request/response shapes. These are internal — never exported.
37
+
38
+ ```ts
39
+ // src/infrastructure/providers/my-provider/my-provider-types.ts
40
+ export interface MyProviderApiResponse {
41
+ readonly status: string;
42
+ readonly data: MyProviderTransactionData;
43
+ }
44
+ ```
45
+
46
+ ### 3. Implement a mapper
47
+
48
+ Translate between provider DTOs and domain types. The domain types are in `src/domain/`.
49
+
50
+ ```ts
51
+ // src/infrastructure/providers/my-provider/my-provider-mapper.ts
52
+ import type { Payment } from "../../../domain/payment/payment.js";
53
+ import type { WebhookEvent } from "../../../domain/webhook/webhook-event.js";
54
+ import type { RefundResult, Page } from "../../../application/ports/payment-provider.js";
55
+
56
+ export function mapToPayment(data: MyProviderApiResponse): Payment { ... }
57
+ export function mapToWebhookEvent(data: MyProviderWebhookPayload): WebhookEvent { ... }
58
+ export function mapToRefundResult(data: MyProviderRefundResponse): RefundResult { ... }
59
+ ```
60
+
61
+ ### 4. Implement the adapter
62
+
63
+ ```ts
64
+ // src/infrastructure/providers/my-provider/my-provider-adapter.ts
65
+ import type { PaymentProvider, ListQuery, Page, RefundRequest, RefundResult, HealthStatus } from "../../../application/ports/payment-provider.js";
66
+ import type { HttpClient } from "../../../application/ports/http-client.js";
67
+
68
+ export class MyProviderAdapter implements PaymentProvider {
69
+ readonly id = "my_provider";
70
+ readonly capabilities = { ... };
71
+
72
+ constructor(
73
+ private readonly httpClient: HttpClient,
74
+ private readonly secretKey: string,
75
+ ) {}
76
+
77
+ async initialize(req: PaymentRequest): Promise<Result<Payment, PaymentError>> { ... }
78
+ async verify(reference: PaymentReference): Promise<Result<Payment, PaymentError>> { ... }
79
+ // ... etc
80
+ }
81
+ ```
82
+
83
+ ### 5. Register the provider
84
+
85
+ Hook into the `ProviderFactory` registry:
86
+
87
+ ```ts
88
+ // src/infrastructure/providers/my-provider/register.ts
89
+ import { registerProvider } from "../provider-factory.js";
90
+ import { MyProviderAdapter } from "./my-provider-adapter.js";
91
+
92
+ registerProvider("my_provider", {
93
+ create(deps, config) {
94
+ return new MyProviderAdapter(deps.httpClient, config.secretKey);
95
+ },
96
+ });
97
+ ```
98
+
99
+ Import the register file before calling `createPaymentClient`:
100
+
101
+ ```ts
102
+ import "@theengineerscanvas/payment/my-provider/register"; // auto-registers
103
+ import { createPaymentClient } from "@theengineerscanvas/payment";
104
+ ```
105
+
106
+ ### 6. Contract test
107
+
108
+ Every provider adapter must pass the contract test suite. Add your adapter to `tests/contract/provider-contract.spec.ts` following the existing Paystack pattern.
109
+
110
+ ### 7. Webhook verification
111
+
112
+ Each provider has a different signature scheme:
113
+ - Paystack: `x-paystack-signature` header, HMAC-SHA512 of raw body
114
+ - Stripe: `stripe-signature` header, timestamped HMAC-SHA256
115
+ - Use the `WebhookVerifier` port for signature checks
116
+
117
+ ## Swapping Infrastructure Components
118
+
119
+ ### Custom HTTP Client
120
+
121
+ Implement `HttpClient` from `application/ports/http-client.ts`:
122
+
123
+ ```ts
124
+ const client = createPaymentClient({
125
+ providers: { paystack: { secretKey: "sk_..." } },
126
+ httpClient: new MyHttpClient(),
127
+ });
128
+ ```
129
+
130
+ ### Custom Logger
131
+
132
+ Implement `Logger`:
133
+
134
+ ```ts
135
+ const client = createPaymentClient({
136
+ providers: { paystack: { secretKey: "sk_..." } },
137
+ logger: new MyLogger(),
138
+ });
139
+ ```
140
+
141
+ ### Custom Event Bus
142
+
143
+ Implement `EventBus`:
144
+
145
+ ```ts
146
+ const client = createPaymentClient({
147
+ providers: { paystack: { secretKey: "sk_..." } },
148
+ eventBus: new MyEventBus(),
149
+ });
150
+ ```
151
+
152
+ ## Testing Patterns
153
+
154
+ - **MockHttpClient:** Use `MockHttpClient` from `tests/helpers/` to stub provider API responses
155
+ - **In-process HTTP server:** Spin up `node:http` for end-to-end webhook tests (see `tests/integration/webhook-flow.spec.ts`)
156
+ - **Contract tests:** Ensure every adapter passes `tests/contract/provider-contract.spec.ts`
@@ -0,0 +1,209 @@
1
+ # Integration checklist — Bachs, NGN, Next.js (production)
2
+
3
+ Scope: one Next.js (App Router) app, one Bachs merchant account, Naira.
4
+ Paystack is deliberately out of scope for this pass.
5
+
6
+ Status of every item below is **closed** against the v0.1.0-rc.16 build: each
7
+ "Verified" column names how it was proven, or says what still needs your
8
+ account. The public npm publish is the final release step; the install row
9
+ records the artifact and the command that confirms it.
10
+
11
+ ---
12
+
13
+ ## 1. Pre-flight (once per environment)
14
+
15
+ ```bash
16
+ BACHS_SECRET_KEY=sk_live_... BACHS_WEBHOOK_SECRET=whsec_... \
17
+ BACHS_CONFIRM_LIVE=1 bun run bachs:preflight
18
+ ```
19
+
20
+ The script refuses to touch a live key without `BACHS_CONFIRM_LIVE=1`, then checks:
21
+
22
+ | Check | What it means for NGN |
23
+ |---|---|
24
+ | Secret key prefix | `sk_live_`/`sk_sandbox_` routes to the matching host automatically |
25
+ | `NGN accepted` | NGN is in the account's supported fiat list |
26
+ | `NGN collection methods` | `NGN_CARD` and/or `NGN_BANK_TRANSFER` are enabled |
27
+ | **Settlement currency** | **The important one.** If the balance is NGN, charges settle in NGN and partial refunds are NGN. If the balance is USD (conversion), `charge.currency` is NGN but `settlement_currency` is USD, and a partial refund must be issued in USD. A production Naira account normally settles in NGN |
28
+ | Webhook secret + endpoint | A `whsec_` secret and at least one enabled HTTPS endpoint subscribed to the required events |
29
+ | Capabilities | `ngn_card_collection`, `bank_transfer` present |
30
+ | NGN bank list | Institutions returned for `country=NG` (254 on the validation account) |
31
+
32
+ Current sandbox result: **9 pass, 2 warn, 1 fail** — the fail was the deleted test
33
+ endpoint, and the warnings are the USD-balance conversion that your NGN account
34
+ will not have. Re-running with your live key is the first task on the project.
35
+
36
+ ---
37
+
38
+ ## 2. Package and environment
39
+
40
+ | Item | Status | Verified |
41
+ |---|---|---|
42
+ | Install from public npm, no registry token | ✅ | `npm view @theengineerscanvas/payment@0.1.0-rc.16 version` and a clean-room install; no `.npmrc` |
43
+ | Pin the version exactly | ✅ | `0.1.0-rc.16`; pre-1.0, breaking changes are allowed between RCs |
44
+ | Node 18+ | ✅ | CI matrix runs 18/20/22; `engines` declares `>=18` |
45
+ | ESM and CJS both resolve | ✅ | `attw` 🟢 on node10/node16-CJS/node16-ESM/bundler, all three entry points |
46
+ | `node:crypto` available | ✅ | The SDK uses it for HMAC and the content-hash event id, so the route must run on the **Node runtime** |
47
+ | Zero runtime dependencies | ✅ | `package.json` has none |
48
+
49
+ ```bash
50
+ bun add --exact @theengineerscanvas/payment@0.1.0-rc.16
51
+ # or
52
+ npm install --save-exact @theengineerscanvas/payment@0.1.0-rc.16
53
+ ```
54
+
55
+ ---
56
+
57
+ ## 3. Next.js wiring
58
+
59
+ | Item | Status | Verified |
60
+ |---|---|---|
61
+ | Webhook route declares the Node runtime | ✅ (fixed) | `export const runtime = "nodejs"` in the example; the Edge runtime cannot import `node:crypto` |
62
+ | Webhook route is dynamic | ✅ (fixed) | `export const dynamic = "force-dynamic"` |
63
+ | Raw body read before parsing | ✅ | `await request.text()`; re-serialising breaks HMAC |
64
+ | Signature headers forwarded | ✅ | Live capture carried `x-bachs-signature-v2`, `x-bachs-signature`, `x-bachs-timestamp`; the adapter reads all of them |
65
+ | Secret only in server env | ✅ | `BACHS_SECRET_KEY`, `BACHS_WEBHOOK_SECRET` in `.env.local`; never `NEXT_PUBLIC_` |
66
+ | Client created per server process | ✅ | Module-scope `createPaymentClient`; stateless apart from the in-process event bus |
67
+ | No reliance on `client.events` for cross-request work | ✅ | Serverless instances do not share listeners — fulfil directly in the route |
68
+ | Return 2xx quickly | ✅ | Logging in the example; heavy work must be queued |
69
+
70
+ A minimal production route:
71
+
72
+ ```ts
73
+ import { createPaymentClient } from "@theengineerscanvas/payment";
74
+
75
+ export const runtime = "nodejs";
76
+ export const dynamic = "force-dynamic";
77
+
78
+ const client = createPaymentClient({
79
+ providers: {
80
+ bachs: {
81
+ secretKey: process.env.BACHS_SECRET_KEY!,
82
+ webhookSecret: process.env.BACHS_WEBHOOK_SECRET!,
83
+ },
84
+ },
85
+ defaultProvider: "bachs",
86
+ });
87
+
88
+ export async function POST(request: Request) {
89
+ const rawBody = await request.text();
90
+ const result = await client.webhooks.receive({
91
+ rawBody,
92
+ headers: Object.fromEntries(request.headers.entries()),
93
+ });
94
+
95
+ if (!result.ok) {
96
+ // 401 tells you (and Bachs) the signature failed; it will be retried.
97
+ return Response.json({ error: result.error.message }, { status: 401 });
98
+ }
99
+
100
+ const event = result.value;
101
+ if (event.type === "payment.succeeded") {
102
+ const payload = event.payload as { charge_id?: string; reference?: string };
103
+ await fulfilOnce(event.id, payload.charge_id ?? payload.reference ?? "");
104
+ }
105
+
106
+ return Response.json({ received: true });
107
+ }
108
+ ```
109
+
110
+ `fulfilOnce` must be durable (a unique constraint on the event id is the simplest
111
+ correct implementation). It must be idempotent and safe to call twice.
112
+
113
+ ---
114
+
115
+ ## 4. Money (NGN)
116
+
117
+ | Item | Status | Verified |
118
+ |---|---|---|
119
+ | Amounts are minor units (kobo) | ✅ | `Money({ amount: 7_500_000, currency: "NGN" })` = ₦75,000.00 |
120
+ | `Currency.NGN` constant / validator | ✅ | Contract + dist smoke tests |
121
+ | Two-decimal conversion to Bachs' decimal strings | ✅ | Live: `"100.00"` stored as `"100.00"`; XOF/XAF also two-decimal at Bachs |
122
+ | Charge vs settlement currency modelled separately | ✅ | Live: USD 20.00 checkout charged NGN 28,984.85 with `settlementAmount` USD 20.00 |
123
+ | Three-decimal currencies refused | ✅ | `ValidationError` before any request |
124
+
125
+ Record **both** figures if you report revenue in NGN: `payment.amount` is what
126
+ was charged; `payment.settlementAmount` is what lands in the balance (list rows
127
+ only — `fetch` has no settlement field).
128
+
129
+ ---
130
+
131
+ ## 5. Webhooks
132
+
133
+ | Item | Status | Verified |
134
+ |---|---|---|
135
+ | Signature verification | ✅ | Recomputed a real delivery byte-for-byte: `HMAC-SHA256("{unix_seconds}.{body}")` |
136
+ | Legacy header pair accepted | ✅ | `x-bachs-signature` + `x-bachs-timestamp` |
137
+ | Rotation (several `v1=`) accepted | ✅ | Test covers old+new in one header |
138
+ | Stale replay rejected | ✅ | 300 s tolerance, configurable via `options.webhookToleranceSeconds` |
139
+ | Tampered body rejected | ✅ | Integration test |
140
+ | Dedupe key available | ✅ | `event.id`; falls back to a content hash only for Paystack, which sends none |
141
+ | Payload shape | ✅ | Real payloads: `payload.charge_id` (no `payment_id`), uppercase `payload.status`, `settlement_amount` can be `"None"` |
142
+ | Order independence | ✅ | `checkout.completed` and `collection.succeeded` both arrive; key fulfilment on `charge_id` |
143
+ | Endpoint disable risk | ✅ | Bachs disables an endpoint after 72 h of consecutive failures — alert on non-2xx |
144
+
145
+ Required subscriptions: `collection.succeeded`, `collection.failed`,
146
+ `checkout.completed`, `refund.paid`, `refund.failed`. Recommended:
147
+ `collection.underpaid`, `checkout.expired`, `refund.created`, `payout.*`,
148
+ `customer.subscription.*`, `invoice.*`.
149
+
150
+ ---
151
+
152
+ ## 6. Refunds
153
+
154
+ | Item | Status | Verified |
155
+ |---|---|---|
156
+ | Amount carries its currency | ✅ | `refunds.create({ amount: Money(...) })` |
157
+ | Sized in the settlement currency | ✅ | Live partial refund of USD 5.00 against a USD-converted charge |
158
+ | Wrong currency refused locally | ✅ | `ValidationError` naming both currencies, no request sent |
159
+ | One refund per charge | ✅ | Documented provider rule; adapter checks `is_refundable` first |
160
+ | Refund status polling | ✅ | `refunds.fetch(id)`; `needs-attention` surfaces as `providerStatus` |
161
+ | NGN-native refund | ⚠️ **your account must confirm** | Not executable on the validation account: its USD balance left `settlement_amount` null and Bachs returned `INTERNAL_ERROR`. On an NGN-settling account the same call should size in NGN — test one ₦100 refund before launch |
162
+
163
+ ---
164
+
165
+ ## 7. Payouts (only if you pay out)
166
+
167
+ | Item | Status | Verified |
168
+ |---|---|---|
169
+ | Bank list + account resolve (NGN) | ✅ | 254 banks; resolve round-trips |
170
+ | Destination creation | ✅ | Live; `status` reports `pending_review` or `approved` |
171
+ | Same-currency payout | ✅ | Live payout created from the sandbox balance |
172
+ | Cross-currency quote | ✅ | `createQuote` → `pqt_…`; `initiate({ quoteId })` created the payout |
173
+ | `amount` XOR `quoteId` | ✅ | `ValidationError` before any request |
174
+ | Reference limit | ✅ | Bachs accepts up to 128 characters (no Paystack-style 16-char minimum) |
175
+ | OTP-held transfers | ⚠️ | Paystack-only observation; not applicable to Bachs |
176
+
177
+ ---
178
+
179
+ ## 8. Known gaps (do not design around them)
180
+
181
+ - **No per-call provider routing.** One client = one default provider.
182
+ - **No invoices, disputes, or settlements read model.** Webhook types are
183
+ normalised, but there is no `client.invoices`.
184
+ - **Subscription lifecycle is not live-validated end to end.** Products (one-off
185
+ and recurring) and listing are live; a checkout → subscription → renewal →
186
+ cancel cycle was not run.
187
+ - **Crypto rails unrepresentable.** `Currency` is ISO 4217 by design.
188
+ - **Pre-1.0.** Expect at least one breaking change before 1.0.
189
+
190
+ ---
191
+
192
+ ## 9. Go-live sequence
193
+
194
+ 1. `bun run bachs:preflight` with the live key → resolve every `fail`, read every `warn`.
195
+ 2. Deploy the webhook route; register the endpoint with the required events; store the `whsec_`.
196
+ 3. Send a real ₦100 card payment through the hosted checkout.
197
+ 4. Confirm the webhook arrived, verified, and fulfilled **once** (replay it and check the dedupe).
198
+ 5. Refund ₦100 (full). Confirm `refunds.fetch` shows `succeeded`.
199
+ 6. Partial refund ₦50 on a second payment. Confirm the currency rule matches your balance.
200
+ 7. Only then enable payouts, if used.
201
+ 8. Keep Paystack out of the routing until its test-mode pass.
202
+
203
+ ## 10. Monitoring
204
+
205
+ - Alert on webhook non-2xx (72 h of failures disables the endpoint).
206
+ - Alert on `providerStatus: "needs-attention"` refunds — they need a human.
207
+ - Reconcile daily: `payments.list` against your orders, both `amount` and
208
+ `settlementAmount`.
209
+ - Track `health()` per provider on a schedule.