@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,119 @@
|
|
|
1
|
+
# Architecture
|
|
2
|
+
|
|
3
|
+
`@theengineerscanvas/payment` follows **Hexagonal Architecture** (Ports & Adapters) combined with **Domain-Driven Design** tactical patterns.
|
|
4
|
+
|
|
5
|
+
## Layers
|
|
6
|
+
|
|
7
|
+
```
|
|
8
|
+
┌────────────────────────────────────────────────────────────┐
|
|
9
|
+
│ APPLICATION CODE │
|
|
10
|
+
│ (Next.js, NestJS, Hono, Express, Worker) │
|
|
11
|
+
└────────────────────────┬───────────────────────────────────┘
|
|
12
|
+
│ imports
|
|
13
|
+
▼
|
|
14
|
+
┌────────────────────────────────────────────────────────────┐
|
|
15
|
+
│ @theengineerscanvas/payment (public API) │
|
|
16
|
+
│ createPaymentClient(config) → PaymentClient │
|
|
17
|
+
└────────────────────────┬───────────────────────────────────┘
|
|
18
|
+
│
|
|
19
|
+
┌────────────────┼─────────────────┐
|
|
20
|
+
▼ ▼ ▼
|
|
21
|
+
┌──────────────┐ ┌──────────────┐ ┌────────────────────┐
|
|
22
|
+
│ Application │ │ Domain │ │ Infrastructure │
|
|
23
|
+
│ Layer │◄┤ Layer │─►│ Layer │
|
|
24
|
+
│ │ │ (pure TS) │ │ (HTTP, providers) │
|
|
25
|
+
│ Use cases │ │ Entities │ │ Adapters, ports │
|
|
26
|
+
│ Orchestr. │ │ VOs, events │ │ impls │
|
|
27
|
+
└──────────────┘ └──────────────┘ └────────────────────┘
|
|
28
|
+
▲ ▲ ▲
|
|
29
|
+
└────────────────┴─────────────────┘
|
|
30
|
+
Dependency Inversion: domain knows no infra
|
|
31
|
+
```
|
|
32
|
+
|
|
33
|
+
### `src/domain/` — Pure TypeScript
|
|
34
|
+
|
|
35
|
+
- No I/O, no framework imports
|
|
36
|
+
- Entities: `Payment`, `Refund`, `Customer`
|
|
37
|
+
- Value objects: `Money`, `Currency`, `PaymentReference`, `Provider`, `Metadata`
|
|
38
|
+
- State machines: `PaymentStatus`, `RefundStatus` (discriminated unions)
|
|
39
|
+
- Domain events: `PaymentInitialized`, `PaymentSucceeded`, `RefundInitiated`, etc.
|
|
40
|
+
|
|
41
|
+
### `src/application/` — Use Cases & Ports
|
|
42
|
+
|
|
43
|
+
- **Ports** (interfaces): `PaymentProvider`, `HttpClient`, `Logger`, `Clock`, `IdGenerator`, `EventBus`, `WebhookVerifier`
|
|
44
|
+
- **Use cases** (pure functions): `initializePayment`, `verifyPayment`, `refundPayment`, `parseWebhook`, etc.
|
|
45
|
+
- **Services** (facades): `PaymentService`, `RefundService`, `WebhookService`
|
|
46
|
+
|
|
47
|
+
### `src/infrastructure/` — Adapters
|
|
48
|
+
|
|
49
|
+
- Paystack adapter (the only v1 provider)
|
|
50
|
+
- `FetchHttpClient` — native `fetch()` wrapper
|
|
51
|
+
- `InMemoryEventBus` — synchronous pub/sub
|
|
52
|
+
- `HmacWebhookVerifier` — HMAC-SHA512 with `timingSafeEqual`
|
|
53
|
+
- `ConsoleLogger` — JSON-line output with secret redaction
|
|
54
|
+
|
|
55
|
+
### `src/public-api/` — Firewall
|
|
56
|
+
|
|
57
|
+
The **only** layer visible to consumers. Everything else is internal and may change without notice.
|
|
58
|
+
|
|
59
|
+
## Dependency Rules
|
|
60
|
+
|
|
61
|
+
Enforced by `tests/contract/layer-boundaries.spec.ts` (a dependency-free import-graph check that fails CI on any violation, and on the NestJS peer dependency leaking outside `src/adapters/`):
|
|
62
|
+
|
|
63
|
+
> The `boundaries/dependencies` ESLint rule is configured but inert under ESLint 10 with eslint-plugin-boundaries 7.x — reproduced under ESLint 9 as well (technical debt #31). The test is the gate; do not rely on the rule until it is repaired or replaced.
|
|
64
|
+
|
|
65
|
+
| Layer | May import from |
|
|
66
|
+
|-------|----------------|
|
|
67
|
+
| `domain` | `domain`, `shared`, `errors` |
|
|
68
|
+
| `application` | `application`, `domain`, `shared`, `errors` |
|
|
69
|
+
| `infrastructure` | `infrastructure`, `application`, `domain`, `shared`, `errors` |
|
|
70
|
+
| `public-api` | Everything |
|
|
71
|
+
|
|
72
|
+
## Key Design Decisions
|
|
73
|
+
|
|
74
|
+
1. **Stateless SDK.** No database, no connection pool, no mutable state. Apps own persistence.
|
|
75
|
+
2. **Provider ignorance.** Application code never imports a provider directly. `PaymentProvider` is a port.
|
|
76
|
+
3. **Result-over-throw.** Expected failures return `Result<T, E>`. Only programmer errors throw.
|
|
77
|
+
4. **Branded primitives.** `Money`, `PaymentReference`, `Provider` are branded types validated at construction.
|
|
78
|
+
5. **Money in minor units.** Always kobo/cents. Major unit display is a UI concern.
|
|
79
|
+
6. **App-owned references.** The SDK never generates payment references. Idempotency is controllable by the app.
|
|
80
|
+
7. **Webhook raw body is mandatory.** Signature verification requires exact bytes from the HTTP request.
|
|
81
|
+
|
|
82
|
+
## Folder Structure
|
|
83
|
+
|
|
84
|
+
```
|
|
85
|
+
src/
|
|
86
|
+
├── public-api/ # Only layer visible to consumers
|
|
87
|
+
├── domain/ # Pure TS — no I/O
|
|
88
|
+
│ ├── money/ # Money, Currency
|
|
89
|
+
│ ├── payment/ # Payment, PaymentStatus, PaymentRequest
|
|
90
|
+
│ ├── refund/ # Refund, RefundStatus, RefundReason
|
|
91
|
+
│ ├── customer/ # Customer
|
|
92
|
+
│ ├── provider/ # Provider branded type
|
|
93
|
+
│ ├── reference/ # PaymentReference branded type
|
|
94
|
+
│ ├── metadata/ # Metadata branded type
|
|
95
|
+
│ ├── webhook/ # WebhookEvent
|
|
96
|
+
│ └── events/ # Domain events (9 types)
|
|
97
|
+
├── application/ # Use cases, services, ports
|
|
98
|
+
│ ├── ports/ # Interfaces (8 ports)
|
|
99
|
+
│ ├── use-cases/ # Pure functions (7 use cases)
|
|
100
|
+
│ └── services/ # Facades (5 services)
|
|
101
|
+
├── infrastructure/ # Adapter implementations
|
|
102
|
+
│ ├── providers/ # Provider adapters (Paystack)
|
|
103
|
+
│ ├── http/ # FetchHttpClient
|
|
104
|
+
│ ├── event-bus/ # InMemoryEventBus
|
|
105
|
+
│ ├── webhook/ # HmacWebhookVerifier
|
|
106
|
+
│ ├── logging/ # ConsoleLogger, NoopLogger
|
|
107
|
+
│ ├── clock/ # SystemClock
|
|
108
|
+
│ └── id/ # UlidIdGenerator
|
|
109
|
+
├── errors/ # Error hierarchy (15 classes)
|
|
110
|
+
└── shared/ # Result<T, E>, brand type
|
|
111
|
+
```
|
|
112
|
+
|
|
113
|
+
## Testing Strategy
|
|
114
|
+
|
|
115
|
+
3-tier testing pyramid:
|
|
116
|
+
|
|
117
|
+
1. **Unit tests** — Co-located with source (`*.test.ts`). Test use cases, domain objects, infrastructure components in isolation.
|
|
118
|
+
2. **Contract tests** — `tests/contract/provider-contract.spec.ts`. Every provider adapter must pass the same contract. Uses `MockHttpClient`.
|
|
119
|
+
3. **Integration tests** — `tests/integration/`. End-to-end against Paystack sandbox (gated on `PAYSTACK_SECRET_KEY`). In-process HTTP server for webhook E2E.
|
|
@@ -0,0 +1,359 @@
|
|
|
1
|
+
# Bachs Integration Guide
|
|
2
|
+
|
|
3
|
+
How to take payments with Bachs through `@theengineerscanvas/payment`. The adapter covers
|
|
4
|
+
one-time payments (hosted checkout), refunds, signed webhooks, and payouts. Subscriptions,
|
|
5
|
+
products, and customer-portal sessions arrive in v0.1.0-RC11.
|
|
6
|
+
|
|
7
|
+
## 1. Configure the client
|
|
8
|
+
|
|
9
|
+
```ts
|
|
10
|
+
import { createPaymentClient } from "@theengineerscanvas/payment";
|
|
11
|
+
|
|
12
|
+
const client = createPaymentClient({
|
|
13
|
+
providers: {
|
|
14
|
+
bachs: {
|
|
15
|
+
secretKey: process.env.BACHS_SECRET_KEY!, // sk_sandbox_... or sk_live_...
|
|
16
|
+
webhookSecret: process.env.BACHS_WEBHOOK_SECRET!, // whsec_... from the webhook endpoint
|
|
17
|
+
},
|
|
18
|
+
},
|
|
19
|
+
defaultProvider: "bachs",
|
|
20
|
+
});
|
|
21
|
+
```
|
|
22
|
+
|
|
23
|
+
`sandbox-api.bachs.io` is selected automatically when the key starts with `sk_sandbox_`;
|
|
24
|
+
everything else uses `https://api.bachs.io`. Set `baseUrl` explicitly only to override that.
|
|
25
|
+
|
|
26
|
+
`webhookSecret` is the **endpoint signing secret** (`whsec_...`), not the API key. Bachs signs
|
|
27
|
+
deliveries with it; there is deliberately no fallback, because falling back to the API key
|
|
28
|
+
would make every verification fail.
|
|
29
|
+
|
|
30
|
+
Environment variables (via `createPaymentClient.fromEnv()`):
|
|
31
|
+
|
|
32
|
+
| SDK variable | Provider-native fallback |
|
|
33
|
+
|---|---|
|
|
34
|
+
| `TEC_PAYMENT_BACHS_SECRET_KEY` | `BACHS_SECRET_KEY` |
|
|
35
|
+
| `TEC_PAYMENT_BACHS_WEBHOOK_SECRET` | `BACHS_WEBHOOK_SECRET` |
|
|
36
|
+
| `TEC_PAYMENT_BACHS_BASE_URL` | `BACHS_BASE_URL` |
|
|
37
|
+
| `TEC_PAYMENT_BACHS_TIMEOUT_MS` | — |
|
|
38
|
+
|
|
39
|
+
## 2. Money is minor units on this side of the wire
|
|
40
|
+
|
|
41
|
+
The SDK never exposes Bachs' decimal strings. `Money({ amount: 2900, currency: "USD" })` is
|
|
42
|
+
`$29.00`; the adapter converts on the way out and back with exact arithmetic (never floating
|
|
43
|
+
point). XOF/XAF are the currencies Bachs documents as zero-decimal and are handled. Amounts
|
|
44
|
+
below one major unit are fine (`{ amount: 5 }` → `"0.05"`).
|
|
45
|
+
|
|
46
|
+
Two boundaries worth knowing:
|
|
47
|
+
|
|
48
|
+
- Every other currency is converted at two decimals, including **UGX and RWF**, which ISO 4217
|
|
49
|
+
lists as zero-decimal. Bachs' schema is the contract followed here; a sandbox check would
|
|
50
|
+
settle the divergence (tracked as technical debt #21).
|
|
51
|
+
- Three-decimal currencies (`KWD`, `BHD`, `TND`, …) are **rejected with `ValidationError`**
|
|
52
|
+
rather than sent with the wrong scale, because two decimals would be ten times too little.
|
|
53
|
+
|
|
54
|
+
## 3. Take a payment
|
|
55
|
+
|
|
56
|
+
```ts
|
|
57
|
+
import { Money, PaymentReference } from "@theengineerscanvas/payment";
|
|
58
|
+
|
|
59
|
+
const result = await client.payments.initialize({
|
|
60
|
+
amount: Money({ amount: 7500000, currency: "NGN" }), // ₦75,000.00
|
|
61
|
+
reference: PaymentReference(`order_${order.id}`), // your id, unique for good
|
|
62
|
+
customer: { kind: "new", email: user.email, name: user.name },
|
|
63
|
+
callbackUrl: `${process.env.APP_URL}/checkout/success`, // must be publicly reachable
|
|
64
|
+
idempotencyKey: `checkout_${order.id}`, // safe to retry
|
|
65
|
+
});
|
|
66
|
+
|
|
67
|
+
if (!result.ok) throw result.error;
|
|
68
|
+
const { id, authorizationUrl } = result.value; // id = checkout id (chk_...)
|
|
69
|
+
redirect(authorizationUrl!);
|
|
70
|
+
```
|
|
71
|
+
|
|
72
|
+
Notes that matter:
|
|
73
|
+
|
|
74
|
+
- **`success_url`/`cancel_url` must be public.** Bachs refuses `localhost` and private
|
|
75
|
+
addresses even in the sandbox — use a tunnel while developing.
|
|
76
|
+
- **Fulfil on the webhook, not the redirect.** Bachs appends `?checkout_id=...` to the success
|
|
77
|
+
URL for display purposes only.
|
|
78
|
+
- **References are app-owned and unique per account forever** (max 128 characters). Reusing one
|
|
79
|
+
returns `409 CONFLICT`; use `idempotencyKey` for true retries.
|
|
80
|
+
|
|
81
|
+
### Verify on the return page (optional convenience)
|
|
82
|
+
|
|
83
|
+
```ts
|
|
84
|
+
const checkoutId = searchParams.get("checkout_id"); // e.g. chk_1M2N3o4P5q6R7s8T
|
|
85
|
+
const result = await client.payments.verify(PaymentReference(checkoutId));
|
|
86
|
+
```
|
|
87
|
+
|
|
88
|
+
Bachs has no lookup-by-your-reference endpoint anywhere, so Bachs `verify()` accepts a
|
|
89
|
+
**checkout id** (`chk_`) or a **payment id** (`ch_`, `pay_`, `chrg_`). Passing your own
|
|
90
|
+
reference returns a clear error instead of a confusing 404. After payment, verifying by
|
|
91
|
+
checkout id returns the underlying payment (its id is the charge id you will refund later).
|
|
92
|
+
|
|
93
|
+
## 4. Receive webhooks
|
|
94
|
+
|
|
95
|
+
```ts
|
|
96
|
+
// app/api/webhooks/bachs/route.ts
|
|
97
|
+
import { NextResponse } from "next/server";
|
|
98
|
+
|
|
99
|
+
export async function POST(request: Request) {
|
|
100
|
+
const rawBody = await request.text(); // raw bytes — never req.json() first
|
|
101
|
+
const result = await client.webhooks.receive({
|
|
102
|
+
provider: "bachs",
|
|
103
|
+
rawBody,
|
|
104
|
+
signature: request.headers.get("x-bachs-signature-v2") ?? "",
|
|
105
|
+
headers: Object.fromEntries(request.headers.entries()),
|
|
106
|
+
});
|
|
107
|
+
|
|
108
|
+
if (!result.ok) return NextResponse.json({ error: result.error.message }, { status: 401 });
|
|
109
|
+
|
|
110
|
+
const event = result.value; // type, originalType, payload, raw
|
|
111
|
+
switch (event.type) {
|
|
112
|
+
case "payment.succeeded":
|
|
113
|
+
await fulfilOrder(event.payload); // payload.charge_id, payload.reference, payload.metadata
|
|
114
|
+
break;
|
|
115
|
+
case "refund.succeeded":
|
|
116
|
+
await markRefundSettled(event.payload);
|
|
117
|
+
break;
|
|
118
|
+
}
|
|
119
|
+
|
|
120
|
+
return NextResponse.json({ received: true }); // 2xx = accepted; return 5xx to be retried
|
|
121
|
+
}
|
|
122
|
+
```
|
|
123
|
+
|
|
124
|
+
Verification details:
|
|
125
|
+
|
|
126
|
+
- HMAC-SHA256 over `"{timestamp}.{rawBody}"`; the adapter prefers `X-Bachs-Signature-V2`
|
|
127
|
+
(`t=...,v1=...`) and accepts **any** matching `v1=` so secret rotation cannot break you. The
|
|
128
|
+
legacy `X-Bachs-Signature` + `X-Bachs-Timestamp` pair is also verified.
|
|
129
|
+
- Deliveries older than 300 seconds are rejected as replays. Configure with
|
|
130
|
+
`providers.bachs.options.webhookToleranceSeconds`.
|
|
131
|
+
- Raw body is mandatory; re-serialising JSON changes the bytes and breaks verification.
|
|
132
|
+
- Bachs retries failed deliveries (5 tries over ~80 minutes) and may deliver out of order —
|
|
133
|
+
check `event.createdAt` before overwriting state, and dedupe on `event.id` (`evt_...`).
|
|
134
|
+
|
|
135
|
+
### Normalised event names
|
|
136
|
+
|
|
137
|
+
| Bachs event | SDK `event.type` |
|
|
138
|
+
|---|---|
|
|
139
|
+
| `collection.succeeded` | `payment.succeeded` |
|
|
140
|
+
| `collection.failed` | `payment.failed` |
|
|
141
|
+
| `collection.underpaid` | `payment.underpaid` |
|
|
142
|
+
| `checkout.completed` / `checkout.expired` | same name |
|
|
143
|
+
| `refund.created` / `refund.paid` / `refund.failed` | `refund.initiated` / `refund.succeeded` / `refund.failed` |
|
|
144
|
+
| `payout.created` / `payout.paid` / `payout.failed` | `transfer.initiated` / `transfer.succeeded` / `transfer.failed` |
|
|
145
|
+
| `customer.subscription.*`, `invoice.*`, `dispute.*`, `customer.*`, `conversion.*`, `payment_method.saved` | mapped or passed through by name |
|
|
146
|
+
|
|
147
|
+
Anything unrecognised stays `unknown` with `event.originalType` preserved and the full
|
|
148
|
+
envelope in `event.raw`.
|
|
149
|
+
|
|
150
|
+
## 5. Refunds
|
|
151
|
+
|
|
152
|
+
```ts
|
|
153
|
+
const refund = await client.refunds.create({
|
|
154
|
+
paymentId: "ch_1a2b3c4d5e6f", // the charge id
|
|
155
|
+
reason: "Customer requested cancellation",
|
|
156
|
+
reference: `refund_${order.id}`,
|
|
157
|
+
idempotencyKey: `refund_${order.id}`,
|
|
158
|
+
// amount: Money({ amount: 250000, currency: "NGN" }), // omit for a full refund
|
|
159
|
+
});
|
|
160
|
+
|
|
161
|
+
if (refund.ok && refund.value.status.kind === "processing") { /* wait for refund.paid */ }
|
|
162
|
+
```
|
|
163
|
+
|
|
164
|
+
- **Asynchronous.** The result starts `processing`; completion arrives as `refund.paid` /
|
|
165
|
+
`refund.failed`, or by polling `client.refunds.fetch(refundId)`.
|
|
166
|
+
- **One refund per charge.** A partial refund forecloses the rest; a *failed* refund releases
|
|
167
|
+
the charge again. The adapter checks `is_refundable` before creating anything.
|
|
168
|
+
- Refunds return to the customer's original rail.
|
|
169
|
+
- **A partial refund is sized in the settlement currency**, which is not always the charge
|
|
170
|
+
currency: under adaptive pricing a GHS charge can settle in USD. The adapter reads
|
|
171
|
+
`GET /v1/payments/charges/{charge_id}` for `settlement_currency`, validates the currency of the
|
|
172
|
+
`Money` you pass, and refuses locally when it does not match. `Payment.settlementAmount` carries
|
|
173
|
+
the settlement figure on list results.
|
|
174
|
+
- The refund request also carries `idempotency_key`, so retrying with the same key returns the
|
|
175
|
+
existing refund instead of creating a second one.
|
|
176
|
+
|
|
177
|
+
## 6. Payouts (the transfers API)
|
|
178
|
+
|
|
179
|
+
```ts
|
|
180
|
+
const recipient = await client.transfers.createRecipient({
|
|
181
|
+
name: "Treasury NGN",
|
|
182
|
+
accountNumber: "0123456789",
|
|
183
|
+
bankCode: "058",
|
|
184
|
+
currency: "NGN",
|
|
185
|
+
});
|
|
186
|
+
|
|
187
|
+
const payout = await client.transfers.initiate({
|
|
188
|
+
amount: Money({ amount: 500000, currency: "NGN" }),
|
|
189
|
+
currency: "NGN",
|
|
190
|
+
recipientCode: recipient.value.code, // pd_...
|
|
191
|
+
reference: "payout_2026_10_15_0012", // up to 128 characters
|
|
192
|
+
idempotencyKey: "payout_2026_10_15_0012",
|
|
193
|
+
});
|
|
194
|
+
|
|
195
|
+
// Cross-currency: quote first, then send quoteId instead of amount.
|
|
196
|
+
const quote = await client.transfers.createQuote({
|
|
197
|
+
fromCurrency: "USD", toCurrency: "NGN", amount: Money({ amount: 10000, currency: "USD" }),
|
|
198
|
+
});
|
|
199
|
+
if (quote.ok) {
|
|
200
|
+
await client.transfers.initiate({
|
|
201
|
+
quoteId: quote.value.id,
|
|
202
|
+
currency: "NGN",
|
|
203
|
+
recipientCode: recipient.value.code,
|
|
204
|
+
reference: "payout_2026_10_15_0013",
|
|
205
|
+
});
|
|
206
|
+
}
|
|
207
|
+
```
|
|
208
|
+
|
|
209
|
+
Bachs calls these **payouts**; the SDK exposes them through `client.transfers` because that is
|
|
210
|
+
the same concept as Paystack's transfers.
|
|
211
|
+
|
|
212
|
+
- **Cross-currency payouts need a quote.** `createQuote` locks the rate
|
|
213
|
+
(`POST /v1/payouts/quotes`); `initiate` then takes `quoteId` and no `amount`. Exactly one of
|
|
214
|
+
the two is required, and the SDK enforces it before sending anything.
|
|
215
|
+
- **Destinations come in kinds.** `createRecipient` accepts `type: "bank_account"` (default) or
|
|
216
|
+
`type: "mobile_money"` (which needs `phoneNumber`, and optionally `mobileProvider`), plus the
|
|
217
|
+
routing fields Bachs supports (`scheme`, `sortCode`, `routingNumber`, `accountName`, `bankName`).
|
|
218
|
+
Crypto wallets are not representable and fail validation deliberately.
|
|
219
|
+
- **A new destination starts in `pending_review`** and is only payable once approved in the Bachs
|
|
220
|
+
dashboard. `TransferRecipient.status` reports that state.
|
|
221
|
+
- `listBankCodes(currency, { country })` needs a country for currencies Bachs does not map
|
|
222
|
+
(`GBP`, `EUR`, `USD`, `CAD`, `XOF`, `XAF`): the endpoint falls back to the platform's own
|
|
223
|
+
country otherwise, and the SDK refuses rather than mislabelling another country's banks.
|
|
224
|
+
`resolveAccount({ accountNumber, bankCode, currency, country })` takes the same hint.
|
|
225
|
+
- `Transfer.fee` and `Transfer.totalDebited` are denominated in `sourceCurrency`, while `amount`
|
|
226
|
+
is what the destination receives — they only add up on a same-currency payout.
|
|
227
|
+
|
|
228
|
+
## 7. Subscriptions, products, and customers
|
|
229
|
+
|
|
230
|
+
### Define the catalog
|
|
231
|
+
|
|
232
|
+
```ts
|
|
233
|
+
const product = await client.products.create({
|
|
234
|
+
name: "Pro Plan",
|
|
235
|
+
description: "Monthly access to all Pro features.",
|
|
236
|
+
price: { priceType: "fixed", currency: "USD", amount: Money({ amount: 2900, currency: "USD" }) },
|
|
237
|
+
billingCycle: RecurringCadence({ interval: "month", frequency: 1 }),
|
|
238
|
+
trialPeriod: RecurringCadence({ interval: "day", frequency: 14 }), // optional free period
|
|
239
|
+
});
|
|
240
|
+
```
|
|
241
|
+
|
|
242
|
+
- `billingCycle` makes the product recurring and is **immutable**: change the cadence by creating
|
|
243
|
+
a new product, not by updating the old one.
|
|
244
|
+
- Pay-what-you-want: `priceType: "custom"` with `presetAmount`, `minimumAmount`,
|
|
245
|
+
`maximumAmount`.
|
|
246
|
+
- Local pricing: `currencyOptions: [{ currency: "NGN", amount: Money({ amount: 4500000, currency: "NGN" }) }]`.
|
|
247
|
+
Bachs only charges an option when adaptive pricing is enabled on your account.
|
|
248
|
+
- Products page by cursor — pass `page.nextCursor` back as `cursor`. Archived products stop
|
|
249
|
+
selling but keep billing existing subscriptions.
|
|
250
|
+
|
|
251
|
+
### Start the subscription with a catalog checkout
|
|
252
|
+
|
|
253
|
+
A recurring checkout needs a catalog cart; ad-hoc pricing can only sell one-off amounts. Pass
|
|
254
|
+
`products` (and a customer — Bachs requires one for a recurring checkout):
|
|
255
|
+
|
|
256
|
+
```ts
|
|
257
|
+
const checkout = await client.payments.initialize({
|
|
258
|
+
amount: Money({ amount: 2900, currency: "USD" }), // ignored on the cart path
|
|
259
|
+
reference: PaymentReference(`sub_${user.id}_${Date.now()}`),
|
|
260
|
+
customer: { kind: "existing", providerCustomerId: customerId },
|
|
261
|
+
products: [{ productId: product.value.id }],
|
|
262
|
+
callbackUrl: `${process.env.APP_URL}/billing/success`,
|
|
263
|
+
});
|
|
264
|
+
```
|
|
265
|
+
|
|
266
|
+
Completion arrives as `collection.succeeded` plus `customer.subscription.created` and
|
|
267
|
+
`invoice.paid`. Fulfil on the webhook.
|
|
268
|
+
|
|
269
|
+
### Manage subscriptions
|
|
270
|
+
|
|
271
|
+
```ts
|
|
272
|
+
import { isSubscriptionActive } from "@theengineerscanvas/payment";
|
|
273
|
+
|
|
274
|
+
const listed = await client.subscriptions.list({ customerId, status: "active" });
|
|
275
|
+
if (listed.ok) {
|
|
276
|
+
const subscription = listed.value.items[0];
|
|
277
|
+
if (subscription && isSubscriptionActive(subscription.status)) {
|
|
278
|
+
// grant access; subscription.status is trialing | active | pastDue | unpaid | canceled | paused
|
|
279
|
+
}
|
|
280
|
+
}
|
|
281
|
+
|
|
282
|
+
// Change plan. Proration defaults to invoice_now; next_cycle and none are also valid.
|
|
283
|
+
await client.subscriptions.update(subscriptionId, {
|
|
284
|
+
productId: premiumProductId,
|
|
285
|
+
prorationBehavior: "invoice_now",
|
|
286
|
+
});
|
|
287
|
+
|
|
288
|
+
// Move a trial: a future date extends it, a past or current date ends it and bills now.
|
|
289
|
+
await client.subscriptions.update(subscriptionId, { trialEnd: new Date("2026-11-01T00:00:00Z") });
|
|
290
|
+
|
|
291
|
+
// Cancel at the period end (immediate cancellation is the default when omitted).
|
|
292
|
+
await client.subscriptions.cancel(subscriptionId, { atPeriodEnd: true, reason: "too expensive" });
|
|
293
|
+
```
|
|
294
|
+
|
|
295
|
+
`update()` takes **exactly one** intent per call — `productId`, `trialEnd`, `paymentMethodId`, or
|
|
296
|
+
`metadata`. Combining them throws `ValidationError`, because Bachs rejects combined intents.
|
|
297
|
+
Successful updates and cancellations emit `subscription.updated` / `subscription.canceled` on
|
|
298
|
+
`client.events`.
|
|
299
|
+
|
|
300
|
+
There is no create-subscription call by design: subscriptions start at checkout.
|
|
301
|
+
|
|
302
|
+
### The customer portal
|
|
303
|
+
|
|
304
|
+
```ts
|
|
305
|
+
const session = await client.customers.createPortalSession(customerId);
|
|
306
|
+
if (session.ok) redirect(session.value.url);
|
|
307
|
+
```
|
|
308
|
+
|
|
309
|
+
The URL opens Bachs' hosted portal (subscriptions, invoices, cards, profile — governed by your
|
|
310
|
+
portal settings). It is a short-lived **credential**: mint one per request, never log it, never
|
|
311
|
+
cache it. A customer whose renewal failed can also update their card there.
|
|
312
|
+
|
|
313
|
+
### Billing customers
|
|
314
|
+
|
|
315
|
+
```ts
|
|
316
|
+
const customer = await client.customers.create({ email: user.email, name: user.name });
|
|
317
|
+
await client.customers.update(customer.value.id, { name: "Ada L" });
|
|
318
|
+
const found = await client.customers.list({ search: "ada" });
|
|
319
|
+
```
|
|
320
|
+
|
|
321
|
+
Creating the customer up front lets you pass `{ kind: "existing", providerCustomerId }` to
|
|
322
|
+
checkouts and hand them a portal session immediately.
|
|
323
|
+
|
|
324
|
+
## 8. Known limitations
|
|
325
|
+
|
|
326
|
+
| Limitation | Why |
|
|
327
|
+
|---|---|
|
|
328
|
+
| No lookup by your own reference | Bachs exposes no reference filter; use ids from `initialize()`/webhooks |
|
|
329
|
+
| One non-failed refund per charge | Bachs product rule |
|
|
330
|
+
| Crypto rails (`USDT_TRC20`, …) unsupported | Not ISO 4217; the SDK `Currency` type only carries 3-letter codes |
|
|
331
|
+
| Settlement currency is read from the charge-status endpoint | The single-payment endpoint does not publish it; the adapter makes one extra call per partial refund |
|
|
332
|
+
| Bank lists need a country for some currencies | `/v1/reference/banks` resolves by country (falling back to the platform's) |
|
|
333
|
+
| `success_url` must be public | Bachs refuses localhost/private addresses, sandbox included |
|
|
334
|
+
| Product cadence is immutable | Bachs rule — create a new product to change the interval |
|
|
335
|
+
| Portal session lifetime is not published | Treat it as very short: mint a fresh session per request |
|
|
336
|
+
| Paystack cannot sell catalog checkouts | Product-based checkouts return `UnsupportedProviderError` there |
|
|
337
|
+
|
|
338
|
+
## 8a. Verifying against the sandbox
|
|
339
|
+
|
|
340
|
+
`docs/bachs-sandbox-validation.md` is the runbook: probe scripts, the 32-assertion
|
|
341
|
+
integration suite, the full lifecycle (`bun run sandbox:e2e`), and the webhook
|
|
342
|
+
endpoint fields. Two provider preconditions it records are worth knowing while
|
|
343
|
+
integrating:
|
|
344
|
+
|
|
345
|
+
- A partial refund needs the charge to have a populated `settlement_amount`.
|
|
346
|
+
When adaptive pricing has not settled the conversion yet, Bachs answers
|
|
347
|
+
`INTERNAL_ERROR`; the SDK surfaces that as a typed provider error.
|
|
348
|
+
- Customer emails are checked for deliverability, so `@example.com` is refused
|
|
349
|
+
with `EMAIL_NOT_DELIVERABLE`.
|
|
350
|
+
|
|
351
|
+
## 9. Testing
|
|
352
|
+
|
|
353
|
+
- **Unit/contract:** `bun run test` — the Bachs adapter runs the shared provider contract
|
|
354
|
+
against fixtures in `tests/fixtures/bachs-*.json`.
|
|
355
|
+
- **Your app, no network:** `createMockClient()` + `MockHttpClient` from the SDK let you script
|
|
356
|
+
Bachs responses for integration tests.
|
|
357
|
+
- **Sandbox:** any card except `4000000000000002` (declined) succeeds; the sandbox checkout page
|
|
358
|
+
has controls to force bank-transfer, mobile-money, and crypto outcomes. Refund outcomes default
|
|
359
|
+
sensibly in sandbox.
|
|
@@ -0,0 +1,138 @@
|
|
|
1
|
+
# Bachs sandbox validation
|
|
2
|
+
|
|
3
|
+
How to prove the Bachs adapter against the real provider, and what the last run
|
|
4
|
+
found. This is the v1.0.0 gate from [the roadmap](roadmap/README.md), made
|
|
5
|
+
executable.
|
|
6
|
+
|
|
7
|
+
## What you need
|
|
8
|
+
|
|
9
|
+
| Thing | Where it comes from |
|
|
10
|
+
|---|---|
|
|
11
|
+
| `BACHS_SECRET_KEY` (`sk_sandbox_...`) | Bachs dashboard → Developers → API keys (sandbox) |
|
|
12
|
+
| `BACHS_WEBHOOK_SECRET` (`whsec_...`) | Created with a webhook endpoint (below). Shown **once** |
|
|
13
|
+
| A public HTTPS URL | `cloudflared tunnel --url http://localhost:8787`, `localtunnel`, or any deployed receiver |
|
|
14
|
+
|
|
15
|
+
The adapter routes `sk_sandbox_` keys to `sandbox-api.bachs.io` automatically
|
|
16
|
+
(`src/infrastructure/providers/bachs/bachs-connection.ts`), so a sandbox key can
|
|
17
|
+
never hit production.
|
|
18
|
+
|
|
19
|
+
Put the keys in `.env.local` (gitignored) so every command below picks them up:
|
|
20
|
+
|
|
21
|
+
```bash
|
|
22
|
+
BACHS_SECRET_KEY=sk_sandbox_...
|
|
23
|
+
BACHS_WEBHOOK_SECRET=whsec_...
|
|
24
|
+
```
|
|
25
|
+
|
|
26
|
+
## 1. Probe the contract
|
|
27
|
+
|
|
28
|
+
Answers the questions no published document settles. Cheap, read-mostly, and the
|
|
29
|
+
first thing to re-run after a Bachs release.
|
|
30
|
+
|
|
31
|
+
```bash
|
|
32
|
+
bun run sandbox:probe # currencies, banks, settlement, quotes, endpoint access
|
|
33
|
+
bun run sandbox:money # per-currency precision (NGN, USD, UGX, RWF, XOF, XAF, …)
|
|
34
|
+
bun run sandbox:xof # the XOF/XAF exponent question specifically
|
|
35
|
+
```
|
|
36
|
+
|
|
37
|
+
## 2. Run the integration suite
|
|
38
|
+
|
|
39
|
+
32 assertions over the real API: bank lists and account resolve, catalog CRUD,
|
|
40
|
+
one-off and catalog checkouts, verify, payment list mapping, customers and portal
|
|
41
|
+
sessions, payout destinations, quotes, subscriptions, and webhook signature
|
|
42
|
+
handling.
|
|
43
|
+
|
|
44
|
+
```bash
|
|
45
|
+
bun run test:sandbox
|
|
46
|
+
```
|
|
47
|
+
|
|
48
|
+
Refund assertions need a paid charge (Bachs has no "mark as paid" API):
|
|
49
|
+
|
|
50
|
+
```bash
|
|
51
|
+
bun run sandbox:pay # drives the hosted checkout in Chromium
|
|
52
|
+
BACHS_E2E_CHARGE_ID=ch_... bun run test:sandbox
|
|
53
|
+
```
|
|
54
|
+
|
|
55
|
+
## 3. Run the full lifecycle
|
|
56
|
+
|
|
57
|
+
`initialize → verify → pay → fetch → refund → payout destination → quote →
|
|
58
|
+
payout → webhook → cleanup` in one command, printing every step.
|
|
59
|
+
|
|
60
|
+
```bash
|
|
61
|
+
bun run sandbox:e2e
|
|
62
|
+
```
|
|
63
|
+
|
|
64
|
+
`KEEP=1` leaves the created objects in place for inspection. Otherwise products
|
|
65
|
+
are archived and destinations/endpoints deleted.
|
|
66
|
+
|
|
67
|
+
## 4. Register a webhook endpoint
|
|
68
|
+
|
|
69
|
+
The adapter needs a `whsec_...`; Bachs only shows it when the endpoint is
|
|
70
|
+
created. In the dashboard:
|
|
71
|
+
|
|
72
|
+
| Field | Value |
|
|
73
|
+
|---|---|
|
|
74
|
+
| **Endpoint URL** | `https://<your-public-host>/webhooks/bachs` |
|
|
75
|
+
| **Name** | anything, e.g. `payment-sdk-sandbox` |
|
|
76
|
+
| **Event source** | **Account events** — one merchant account. Choose *Connected account events* only if you are a Connect platform receiving events for accounts you own, and *all* for both |
|
|
77
|
+
| **Events** | at least the ones you fulfil on: `collection.succeeded`, `collection.failed`, `collection.underpaid`, `checkout.completed`, `checkout.expired`, `refund.created`, `refund.paid`, `refund.failed`, `payout.created`, `payout.paid`, `payout.failed`, plus `customer.*`, `invoice.*`, `customer.subscription.*`, `dispute.*`, `conversion.*`, `payment_method.saved` if you use them. Anything not selected is **never delivered** |
|
|
78
|
+
|
|
79
|
+
Or create it from code, which returns the secret in the response:
|
|
80
|
+
|
|
81
|
+
```ts
|
|
82
|
+
const endpoint = await fetch("https://sandbox-api.bachs.io/v1/webhooks/endpoints", {
|
|
83
|
+
method: "POST",
|
|
84
|
+
headers: { Authorization: `Bearer ${process.env.BACHS_SECRET_KEY}`, "Content-Type": "application/json" },
|
|
85
|
+
body: JSON.stringify({
|
|
86
|
+
name: "payment-sdk-sandbox",
|
|
87
|
+
url: "https://<your-public-host>/webhooks/bachs",
|
|
88
|
+
event_types: ["collection.succeeded", "collection.failed", "refund.paid", "payout.paid"],
|
|
89
|
+
event_source: "account",
|
|
90
|
+
}),
|
|
91
|
+
});
|
|
92
|
+
// endpoint.signing_secret → BACHS_WEBHOOK_SECRET
|
|
93
|
+
```
|
|
94
|
+
|
|
95
|
+
Then run the receiver, which verifies with the SDK and records every delivery:
|
|
96
|
+
|
|
97
|
+
```bash
|
|
98
|
+
BACHS_WEBHOOK_SECRET=whsec_... bun run scripts/webhook-receiver.ts
|
|
99
|
+
cloudflared tunnel --url http://localhost:8787
|
|
100
|
+
```
|
|
101
|
+
|
|
102
|
+
## What the last run proved (2026-10-19)
|
|
103
|
+
|
|
104
|
+
Sandbox account: NG platform, **USD balance**, adaptive pricing on.
|
|
105
|
+
|
|
106
|
+
| Finding | Evidence |
|
|
107
|
+
|---|---|
|
|
108
|
+
| **XOF and XAF are two-decimal at Bachs**, not zero-decimal as ISO 4217 says | Sending `"1234.56"` to XOF/XAF/USD is echoed back unchanged; `"1000"` returns `"1000.00"`. The SDK's zero-decimal set was wrong and sent those amounts at 1/100 — fixed in RC15 |
|
|
109
|
+
| **UGX/RWF are two-decimal too** | Same probe; matches the SDK |
|
|
110
|
+
| **A settlement currency can differ from the charge currency** | A USD 20.00 checkout was charged as NGN 28,984.85 with `settlement_currency: "USD"`, `settlement_amount: "20.00"` |
|
|
111
|
+
| **Partial refunds are sized in the settlement currency** | `amount: "5.00"` against that charge succeeded as USD 5.00. The SDK now refuses a refund in any other currency before sending |
|
|
112
|
+
| **Refunds need a populated `settlement_amount`** | Charges where it was `null` returned `INTERNAL_ERROR` from Bachs; the charge with `"20.00"` refunded fine. A provider-side precondition the SDK cannot detect locally |
|
|
113
|
+
| **`GET /v1/payments/charges/{id}` accepts only charge ids** | A `chk_` id returns `404 Charge not found`; `ch_` works. The adapter skips the lookup for a checkout id and falls back to the charge currency |
|
|
114
|
+
| **Creating a payout destination can auto-approve** | The sandbox returned `status: "approved", is_usable: true` immediately; production starts at `pending_review`. `TransferRecipient.status` reports whatever the provider says |
|
|
115
|
+
| **Webhook signatures are `HMAC-SHA256("{timestamp}.{body}")` in seconds** | Recomputed the real delivery's `x-bachs-signature` byte-for-byte. `x-bachs-signature-v2: t=…,v1=…` is also sent, plus legacy `x-syncpay-*` aliases |
|
|
116
|
+
| **Webhook payloads are not the REST payloads** | `data.status` is uppercase (`"SUCCEEDED"`), the charge is under `data.charge_id` (not `payment_id`), and `settlement_amount` can be the literal string `"None"`. The webhook layer passes the payload through verbatim, so read `charge_id` and do not money-parse `settlement_amount` |
|
|
117
|
+
| **Bachs validates customer email deliverability** | `@example.com` is rejected with `EMAIL_NOT_DELIVERABLE`; use a domain with MX records |
|
|
118
|
+
| **Payout quotes work as documented** | `createQuote` returned `pqt_…`, `from_amount: "10.00"`, `to_amount: "13492.66"` at 1349.27 NGN/USD, and `initiate({ quoteId })` created a real payout |
|
|
119
|
+
|
|
120
|
+
## Cleanup
|
|
121
|
+
|
|
122
|
+
Objects created by the probes and suite are prefixed `sdk-probe`, `sdk-e2e`, and
|
|
123
|
+
`sdk-it`. `sandbox:e2e` cleans up after itself unless `KEEP=1`; the probe scripts
|
|
124
|
+
leave products and destinations for inspection. Remove leftovers with the API:
|
|
125
|
+
|
|
126
|
+
```bash
|
|
127
|
+
curl -X DELETE "https://sandbox-api.bachs.io/v1/payouts/destinations/<pd_...>" \
|
|
128
|
+
-H "Authorization: Bearer $BACHS_SECRET_KEY"
|
|
129
|
+
curl -X DELETE "https://sandbox-api.bachs.io/v1/webhooks/endpoints/<whe_...>" \
|
|
130
|
+
-H "Authorization: Bearer $BACHS_SECRET_KEY"
|
|
131
|
+
```
|
|
132
|
+
|
|
133
|
+
## Rotating the endpoint secret
|
|
134
|
+
|
|
135
|
+
`POST /v1/webhooks/endpoints/{id}/rotate-secret` returns a new secret and keeps
|
|
136
|
+
both valid during the overlap, so deliveries carry several `v1=` values. The
|
|
137
|
+
adapter accepts any match — covered by the rotation test in
|
|
138
|
+
`src/infrastructure/providers/bachs/bachs-webhook.test.ts`.
|