@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.
- package/LICENSE +201 -0
- package/README.md +323 -2
- package/dist/adapters/nestjs/index.cjs +4979 -0
- package/dist/adapters/nestjs/index.cjs.map +1 -0
- package/dist/adapters/nestjs/index.d.cts +313 -0
- package/dist/adapters/nestjs/index.d.ts +313 -0
- package/dist/adapters/nestjs/index.js +4974 -0
- package/dist/adapters/nestjs/index.js.map +1 -0
- package/dist/index.cjs +4865 -0
- package/dist/index.cjs.map +1 -0
- package/dist/index.d.cts +171 -0
- package/dist/index.d.ts +171 -0
- package/dist/index.js +4822 -0
- package/dist/index.js.map +1 -0
- package/dist/payment-client-DNhLWboh.d.cts +1257 -0
- package/dist/payment-client-DNhLWboh.d.ts +1257 -0
- package/docs/agents/cookbook.md +467 -0
- package/docs/api-stability.md +104 -0
- package/docs/architecture.md +119 -0
- package/docs/bachs-guide.md +359 -0
- package/docs/bachs-sandbox-validation.md +138 -0
- package/docs/concurrency.md +103 -0
- package/docs/extension-guide.md +156 -0
- package/docs/integration-checklist.md +209 -0
- package/docs/migration-guide.md +401 -0
- package/docs/performance.md +86 -0
- package/docs/provider-guide.md +150 -0
- package/docs/public-api.md +1108 -0
- package/docs/security.md +120 -0
- package/docs/versioning.md +95 -0
- package/llms.txt +97 -0
- package/package.json +141 -4
- package/public-api.json +452 -0
|
@@ -0,0 +1,467 @@
|
|
|
1
|
+
# Cookbook: using @theengineerscanvas/payment
|
|
2
|
+
|
|
3
|
+
Everything an agent needs to use this package correctly, organised by task. Every snippet is
|
|
4
|
+
written against the real public API. When a rule matters, it says **why**, because the rules
|
|
5
|
+
exist for failure modes that are expensive in production.
|
|
6
|
+
|
|
7
|
+
## 0. Invariants
|
|
8
|
+
|
|
9
|
+
Break any of these and the integration is wrong, even if it compiles:
|
|
10
|
+
|
|
11
|
+
1. **Money is in minor units.** `Money({ amount: 2900, currency: "USD" })` is $29.00. Display
|
|
12
|
+
formatting is the app's job. There are no floats anywhere in the SDK's money path — never
|
|
13
|
+
multiply or divide amounts yourself.
|
|
14
|
+
2. **Expected failures return `Result`.** Always branch on `result.ok`. `result.error` is a typed
|
|
15
|
+
`PaymentError` (message is safe to show users, details live in `meta`/`cause`).
|
|
16
|
+
3. **Only programmer errors throw.** `ValidationError` (bad input, e.g. a subscription update
|
|
17
|
+
with two intents) and `ConfigurationError` (bad client config) are thrown. Catching them is
|
|
18
|
+
optional; they indicate a bug in the calling code.
|
|
19
|
+
4. **Webhooks are the source of truth for fulfilment.** A redirect means "the browser came back",
|
|
20
|
+
not "money moved". Fulfil on `payment.succeeded` (or an equivalent) and nothing else.
|
|
21
|
+
5. **Raw body is mandatory for webhook verification.** Read `req.text()` / `arrayBuffer()` first;
|
|
22
|
+
never `JSON.parse` and re-serialise — bytes change and every signature fails.
|
|
23
|
+
6. **References and idempotency keys are app-owned.** The SDK never generates a payment
|
|
24
|
+
reference. Make references unique per business operation and pass `idempotencyKey` on
|
|
25
|
+
create/refund/payout calls — but note that **retry safety is provider-dependent**: Bachs
|
|
26
|
+
documents an `Idempotency-Key` header (and per-refund key), Paystack documents none, so a
|
|
27
|
+
retried Paystack write can repeat. Check `client.providers.capabilities(id).supportsIdempotencyKey`,
|
|
28
|
+
and on Paystack reconcile (`payments.fetch`, a refunds lookup) before retrying an uncertain write.
|
|
29
|
+
7. **A catalog checkout has no known amount yet.** When you pass `products`, the provider prices the
|
|
30
|
+
cart, so the `Payment` returned by `initialize()` has no `amount`. Read it from `verify()` /
|
|
31
|
+
`fetch()` / `list()` or the webhook payload. `amount` and `products` are mutually exclusive in
|
|
32
|
+
`PaymentRequest`; combining them does not compile.
|
|
33
|
+
|
|
34
|
+
## 1. Setup
|
|
35
|
+
|
|
36
|
+
```ts
|
|
37
|
+
import { createPaymentClient } from "@theengineerscanvas/payment";
|
|
38
|
+
|
|
39
|
+
const client = createPaymentClient({
|
|
40
|
+
providers: {
|
|
41
|
+
bachs: {
|
|
42
|
+
secretKey: process.env.BACHS_SECRET_KEY!, // sk_sandbox_... routes to the sandbox host
|
|
43
|
+
webhookSecret: process.env.BACHS_WEBHOOK_SECRET!, // whsec_... from the webhook endpoint
|
|
44
|
+
},
|
|
45
|
+
paystack: {
|
|
46
|
+
secretKey: process.env.PAYSTACK_SECRET_KEY!,
|
|
47
|
+
webhookSecret: process.env.PAYSTACK_WEBHOOK_SECRET,
|
|
48
|
+
},
|
|
49
|
+
},
|
|
50
|
+
defaultProvider: "bachs", // which provider client.payments/refunds/products/... use
|
|
51
|
+
logging: { level: "info" }, // omit for a no-op logger
|
|
52
|
+
});
|
|
53
|
+
```
|
|
54
|
+
|
|
55
|
+
- `createPaymentClient.fromEnv()` builds the same thing from environment variables (see the
|
|
56
|
+
README table). Use it when the deployment already has the variables.
|
|
57
|
+
- Provider config: `secretKey` (required), `webhookSecret`, `baseUrl` (override), `timeoutMs`,
|
|
58
|
+
`enabled`, `options`, and `allowInsecureBaseUrl` (local stubs only: an `http://` base URL is
|
|
59
|
+
rejected at construction otherwise). Bachs also reads `options.webhookToleranceSeconds` (default 300).
|
|
60
|
+
- Client-wide `http.timeoutMs` / `http.baseUrl` are fallbacks; a provider's own value wins.
|
|
61
|
+
`retry.maxRetries` (default 1) and `retry.delayMs` (default 500 ms + jitter) apply to `GET`/`HEAD`
|
|
62
|
+
only — mutating calls are never retried automatically. Invalid values throw `ConfigurationError`
|
|
63
|
+
instead of being ignored.
|
|
64
|
+
- **Bachs secret keys must match the host.** `sk_sandbox_` → `sandbox-api.bachs.io`,
|
|
65
|
+
`sk_live_` → `api.bachs.io`; the adapter picks the host from the key unless `baseUrl` is set.
|
|
66
|
+
- For tests, `createMockClient()` returns `{ client, http }` with no network (section 12).
|
|
67
|
+
|
|
68
|
+
## 2. Payments
|
|
69
|
+
|
|
70
|
+
### 2.1 Take a one-off payment (hosted checkout)
|
|
71
|
+
|
|
72
|
+
```ts
|
|
73
|
+
const result = await client.payments.initialize({
|
|
74
|
+
amount: Money({ amount: 7500000, currency: "NGN" }), // ₦75,000.00
|
|
75
|
+
reference: PaymentReference(`order_${order.id}`), // unique per account, forever
|
|
76
|
+
customer: { kind: "new", email: user.email, name: user.name },
|
|
77
|
+
callbackUrl: "https://app.example.com/checkout/success",
|
|
78
|
+
idempotencyKey: `checkout_${order.id}`, // safe to retry this call
|
|
79
|
+
});
|
|
80
|
+
|
|
81
|
+
if (!result.ok) return errorResponse(result.error);
|
|
82
|
+
redirect(result.value.authorizationUrl!);
|
|
83
|
+
```
|
|
84
|
+
|
|
85
|
+
- `customer` variants: `{ kind: "new", email, name?, phone? }`,
|
|
86
|
+
`{ kind: "existing", providerCustomerId }`, `{ kind: "inline", customer }`.
|
|
87
|
+
- Optional: `metadata` (≤20 keys on Bachs), `expiresAt` (Bachs clamps to 24 h),
|
|
88
|
+
`channels` (best-effort mapping to Bachs corridors; unknown channels fall back to all).
|
|
89
|
+
- **Bachs `success_url`/`cancel_url` must be publicly reachable** — `localhost` is rejected even
|
|
90
|
+
in sandbox. Use a tunnel while developing.
|
|
91
|
+
- `result.value.id` is the provider resource id. On Bachs that is the checkout id (`chk_...`);
|
|
92
|
+
the payment id (`ch_...`) only exists after payment.
|
|
93
|
+
|
|
94
|
+
### 2.2 Sell a catalog product (required for subscriptions)
|
|
95
|
+
|
|
96
|
+
```ts
|
|
97
|
+
const checkout = await client.payments.initialize({
|
|
98
|
+
amount: Money({ amount: 2900, currency: "USD" }), // ignored on the cart path
|
|
99
|
+
reference: PaymentReference(`sub_${user.id}_${Date.now()}`),
|
|
100
|
+
customer: { kind: "existing", providerCustomerId: customer.id },
|
|
101
|
+
products: [{ productId: "prod_abc123", quantity: 1 }],
|
|
102
|
+
callbackUrl: "https://app.example.com/billing/success",
|
|
103
|
+
});
|
|
104
|
+
```
|
|
105
|
+
|
|
106
|
+
- `products` sends a provider cart instead of an ad-hoc amount. Bachs **requires** a cart to
|
|
107
|
+
start a subscription; ad-hoc pricing only sells one-off amounts.
|
|
108
|
+
- Paystack rejects `products` with `UnsupportedProviderError` — check the provider before using it.
|
|
109
|
+
- Pay-what-you-want: add `amount` to the cart item (`{ productId, amount: Money(...) }`).
|
|
110
|
+
|
|
111
|
+
### 2.3 Verify on the return page
|
|
112
|
+
|
|
113
|
+
```ts
|
|
114
|
+
// Bachs appends ?checkout_id=chk_... to your success_url.
|
|
115
|
+
const result = await client.payments.verify(PaymentReference(searchParams.checkout_id!));
|
|
116
|
+
if (result.ok && result.value.status.kind === "success") showReceipt(result.value);
|
|
117
|
+
```
|
|
118
|
+
|
|
119
|
+
- **Paystack** verifies by your reference. **Bachs** has no reference lookup: pass a checkout id
|
|
120
|
+
(`chk_`) or a payment id (`ch_`/`pay_`/`chrg_`). Passing your own reference returns a clear
|
|
121
|
+
`ProviderBadRequestError` — that is by design, not a bug to work around.
|
|
122
|
+
- Treat `verify()` as a convenience for the browser landing. Fulfilment still comes from the webhook.
|
|
123
|
+
|
|
124
|
+
### 2.4 Fetch and list
|
|
125
|
+
|
|
126
|
+
```ts
|
|
127
|
+
const payment = await client.payments.fetch("ch_1a2b3c4d5e6f");
|
|
128
|
+
|
|
129
|
+
const page = await client.payments.list({ page: 1, perPage: 50, status: "succeeded" });
|
|
130
|
+
if (page.ok) {
|
|
131
|
+
page.value.items; // Payment[]
|
|
132
|
+
page.value.total;
|
|
133
|
+
page.value.nextCursor; // Bachs: pass as { cursor: page.value.nextCursor }
|
|
134
|
+
}
|
|
135
|
+
```
|
|
136
|
+
|
|
137
|
+
- Bachs lists `page`/`perPage` internally as `limit`/`offset`, but the SDK accepts `cursor` too
|
|
138
|
+
(preferred for Bachs) and returns `nextCursor`.
|
|
139
|
+
- Unsupported filters (Bachs: `from`/`to`/`customer`) are logged and ignored — never assume they applied.
|
|
140
|
+
|
|
141
|
+
### 2.5 Statuses
|
|
142
|
+
|
|
143
|
+
| `status.kind` | Meaning | Fulfil? |
|
|
144
|
+
|---|---|---|
|
|
145
|
+
| `initialized` | created, not yet paid | no |
|
|
146
|
+
| `pending` | in progress (Bachs: processing/underpaid) | no |
|
|
147
|
+
| `success` | money collected (`paidAt`) | **yes** |
|
|
148
|
+
| `failed` | declined (`reason`, `failedAt`) | no |
|
|
149
|
+
| `abandoned` | expired/cancelled | no |
|
|
150
|
+
| `refunded` | refunded (`refundedAt`, `refundId`) | reverse the entitlement |
|
|
151
|
+
|
|
152
|
+
`isFinalStatus(status)` / `isTransitionAllowed(from, to)` are exported. An unrecognised provider
|
|
153
|
+
status maps to `pending`, never to `success`.
|
|
154
|
+
|
|
155
|
+
## 3. Webhooks
|
|
156
|
+
|
|
157
|
+
### 3.1 Receive and verify
|
|
158
|
+
|
|
159
|
+
```ts
|
|
160
|
+
// Next.js App Router
|
|
161
|
+
export async function POST(request: Request) {
|
|
162
|
+
const rawBody = await request.text(); // RAW. Not request.json().
|
|
163
|
+
const signature = request.headers.get("x-bachs-signature-v2") ?? "";
|
|
164
|
+
|
|
165
|
+
const result = await client.webhooks.receive({
|
|
166
|
+
provider: "bachs", // optional; omit to auto-detect
|
|
167
|
+
rawBody,
|
|
168
|
+
signature,
|
|
169
|
+
headers: Object.fromEntries(request.headers.entries()), // Bachs needs several headers
|
|
170
|
+
});
|
|
171
|
+
|
|
172
|
+
if (!result.ok) return new Response("invalid", { status: 401 });
|
|
173
|
+
|
|
174
|
+
const event = result.value;
|
|
175
|
+
if (event.type === "payment.succeeded") await fulfilOrder(event.payload);
|
|
176
|
+
return Response.json({ received: true }); // 2xx within 10 s
|
|
177
|
+
}
|
|
178
|
+
```
|
|
179
|
+
|
|
180
|
+
- Signature requirements: **Paystack** HMAC-SHA512 in `x-paystack-signature` (signed with
|
|
181
|
+
`webhookSecret ?? secretKey`). **Bachs** HMAC-SHA256 over `"{timestamp}.{rawBody}"` in
|
|
182
|
+
`x-bachs-signature-v2` (or `x-bachs-signature` + `x-bachs-timestamp`), signed with the
|
|
183
|
+
endpoint's `whsec_...`. Bachs **requires** `webhookSecret`; there is no fallback to the API key.
|
|
184
|
+
- Both verify the exact bytes. `Buffer.from(await req.arrayBuffer())` works too.
|
|
185
|
+
- Return `2xx` as soon as the event is stored, do slow work after. Return `5xx` to be retried
|
|
186
|
+
(Bachs retries 5 times over ~80 minutes); return `400` only to refuse a delivery.
|
|
187
|
+
- Deduplicate on `event.id` — deliveries are at-least-once and may arrive out of order. Compare
|
|
188
|
+
`event.createdAt` before overwriting stored state.
|
|
189
|
+
|
|
190
|
+
### 3.2 Event names
|
|
191
|
+
|
|
192
|
+
`event.type` is normalised across providers; `event.originalType` keeps the provider's name and
|
|
193
|
+
`event.raw` the full envelope.
|
|
194
|
+
|
|
195
|
+
| Provider event (Bachs) | `event.type` | Paystack equivalent |
|
|
196
|
+
|---|---|---|
|
|
197
|
+
| `collection.succeeded` | `payment.succeeded` | `charge.success` |
|
|
198
|
+
| `collection.failed` | `payment.failed` | `charge.failed` |
|
|
199
|
+
| `collection.underpaid` | `payment.underpaid` | — |
|
|
200
|
+
| `refund.created` / `refund.paid` / `refund.failed` | `refund.initiated` / `refund.succeeded` / `refund.failed` | `refund.pending` / `refund.processed` / `refund.failed` |
|
|
201
|
+
| `payout.*` | `transfer.initiated` / `transfer.succeeded` / `transfer.failed` | `transfer.*` |
|
|
202
|
+
| `customer.subscription.created/updated/deleted` | `subscription.created/updated/canceled` | — |
|
|
203
|
+
| `invoice.created/paid/payment_failed` | `invoice.created` / `invoice.paid` / `invoice.payment_failed` | — |
|
|
204
|
+
| `checkout.completed` / `checkout.expired` | same names | — |
|
|
205
|
+
| `customer.*`, `dispute.*`, `conversion.*`, `payment_method.saved` | pass-through names | — |
|
|
206
|
+
|
|
207
|
+
`event.payload` is the provider's `data` object (e.g. `charge_id`, `reference`, `metadata`).
|
|
208
|
+
Anything unmapped becomes `type: "unknown"` with `originalType` preserved — never silently dropped.
|
|
209
|
+
|
|
210
|
+
### 3.3 React in-process
|
|
211
|
+
|
|
212
|
+
```ts
|
|
213
|
+
client.events.on("payment.succeeded", (event) => orderService.fulfil(event.payment.reference));
|
|
214
|
+
client.events.on("subscription.canceled", (event) => accessService.revoke(event.subscription.id));
|
|
215
|
+
```
|
|
216
|
+
|
|
217
|
+
Webhook handling emits `webhook.received`; `verify()` emits `payment.succeeded`/`payment.failed`;
|
|
218
|
+
refund and transfer calls emit their own events. Facade-driven subscription updates/cancellations
|
|
219
|
+
emit `subscription.updated`/`subscription.canceled`.
|
|
220
|
+
|
|
221
|
+
## 4. Refunds
|
|
222
|
+
|
|
223
|
+
```ts
|
|
224
|
+
const refund = await client.refunds.create({
|
|
225
|
+
paymentId: "ch_1a2b3c4d5e6f", // the charge id, not your reference
|
|
226
|
+
reason: "Customer requested cancellation",
|
|
227
|
+
reference: `refund_${order.id}`, // app-owned; unique
|
|
228
|
+
idempotencyKey: `refund_${order.id}`,
|
|
229
|
+
// amount: Money({ amount: 250000, currency: "NGN" }), // omit for a full refund
|
|
230
|
+
});
|
|
231
|
+
|
|
232
|
+
if (refund.ok && refund.value.status.kind === "pending") {
|
|
233
|
+
// Also true for Bachs "processing": async. Wait for refund.succeeded / refund.failed,
|
|
234
|
+
// or poll client.refunds.fetch(refund.value.id).
|
|
235
|
+
}
|
|
236
|
+
```
|
|
237
|
+
|
|
238
|
+
- Bachs refunds are **asynchronous** and limited to **one non-failed refund per charge**. A
|
|
239
|
+
partial refund forecloses the rest; a failed refund releases the charge again. The adapter
|
|
240
|
+
checks `is_refundable` before creating anything.
|
|
241
|
+
- A partial refund is sized in the **settlement** currency, which is not always the charge
|
|
242
|
+
currency (Bachs adaptive pricing converts some charges). Pass `Money` with the right currency:
|
|
243
|
+
the adapter validates it against the charge and returns a `ValidationError` locally instead of
|
|
244
|
+
sizing a refund in the wrong currency. `Payment.settlementAmount` carries the settlement side
|
|
245
|
+
where the provider publishes it (list items).
|
|
246
|
+
- Refunds return to the customer's original rail. `client.refunds.fetch(id)` works on both providers.
|
|
247
|
+
- Paystack refunds can sit in `needs-attention`, which means the merchant must supply the
|
|
248
|
+
customer's bank details before the money moves. The SDK reports it as `status: "pending"` with
|
|
249
|
+
`providerStatus: "needs-attention"` — do not treat it as progress or as a failure.
|
|
250
|
+
- `idempotencyKey` on a refund is honoured by Bachs (per-refund key). Paystack has no refund
|
|
251
|
+
idempotency, so serialise refund attempts per payment.
|
|
252
|
+
|
|
253
|
+
## 5. Payouts (the transfers API)
|
|
254
|
+
|
|
255
|
+
```ts
|
|
256
|
+
const recipient = await client.transfers.createRecipient({
|
|
257
|
+
name: "Treasury NGN", accountNumber: "0123456789", bankCode: "058", currency: "NGN",
|
|
258
|
+
});
|
|
259
|
+
|
|
260
|
+
const payout = await client.transfers.initiate({
|
|
261
|
+
amount: Money({ amount: 500000, currency: "NGN" }),
|
|
262
|
+
currency: "NGN", // must equal amount.currency
|
|
263
|
+
recipientCode: recipient.value.code, // pd_... on Bachs, RCP_... on Paystack
|
|
264
|
+
reference: "payout_2026_10_16_001",
|
|
265
|
+
idempotencyKey: "payout_2026_10_16_001",
|
|
266
|
+
});
|
|
267
|
+
```
|
|
268
|
+
|
|
269
|
+
- Bachs calls these **payouts**; the SDK exposes them through `client.transfers` because that is
|
|
270
|
+
the same concept as Paystack's transfers.
|
|
271
|
+
- New Bachs destinations start in `pending_review` and are not payable until approved in the
|
|
272
|
+
dashboard — `createRecipient` succeeding does not mean money can move yet. The created
|
|
273
|
+
recipient carries `status` (`"pending_review" | "approved" | "rejected"`), so wait for
|
|
274
|
+
`"approved"` instead of discovering it when a payout is rejected.
|
|
275
|
+
- Paystack requires the payout `reference` to be 16-50 characters of `[a-z0-9-_]`; the SDK
|
|
276
|
+
validates it locally and refuses the call otherwise. Kenya MPESA payouts need
|
|
277
|
+
`accountReference`.
|
|
278
|
+
- **Cross-currency payouts (Bachs):** quote first —
|
|
279
|
+
`client.transfers.createQuote({ fromCurrency, toCurrency, amount })` — then
|
|
280
|
+
`initiate({ quoteId, recipientCode, reference, currency })` with no `amount`. Passing both
|
|
281
|
+
`amount` and `quoteId`, or neither, throws `ValidationError`.
|
|
282
|
+
- A payout the provider reports as `pending` with `requiresAction: true` is waiting on **you**
|
|
283
|
+
(Paystack `otp`): finalize it in the provider dashboard.
|
|
284
|
+
- `Transfer.fee` / `totalDebited` (in `sourceCurrency`) and `amount` (destination currency) are the
|
|
285
|
+
figures to reconcile against on Bachs.
|
|
286
|
+
- Crypto destinations (`USDT_TRC20`, …) are unsupported: they are not ISO-4217 currencies and
|
|
287
|
+
fail validation deliberately.
|
|
288
|
+
- Also available: `listBankCodes(currency)`, `resolveAccount({ accountNumber, bankCode, currency })`,
|
|
289
|
+
`fetch(id)`, `list(query)`. `transfer.status.kind` ∈ pending/processing/succeeded/failed/reversed.
|
|
290
|
+
|
|
291
|
+
## 6. Products (the billing catalog)
|
|
292
|
+
|
|
293
|
+
```ts
|
|
294
|
+
const product = await client.products.create({
|
|
295
|
+
name: "Pro Plan",
|
|
296
|
+
description: "Monthly access",
|
|
297
|
+
price: { priceType: "fixed", currency: "USD", amount: Money({ amount: 2900, currency: "USD" }) },
|
|
298
|
+
billingCycle: RecurringCadence({ interval: "month", frequency: 1 }),
|
|
299
|
+
trialPeriod: RecurringCadence({ interval: "day", frequency: 14 }), // optional
|
|
300
|
+
});
|
|
301
|
+
```
|
|
302
|
+
|
|
303
|
+
- `priceType`: `"fixed"` (needs `amount`), `"free"`, `"custom"` (pay-what-you-want; optional
|
|
304
|
+
`presetAmount`, `minimumAmount`, `maximumAmount`).
|
|
305
|
+
- Local pricing: `price.currencyOptions: [{ currency: "NGN", amount: Money(...) }]`. Bachs only
|
|
306
|
+
charges an option when adaptive pricing is on.
|
|
307
|
+
- `billingCycle` is **immutable** — a different cadence is a new product. `UpdateProductInput`
|
|
308
|
+
therefore has no `billingCycle`; this is a type-level guarantee, not a runtime error.
|
|
309
|
+
- Update the price with `client.products.update(id, { amount: Money(...) })` (fixed products) or
|
|
310
|
+
`currencyOptions` (a **full replacement** — omitted currencies are removed).
|
|
311
|
+
- `archive(id)` stops selling; existing subscriptions keep billing. `unarchive(id)` restores.
|
|
312
|
+
- Pagination is cursor-based: `client.products.list({ includeArchived: true })` → pass
|
|
313
|
+
`page.nextCursor` as `cursor` until `nextCursor` is null.
|
|
314
|
+
- `isRecurring(product)` tells you whether it can back a subscription.
|
|
315
|
+
|
|
316
|
+
## 7. Subscriptions
|
|
317
|
+
|
|
318
|
+
There is **no create-subscription call** on any provider: a subscription begins when a customer
|
|
319
|
+
completes a checkout for a recurring product (section 2.2), then arrives as
|
|
320
|
+
`subscription.created` / `customer.subscription.created`.
|
|
321
|
+
|
|
322
|
+
```ts
|
|
323
|
+
const page = await client.subscriptions.list({ customerId: customer.id, status: "active" });
|
|
324
|
+
|
|
325
|
+
const sub = page.ok ? page.value.items[0] : undefined;
|
|
326
|
+
if (sub && isSubscriptionActive(sub.status)) grantAccess(sub);
|
|
327
|
+
```
|
|
328
|
+
|
|
329
|
+
Statuses: `trialing` (+`trialEnd`), `active`, `pastDue`, `unpaid`, `canceled` (+`canceledAt`),
|
|
330
|
+
`paused`. Helpers: `isSubscriptionActive`, `isSubscriptionDelinquent`, `isFinalSubscriptionStatus`.
|
|
331
|
+
An unrecognised provider status maps to `paused` — it never silently grants access.
|
|
332
|
+
|
|
333
|
+
```ts
|
|
334
|
+
// Change plan. Proration defaults to invoice_now; also next_cycle | none.
|
|
335
|
+
await client.subscriptions.update(sub.id, { productId: premiumId, prorationBehavior: "invoice_now" });
|
|
336
|
+
|
|
337
|
+
// Move or end a trial: a future date extends it; now/past ends it and bills immediately.
|
|
338
|
+
await client.subscriptions.update(sub.id, { trialEnd: new Date("2026-12-01T00:00:00Z") });
|
|
339
|
+
|
|
340
|
+
// Swap the card; on a past_due/unpaid subscription this retries immediately.
|
|
341
|
+
await client.subscriptions.update(sub.id, { paymentMethodId: "pm_new456" });
|
|
342
|
+
|
|
343
|
+
// Cancel: at the period end (access continues) or immediately (the default).
|
|
344
|
+
await client.subscriptions.cancel(sub.id, { atPeriodEnd: true, reason: "too expensive" });
|
|
345
|
+
```
|
|
346
|
+
|
|
347
|
+
- **Exactly one intent per `update()` call** — `productId`, `trialEnd`, `paymentMethodId`, or
|
|
348
|
+
`metadata`. Combining them, or passing none, throws `ValidationError` before any network call.
|
|
349
|
+
`prorationBehavior` rides along with `productId` and is not an intent by itself.
|
|
350
|
+
- A plan change must bill on the same interval and be priced in the subscription currency;
|
|
351
|
+
the provider rejects otherwise with `ProviderBadRequestError`.
|
|
352
|
+
- Failed renewals follow the provider's dunning (Bachs: retries at ~1/4/9 days, then cancel or
|
|
353
|
+
unpaid per account settings; the customer gets a hosted card-update link).
|
|
354
|
+
- `subscriptions.fetch(id)` for a single subscription; `list({ page, limit, customerId, status })`
|
|
355
|
+
pages by number on Bachs.
|
|
356
|
+
|
|
357
|
+
## 8. Customers and the portal
|
|
358
|
+
|
|
359
|
+
```ts
|
|
360
|
+
const customer = await client.customers.create({ email: user.email, name: user.name });
|
|
361
|
+
await client.customers.update(customer.value.id, { name: "Ada L" });
|
|
362
|
+
const results = await client.customers.list({ search: "ada" }); // email or name
|
|
363
|
+
const found = await client.customers.fetch(customer.value.id);
|
|
364
|
+
```
|
|
365
|
+
|
|
366
|
+
```ts
|
|
367
|
+
const session = await client.customers.createPortalSession(customerId);
|
|
368
|
+
if (session.ok) redirect(session.value.url);
|
|
369
|
+
```
|
|
370
|
+
|
|
371
|
+
- Creating a customer up front lets you pass `{ kind: "existing", providerCustomerId }` to
|
|
372
|
+
checkouts and hand the customer a portal session immediately.
|
|
373
|
+
- The portal is hosted by the provider (subscriptions, invoices, cards, profile — per your portal
|
|
374
|
+
settings) and gives you self-service and dunning recovery for free.
|
|
375
|
+
- **The portal URL is a credential**: short-lived, not logged by the SDK, and it must not be
|
|
376
|
+
cached or persisted. Mint one per request.
|
|
377
|
+
|
|
378
|
+
## 9. Errors
|
|
379
|
+
|
|
380
|
+
| Error | When | Retry? |
|
|
381
|
+
|---|---|---|
|
|
382
|
+
| `ProviderBadRequestError` (400) | provider rejected the input | no — fix the input |
|
|
383
|
+
| `ProviderUnauthorizedError` (401/403) | bad key or missing scope | no |
|
|
384
|
+
| `ProviderNotFoundError` (404) | unknown id | no |
|
|
385
|
+
| `ProviderConflictError` (409) | duplicate reference / idempotency conflict (409) | maybe — reconcile first |
|
|
386
|
+
| `ProviderRateLimitError` (429) | rate limited | yes, after `Retry-After` |
|
|
387
|
+
| `ProviderUnavailableError` (502) | provider 5xx | yes |
|
|
388
|
+
| `NetworkError` (502) / `TimeoutError` (504) | transport | yes |
|
|
389
|
+
| `VerificationError` (422) | the provider answered a verify/fetch with a rejection (unknown reference) | no |
|
|
390
|
+
| `WebhookValidationError` (401) | bad signature/body | n/a |
|
|
391
|
+
| `UnsupportedProviderError` (501) | capability missing on this provider | no — change provider |
|
|
392
|
+
| `RefundError` (422) | the provider refused the refund itself (not refundable, already refunded) | no |
|
|
393
|
+
| `InternalError` (500) | the provider cannot serve the call at all (e.g. fetch refund unsupported) | no |
|
|
394
|
+
| `ProviderError` (502) | unclassified provider failure, or a response that did not match its documented shape | reconcile before retrying |
|
|
395
|
+
| `ValidationError` / `ConfigurationError` | **thrown** programmer errors | no |
|
|
396
|
+
|
|
397
|
+
Useful fields on every error: `code` (`ErrorCode.*`), `category` (`ErrorCategory.*`), `httpStatus`,
|
|
398
|
+
`isRetryable`, `provider`, `providerCode`, `correlationId`, `meta`. Messages are safe to show users.
|
|
399
|
+
The HTTP client retries `GET`/`HEAD` (`retry.maxRetries`, default once) with a jittered delay that
|
|
400
|
+
honours a provider `Retry-After`; **mutating calls are never retried automatically**. Whether a
|
|
401
|
+
manual retry is safe depends on the provider: `supportsIdempotencyKey` is `true` for Bachs and
|
|
402
|
+
`false` for Paystack.
|
|
403
|
+
|
|
404
|
+
Treat `ProviderUnavailableError` and 5xx on an uncertain write as "unknown", not "failed":
|
|
405
|
+
reconcile (fetch by reference/id) before retrying.
|
|
406
|
+
|
|
407
|
+
## 10. Testing without network
|
|
408
|
+
|
|
409
|
+
```ts
|
|
410
|
+
import { createMockClient } from "@theengineerscanvas/payment";
|
|
411
|
+
|
|
412
|
+
const { client, http } = createMockClient({ provider: "bachs", webhookSecret: "whsec_test" });
|
|
413
|
+
http.on("POST", "/v1/checkout-sessions", {
|
|
414
|
+
status: 201,
|
|
415
|
+
body: JSON.stringify({ checkout_id: "chk_1", checkout_url: "https://checkout.bachs.io/c/x", status: "open" }),
|
|
416
|
+
});
|
|
417
|
+
|
|
418
|
+
const result = await client.payments.initialize({ ... });
|
|
419
|
+
expect(result.ok).toBe(true);
|
|
420
|
+
```
|
|
421
|
+
|
|
422
|
+
- `http.getRequests()` exposes every request for assertions (URL, method, body).
|
|
423
|
+
- `http.on()` is fluent (`http.on(a).on(b)`) and `http.reset()` clears both stubbed responses and recorded requests.
|
|
424
|
+
- **Bachs webhook payloads are not REST payloads.** The charge is under
|
|
425
|
+
`payload.charge_id` (there is no `payment_id`), `payload.status` is uppercase
|
|
426
|
+
(`"SUCCEEDED"`), and `payload.settlement_amount` can be the literal string
|
|
427
|
+
`"None"`. Read the id and status you need; do not feed webhook amounts into
|
|
428
|
+
money parsing.
|
|
429
|
+
- **Stub exact URLs for non-GET calls.** Matching tries the full method+URL first, then falls back to the **first** stub (in registration order) whose pattern is a *substring* of the request URL; the fallback ignores the method. That means a prefix stub shadows everything after it, so register the most specific stubs first and use full URLs for POST/PATCH/DELETE (a bare `/v1/products` stub would otherwise satisfy both `POST /v1/products` and `GET /v1/products/…`).
|
|
430
|
+
- A response `>= 400` becomes a `ProviderError` with that status, so error paths are testable.
|
|
431
|
+
- Webhooks: sign a body yourself with `crypto.createHmac` and call `client.webhooks.receive(...)`.
|
|
432
|
+
- The repo's own fixtures live in `tests/fixtures/bachs-*.json` and `tests/fixtures/paystack-*.json`
|
|
433
|
+
and are the reference shapes for realistic payloads.
|
|
434
|
+
|
|
435
|
+
## 11. Capability matrix and unsupported operations
|
|
436
|
+
|
|
437
|
+
| Capability | Paystack | Bachs |
|
|
438
|
+
|---|---|---|
|
|
439
|
+
| One-off checkout | yes | yes |
|
|
440
|
+
| Catalog checkout (`products`) | no (`UnsupportedProviderError`) | yes |
|
|
441
|
+
| Verify by app reference | yes | no (ids only) |
|
|
442
|
+
| Refunds (partial) | yes, multiple | yes, one non-failed per charge |
|
|
443
|
+
| Payouts / transfers | yes | yes |
|
|
444
|
+
| Products & subscriptions | no | yes |
|
|
445
|
+
| Customers & portal | no | yes |
|
|
446
|
+
| Crypto rails | n/a | not representable in `Currency` |
|
|
447
|
+
|
|
448
|
+
Calling a missing capability does **not** throw: every method resolves to
|
|
449
|
+
`UnsupportedProviderError` (`error.code === ErrorCode.UNSUPPORTED`). `isSubscriptionProvider(provider)`
|
|
450
|
+
and `client.providers.capabilities(id)` let you branch up front if you prefer.
|
|
451
|
+
|
|
452
|
+
## 12. Pitfalls checklist
|
|
453
|
+
|
|
454
|
+
- [ ] Money passed as minor units, never dollars/naira.
|
|
455
|
+
- [ ] `result.ok` checked before using `result.value`.
|
|
456
|
+
- [ ] Payment references unique per business operation; idempotency keys passed on create/refund/payout.
|
|
457
|
+
- [ ] Fulfilment driven by webhook events, not redirects.
|
|
458
|
+
- [ ] Webhook route reads the raw body and returns 2xx quickly; events deduped by `event.id`.
|
|
459
|
+
- [ ] Bachs `webhookSecret` set (`whsec_...`) — verification fails without it.
|
|
460
|
+
- [ ] `success_url`/`cancel_url` publicly reachable (no `localhost` on Bachs, sandbox included).
|
|
461
|
+
- [ ] Subscription checkout passes `products` and never reads `Payment.amount` from `initialize()`.
|
|
462
|
+
- [ ] Partial refunds are sized in the settlement currency, and `needs-attention` refunds are surfaced to an operator.
|
|
463
|
+
- [ ] Paystack payout references are 16-50 chars of `[a-z0-9-_]`.
|
|
464
|
+
- [ ] Cross-currency payouts quote first and send `quoteId` without `amount`.
|
|
465
|
+
- [ ] `subscriptions.update` sends exactly one intent.
|
|
466
|
+
- [ ] Portal URLs minted per request and never logged or cached.
|
|
467
|
+
- [ ] Bachs sandbox keys not pointed at production and vice versa.
|
|
@@ -0,0 +1,104 @@
|
|
|
1
|
+
# API Stability
|
|
2
|
+
|
|
3
|
+
Public API stability guarantees and migration timeline for `@theengineerscanvas/payment`.
|
|
4
|
+
|
|
5
|
+
## Public API Surface
|
|
6
|
+
|
|
7
|
+
The **only** stable surface is `src/public-api/index.ts`. Every export from this file is covered by the stability guarantees below:
|
|
8
|
+
|
|
9
|
+
```ts
|
|
10
|
+
export { createPaymentClient, VERSION };
|
|
11
|
+
export type { PaymentClient, PaymentClientConfig };
|
|
12
|
+
export type { Logger, EventBus, EventSubscription };
|
|
13
|
+
export type { Payment, PaymentStatus, PaymentRequest, Customer };
|
|
14
|
+
export type { Refund, RefundStatus, RefundStatusKind };
|
|
15
|
+
export type { WebhookEvent };
|
|
16
|
+
export type { Result };
|
|
17
|
+
export { ok, err, attempt };
|
|
18
|
+
export { Money, MinorUnits, Currency, PaymentReference, Provider, Metadata };
|
|
19
|
+
export { RefundReason };
|
|
20
|
+
export { PaymentError, ConfigurationError, ValidationError, ... };
|
|
21
|
+
```
|
|
22
|
+
|
|
23
|
+
## Stability Tiers
|
|
24
|
+
|
|
25
|
+
### Stable (`v1.x`)
|
|
26
|
+
|
|
27
|
+
Breaking changes require a MAJOR version bump:
|
|
28
|
+
|
|
29
|
+
- `createPaymentClient()` signature
|
|
30
|
+
- `PaymentClient` interface (all service properties and their public methods)
|
|
31
|
+
- `PaymentService.initialize()`, `.verify()`, `.fetch()`, `.list()`
|
|
32
|
+
- `RefundService.create()`, `.fetch()`
|
|
33
|
+
- `WebhookService.receive()`
|
|
34
|
+
- All error classes in `errors/`
|
|
35
|
+
- `Result<T, E>` shape and constructors
|
|
36
|
+
- All branded type factories (`Money`, `PaymentReference`, `Provider`, `Currency`, `Metadata`, `RefundReason`)
|
|
37
|
+
|
|
38
|
+
These APIs will **not** change in a way that breaks existing consumers across `v1.0.0` → `v1.x.x`.
|
|
39
|
+
|
|
40
|
+
### Evolving (`v1.x`)
|
|
41
|
+
|
|
42
|
+
New methods or optional parameters may be added in minor versions without breaking existing callers:
|
|
43
|
+
|
|
44
|
+
- New methods on service facades (e.g., `payments.fetchByReference()`)
|
|
45
|
+
- New optional fields on `PaymentClientConfig`
|
|
46
|
+
- New optional fields on input types (`PaymentRequest`, `RefundCreateInput`, `WebhookInput`, `CreateProductInput`, `UpdateSubscriptionInput`, `CreateCustomerInput`)
|
|
47
|
+
- New service facades on `PaymentClient` (`products`, `subscriptions`, `customers` were added in v0.1.0-RC11) and new optional fields on their input types
|
|
48
|
+
- New capability ports (`SubscriptionProvider` was added in v0.1.0-RC11); a provider that does not implement one keeps working, and its facade methods return `UnsupportedProviderError`
|
|
49
|
+
|
|
50
|
+
Required parameters on existing methods will **not** change in minor versions.
|
|
51
|
+
|
|
52
|
+
### Experimental
|
|
53
|
+
|
|
54
|
+
**None in v1.0.** If a feature is added as experimental in a future minor, it will be gated behind a `features` flag in config and documented as unstable.
|
|
55
|
+
|
|
56
|
+
### Internal
|
|
57
|
+
|
|
58
|
+
Everything **not** in `src/public-api/index.ts` is internal. This includes:
|
|
59
|
+
|
|
60
|
+
- `src/application/` — use cases, ports, services (except those re-exported)
|
|
61
|
+
- `src/domain/` — entities, value objects (except branded types)
|
|
62
|
+
- `src/infrastructure/` — adapters, HTTP client, event bus, loggers
|
|
63
|
+
- `src/shared/` — utilities, brand type
|
|
64
|
+
- `src/errors/` — error implementations
|
|
65
|
+
|
|
66
|
+
Internal APIs may change in any version (major, minor, or patch) without notice.
|
|
67
|
+
|
|
68
|
+
**Do not import from paths beginning with `../../domain/`, `../../infrastructure/`, or `../../application/`.**
|
|
69
|
+
|
|
70
|
+
## Backward Compatibility Policy
|
|
71
|
+
|
|
72
|
+
`v1.x → v1.y` is **non-breaking**. Code compiled against `v1.0.0` will compile and run against `v1.1.0` without changes.
|
|
73
|
+
|
|
74
|
+
`v1.x → v2.0` **may break** if the public API surface changes. Breaking changes will be documented in the changelog.
|
|
75
|
+
|
|
76
|
+
## Provider Adapter Stability
|
|
77
|
+
|
|
78
|
+
Provider adapters (`Paystack`) are internal. Adding a new provider in a minor version is **not** a breaking change — unless it requires adding a required field to `PaymentClientConfig`.
|
|
79
|
+
|
|
80
|
+
## TypeScript Version Support
|
|
81
|
+
|
|
82
|
+
The SDK targets TypeScript 5.x. Minimum supported version: TypeScript 5.0+.
|
|
83
|
+
|
|
84
|
+
Dropping support for a TypeScript major version is a **minor** bump (it does not affect runtime behavior and consumers can pin their TS version).
|
|
85
|
+
|
|
86
|
+
## Node.js Version Support
|
|
87
|
+
|
|
88
|
+
- **Current minimum:** Node 18
|
|
89
|
+
- **Planned EOL:** Node 18 EOL (April 2025)
|
|
90
|
+
- **Next minimum bump:** Node 20 (will be a MAJOR if it drops Node 18 before its official EOL)
|
|
91
|
+
- **Bun:** Supported as a runtime, not tested in CI
|
|
92
|
+
|
|
93
|
+
## Runtime Dependencies
|
|
94
|
+
|
|
95
|
+
The `dependencies` field in `package.json` will **always** be empty in v1.x. Adding a runtime dependency is a MAJOR version bump.
|
|
96
|
+
|
|
97
|
+
## v2 Migration Preview
|
|
98
|
+
|
|
99
|
+
v2 will make these breaking changes (no timeline):
|
|
100
|
+
|
|
101
|
+
1. **Provider packages split.** `@theengineerscanvas/payment-paystack` as a separate installable package. Core becomes a shell with `ProviderFactory` registration.
|
|
102
|
+
2. **Pluggable retry.** `FetchHttpClient` gains configurable backoff strategies.
|
|
103
|
+
3. **Middleware pipeline.** Interceptor pattern for request/response hooks.
|
|
104
|
+
4. **Subscription support.** New `SubscriptionsService` with recurring payment methods.
|