@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,1108 @@
|
|
|
1
|
+
# Public API
|
|
2
|
+
|
|
3
|
+
Complete public API reference for `@theengineerscanvas/payment`.
|
|
4
|
+
|
|
5
|
+
## createPaymentClient(config)
|
|
6
|
+
|
|
7
|
+
Factory function. Returns a `PaymentClient`.
|
|
8
|
+
|
|
9
|
+
```ts
|
|
10
|
+
import { createPaymentClient } from "@theengineerscanvas/payment";
|
|
11
|
+
|
|
12
|
+
const client = createPaymentClient({
|
|
13
|
+
providers: {
|
|
14
|
+
paystack: { secretKey: process.env.PAYSTACK_SECRET_KEY! },
|
|
15
|
+
},
|
|
16
|
+
defaultProvider: "paystack",
|
|
17
|
+
});
|
|
18
|
+
```
|
|
19
|
+
|
|
20
|
+
### PaymentClientConfig
|
|
21
|
+
|
|
22
|
+
| Field | Type | Required | Description |
|
|
23
|
+
|-------|------|----------|-------------|
|
|
24
|
+
| `providers` | `Record<Provider, ProviderConfig>` | Yes | Provider configurations keyed by provider name |
|
|
25
|
+
| `defaultProvider` | `Provider` | No | Default provider for operations. First configured provider if omitted |
|
|
26
|
+
| `logging` | `{ level: "debug" \| "info" \| "warn" \| "error" }` | No | Enables console logging at the given level |
|
|
27
|
+
| `http` | `HttpClientConfig` | No | Client-wide defaults: `timeoutMs` and `baseUrl` (a provider's own value wins) |
|
|
28
|
+
| `retry` | `RetryConfig` | No | `maxRetries` (default 1, idempotent requests only) and `delayMs` (base retry delay, default 500 ms plus jitter). Invalid values throw `ConfigurationError` |
|
|
29
|
+
| `eventBus` | `EventBus` | No | Custom event bus implementation |
|
|
30
|
+
| `clock` | `Clock` | No | Custom clock (for testing) |
|
|
31
|
+
| `idGenerator` | `IdGenerator` | No | Custom ID generator (for testing) |
|
|
32
|
+
| `logger` | `Logger` | No | Custom logger implementation |
|
|
33
|
+
| `httpClient` | `HttpClient` | No | Custom HTTP client implementation |
|
|
34
|
+
|
|
35
|
+
### ProviderConfig
|
|
36
|
+
|
|
37
|
+
| Field | Type | Required | Description |
|
|
38
|
+
|-------|------|----------|-------------|
|
|
39
|
+
| `secretKey` | `string` | Yes | Provider secret/API key |
|
|
40
|
+
| `publicKey` | `string` | No | Provider public key (if needed) |
|
|
41
|
+
| `webhookSecret` | `string` | No | Webhook signing secret. Defaults to `secretKey` |
|
|
42
|
+
| `baseUrl` | `string` | No | Override base URL (e.g., sandbox). Must be `https://` unless the next field opts in |
|
|
43
|
+
| `allowInsecureBaseUrl` | `boolean` | No | Allow an `http://` base URL for local stubs and test harnesses. Off by default: an insecure URL throws `ConfigurationError` at construction |
|
|
44
|
+
| `timeoutMs` | `number` | No | Request timeout in ms (default: 30000, or `http.timeoutMs`) |
|
|
45
|
+
| `enabled` | `boolean` | No | Enable/disable provider (default: true) |
|
|
46
|
+
|
|
47
|
+
### fromEnv()
|
|
48
|
+
|
|
49
|
+
Environment variable convenience:
|
|
50
|
+
|
|
51
|
+
```ts
|
|
52
|
+
const client = createPaymentClient.fromEnv();
|
|
53
|
+
|
|
54
|
+
// Checks in order:
|
|
55
|
+
// 1. TEC_PAYMENT_* namespace (explicit)
|
|
56
|
+
// 2. Provider-native variables (e.g., PAYSTACK_SECRET_KEY)
|
|
57
|
+
|
|
58
|
+
// Reads from:
|
|
59
|
+
// TEC_PAYMENT_DEFAULT_PROVIDER=paystack (or PAYSTACK_* for provider config)
|
|
60
|
+
// TEC_PAYMENT_PAYSTACK_SECRET_KEY=sk_... (or PAYSTACK_SECRET_KEY)
|
|
61
|
+
// TEC_PAYMENT_PAYSTACK_WEBHOOK_SECRET=... (or PAYSTACK_WEBHOOK_SECRET)
|
|
62
|
+
// TEC_PAYMENT_PAYSTACK_BASE_URL=... (or PAYSTACK_BASE_URL)
|
|
63
|
+
// TEC_PAYMENT_BACHS_SECRET_KEY=sk_sandbox_... (or BACHS_SECRET_KEY)
|
|
64
|
+
// TEC_PAYMENT_BACHS_WEBHOOK_SECRET=whsec_... (or BACHS_WEBHOOK_SECRET)
|
|
65
|
+
// TEC_PAYMENT_BACHS_BASE_URL=... (or BACHS_BASE_URL)
|
|
66
|
+
// TEC_PAYMENT_BACHS_TIMEOUT_MS=30000
|
|
67
|
+
// TEC_PAYMENT_LOGGING_LEVEL=debug|info|warn|error
|
|
68
|
+
```
|
|
69
|
+
|
|
70
|
+
## PaymentClient
|
|
71
|
+
|
|
72
|
+
| Property | Type | Description |
|
|
73
|
+
|----------|------|-------------|
|
|
74
|
+
| `payments` | `PaymentService` | Initialize, verify, fetch, list payments |
|
|
75
|
+
| `refunds` | `RefundService` | Create and fetch refunds |
|
|
76
|
+
| `transfers` | `TransferService` | List bank codes, resolve accounts, create recipients, quote cross-currency payouts, initiate/fetch/list transfers |
|
|
77
|
+
| `products` | `ProductService` | Catalog: create, read, update, archive products |
|
|
78
|
+
| `subscriptions` | `SubscriptionService` | List, inspect, change, and cancel subscriptions |
|
|
79
|
+
| `customers` | `CustomerService` | Billing customers and hosted portal sessions |
|
|
80
|
+
| `webhooks` | `WebhookService` | Receive and verify webhooks |
|
|
81
|
+
| `events` | `EventSubscription` | Subscribe to domain events |
|
|
82
|
+
| `providers` | `ProviderRegistry` | Introspect configured providers |
|
|
83
|
+
| `health()` | `Promise<HealthStatus[]>` | Health check all providers |
|
|
84
|
+
|
|
85
|
+
`products`, `subscriptions`, and `customers` require a provider that implements the
|
|
86
|
+
subscription capability (Bachs). On any other provider each call resolves to an
|
|
87
|
+
`UnsupportedProviderError` (`code: "UNSUPPORTED"`, `category: "unsupported"`) rather than
|
|
88
|
+
throwing, so capability checks are not required. Use `isSubscriptionProvider()` when
|
|
89
|
+
building your own provider-aware logic.
|
|
90
|
+
|
|
91
|
+
## ProductService
|
|
92
|
+
|
|
93
|
+
```ts
|
|
94
|
+
interface ProductService {
|
|
95
|
+
list(query?: ProductListQuery): Promise<Result<Page<Product>, PaymentError>>;
|
|
96
|
+
fetch(id: string): Promise<Result<Product, PaymentError>>;
|
|
97
|
+
create(input: CreateProductInput): Promise<Result<Product, PaymentError>>;
|
|
98
|
+
update(id: string, input: UpdateProductInput): Promise<Result<Product, PaymentError>>;
|
|
99
|
+
archive(id: string): Promise<Result<Product, PaymentError>>;
|
|
100
|
+
unarchive(id: string): Promise<Result<Product, PaymentError>>;
|
|
101
|
+
}
|
|
102
|
+
```
|
|
103
|
+
|
|
104
|
+
`CreateProductInput.billingCycle` makes a product recurring and is **immutable** afterwards
|
|
105
|
+
(Bachs rejects a changed cadence) — create a new product to change how often it bills.
|
|
106
|
+
`UpdateProductInput` therefore has no `billingCycle`. Products page by cursor: pass
|
|
107
|
+
`Page.nextCursor` as `query.cursor`. Archived products stop selling but keep billing
|
|
108
|
+
existing subscriptions.
|
|
109
|
+
|
|
110
|
+
## SubscriptionService
|
|
111
|
+
|
|
112
|
+
```ts
|
|
113
|
+
interface SubscriptionService {
|
|
114
|
+
list(query?: SubscriptionListQuery): Promise<Result<Page<Subscription>, PaymentError>>;
|
|
115
|
+
fetch(id: string): Promise<Result<Subscription, PaymentError>>;
|
|
116
|
+
update(id: string, input: UpdateSubscriptionInput): Promise<Result<Subscription, PaymentError>>;
|
|
117
|
+
cancel(id: string, input?: CancelSubscriptionInput): Promise<Result<Subscription, PaymentError>>;
|
|
118
|
+
}
|
|
119
|
+
```
|
|
120
|
+
|
|
121
|
+
There is no create call: a subscription begins when a customer completes a checkout for a
|
|
122
|
+
recurring product, and completion arrives as `subscription.created`. `update()` accepts
|
|
123
|
+
**exactly one** intent per call (`productId`, `trialEnd`, `paymentMethodId`, or `metadata`);
|
|
124
|
+
combining them throws `ValidationError` because the provider rejects combined intents.
|
|
125
|
+
`prorationBehavior` (`invoice_now` — the default — `next_cycle`, or `none`) accompanies a plan
|
|
126
|
+
change. `cancel({ atPeriodEnd: true })` keeps access until the period ends; the default is
|
|
127
|
+
immediate. Successful `update`/`cancel` calls emit `subscription.updated` /
|
|
128
|
+
`subscription.canceled` on the event bus.
|
|
129
|
+
|
|
130
|
+
## CustomerService
|
|
131
|
+
|
|
132
|
+
```ts
|
|
133
|
+
interface CustomerService {
|
|
134
|
+
list(query?: CustomerListQuery): Promise<Result<Page<Customer>, PaymentError>>;
|
|
135
|
+
fetch(id: string): Promise<Result<Customer, PaymentError>>;
|
|
136
|
+
create(input: CreateCustomerInput): Promise<Result<Customer, PaymentError>>;
|
|
137
|
+
update(id: string, input: UpdateCustomerInput): Promise<Result<Customer, PaymentError>>;
|
|
138
|
+
createPortalSession(customerId: string): Promise<Result<PortalSession, PaymentError>>;
|
|
139
|
+
}
|
|
140
|
+
```
|
|
141
|
+
|
|
142
|
+
`createPortalSession()` returns a short-lived, pre-authenticated URL for the provider's hosted
|
|
143
|
+
customer portal (subscriptions, invoices, cards, profile). The URL is a **credential**: mint one
|
|
144
|
+
per request, never log it, never cache it.
|
|
145
|
+
|
|
146
|
+
## PaymentService
|
|
147
|
+
|
|
148
|
+
```ts
|
|
149
|
+
interface PaymentService {
|
|
150
|
+
initialize(req: PaymentRequest): Promise<Result<Payment, PaymentError>>;
|
|
151
|
+
verify(ref: PaymentReference): Promise<Result<Payment, PaymentError>>;
|
|
152
|
+
fetch(id: string): Promise<Result<Payment, PaymentError>>;
|
|
153
|
+
list(query: ListQuery): Promise<Result<Page<Payment>, PaymentError>>;
|
|
154
|
+
}
|
|
155
|
+
```
|
|
156
|
+
|
|
157
|
+
### initialize(req)
|
|
158
|
+
|
|
159
|
+
```ts
|
|
160
|
+
const result = await client.payments.initialize({
|
|
161
|
+
amount: Money({ amount: 500000, currency: "NGN" }),
|
|
162
|
+
reference: PaymentReference("order-9001"),
|
|
163
|
+
customer: { kind: "new", email: "customer@example.com" },
|
|
164
|
+
callbackUrl: "https://myapp.com/verify",
|
|
165
|
+
});
|
|
166
|
+
```
|
|
167
|
+
|
|
168
|
+
Returns `Payment` with `authorizationUrl` for redirect-based flows.
|
|
169
|
+
|
|
170
|
+
### verify(reference)
|
|
171
|
+
|
|
172
|
+
```ts
|
|
173
|
+
const result = await client.payments.verify(PaymentReference("order-9001"));
|
|
174
|
+
```
|
|
175
|
+
|
|
176
|
+
Queries the provider API directly. Never trusts redirect query params.
|
|
177
|
+
|
|
178
|
+
- **Paystack** looks the reference up; `result.value.reference` is the reference
|
|
179
|
+
you supplied.
|
|
180
|
+
- **Bachs cannot look up by your reference.** Pass the provider id: a checkout id
|
|
181
|
+
(`chk_`) reads the checkout session, a payment id (`ch_`/`chrg_`/`pay_`) reads
|
|
182
|
+
the payment. Any other value returns `ProviderBadRequestError` with guidance.
|
|
183
|
+
Once payment has been attempted, Bachs embeds the charge in the session, and
|
|
184
|
+
`result.value.id` is therefore the **charge id** (what refunds and webhooks
|
|
185
|
+
use), not the checkout id you passed. Keep both.
|
|
186
|
+
|
|
187
|
+
### fetch(id)
|
|
188
|
+
|
|
189
|
+
```ts
|
|
190
|
+
const result = await client.payments.fetch("3811142484");
|
|
191
|
+
```
|
|
192
|
+
|
|
193
|
+
Looks up a payment by its provider-assigned ID.
|
|
194
|
+
|
|
195
|
+
### list(query)
|
|
196
|
+
|
|
197
|
+
```ts
|
|
198
|
+
const result = await client.payments.list({
|
|
199
|
+
page: 1,
|
|
200
|
+
perPage: 50,
|
|
201
|
+
from: new Date("2026-01-01"),
|
|
202
|
+
to: new Date("2026-01-31"),
|
|
203
|
+
});
|
|
204
|
+
```
|
|
205
|
+
|
|
206
|
+
Returns `Page<Payment>` with `{ items, total, page, perPage }`.
|
|
207
|
+
|
|
208
|
+
## RefundService
|
|
209
|
+
|
|
210
|
+
```ts
|
|
211
|
+
interface RefundService {
|
|
212
|
+
create(input: RefundCreateInput): Promise<Result<Refund, PaymentError>>;
|
|
213
|
+
fetch(id: string): Promise<Result<Refund, PaymentError>>;
|
|
214
|
+
}
|
|
215
|
+
```
|
|
216
|
+
|
|
217
|
+
### create(input)
|
|
218
|
+
|
|
219
|
+
```ts
|
|
220
|
+
// Full refund
|
|
221
|
+
const result = await client.refunds.create({
|
|
222
|
+
paymentId: "3811142484",
|
|
223
|
+
reason: "Customer requested refund",
|
|
224
|
+
});
|
|
225
|
+
|
|
226
|
+
// Partial refund
|
|
227
|
+
const result = await client.refunds.create({
|
|
228
|
+
paymentId: "3811142484",
|
|
229
|
+
amount: Money({ amount: 100000, currency: "NGN" }),
|
|
230
|
+
reason: "Partial refund",
|
|
231
|
+
});
|
|
232
|
+
```
|
|
233
|
+
|
|
234
|
+
### fetch(id)
|
|
235
|
+
|
|
236
|
+
```ts
|
|
237
|
+
const result = await client.refunds.fetch("ref-500");
|
|
238
|
+
```
|
|
239
|
+
|
|
240
|
+
Returns the current `Refund` status. Requires provider support.
|
|
241
|
+
|
|
242
|
+
## TransferService
|
|
243
|
+
|
|
244
|
+
```ts
|
|
245
|
+
interface TransferService {
|
|
246
|
+
listBankCodes(currency: Currency, options?: { country?: string }): Promise<Result<ReadonlyArray<BankCode>, PaymentError>>;
|
|
247
|
+
resolveAccount(input: { accountNumber: string; bankCode: string; currency: Currency; country?: string }): Promise<Result<ResolveAccountResult, PaymentError>>;
|
|
248
|
+
createRecipient(input: CreateRecipientInput): Promise<Result<TransferRecipient, PaymentError>>;
|
|
249
|
+
createQuote(input: TransferQuoteInput): Promise<Result<TransferQuote, PaymentError>>;
|
|
250
|
+
initiate(input: InitiateTransferInput): Promise<Result<Transfer, PaymentError>>;
|
|
251
|
+
fetch(id: string): Promise<Result<Transfer, PaymentError>>;
|
|
252
|
+
list(query: ListQuery): Promise<Result<Page<Transfer>, PaymentError>>;
|
|
253
|
+
}
|
|
254
|
+
```
|
|
255
|
+
|
|
256
|
+
### listBankCodes(currency, options?)
|
|
257
|
+
|
|
258
|
+
```ts
|
|
259
|
+
const result = await client.transfers.listBankCodes(Currency("NGN"));
|
|
260
|
+
// returns BankCode[]: [{ code: "044", name: "Access Bank", currency: "NGN" }, ...]
|
|
261
|
+
|
|
262
|
+
// Bachs resolves banks by country and falls back to the platform's own country,
|
|
263
|
+
// so a currency it does not map needs an explicit one:
|
|
264
|
+
const gb = await client.transfers.listBankCodes(Currency("GBP"), { country: "GB" });
|
|
265
|
+
```
|
|
266
|
+
|
|
267
|
+
Requires `ProviderCapabilities.supportsTransfers` to be true and the currency to be in `supportedTransferCurrencies`. Paystack pages the full bank list (cursor) and drops deactivated institutions; Bachs fails locally with `ValidationError` when neither the currency nor `country` identifies one, rather than mislabelling another country's banks.
|
|
268
|
+
|
|
269
|
+
### resolveAccount(input)
|
|
270
|
+
|
|
271
|
+
```ts
|
|
272
|
+
const result = await client.transfers.resolveAccount({
|
|
273
|
+
accountNumber: "0123456789",
|
|
274
|
+
bankCode: "044",
|
|
275
|
+
currency: Currency("NGN"),
|
|
276
|
+
});
|
|
277
|
+
// returns { accountName: "JOHN DOE" }
|
|
278
|
+
```
|
|
279
|
+
|
|
280
|
+
### createRecipient(input)
|
|
281
|
+
|
|
282
|
+
```ts
|
|
283
|
+
const result = await client.transfers.createRecipient({
|
|
284
|
+
name: "John Doe",
|
|
285
|
+
accountNumber: "0123456789",
|
|
286
|
+
bankCode: "044",
|
|
287
|
+
currency: Currency("NGN"),
|
|
288
|
+
});
|
|
289
|
+
// returns TransferRecipient with recipient.code
|
|
290
|
+
```
|
|
291
|
+
|
|
292
|
+
### initiate(input)
|
|
293
|
+
|
|
294
|
+
```ts
|
|
295
|
+
const result = await client.transfers.initiate({
|
|
296
|
+
amount: Money({ amount: 1000000, currency: "NGN" }),
|
|
297
|
+
recipientCode: "RCP_abc123",
|
|
298
|
+
reference: "payout_2026_10_17_0012", // Paystack: 16-50 chars of [a-z0-9-_]
|
|
299
|
+
reason: "Monthly payout",
|
|
300
|
+
currency: Currency("NGN"),
|
|
301
|
+
});
|
|
302
|
+
// returns Transfer with status
|
|
303
|
+
|
|
304
|
+
// Cross-currency payout (Bachs): quote first, then send quoteId and no amount.
|
|
305
|
+
const quote = await client.transfers.createQuote({
|
|
306
|
+
fromCurrency: Currency("USD"),
|
|
307
|
+
toCurrency: Currency("NGN"),
|
|
308
|
+
amount: Money({ amount: 10000, currency: "USD" }),
|
|
309
|
+
});
|
|
310
|
+
if (quote.ok) {
|
|
311
|
+
await client.transfers.initiate({
|
|
312
|
+
quoteId: quote.value.id,
|
|
313
|
+
recipientCode: "pd_7Kq2mNv4XbR9dLc0",
|
|
314
|
+
reference: "payout_2026_10_17_0013",
|
|
315
|
+
currency: Currency("NGN"),
|
|
316
|
+
});
|
|
317
|
+
}
|
|
318
|
+
```
|
|
319
|
+
|
|
320
|
+
Emits `transfer.initiated` (pending/processing) or `transfer.failed` events. Accepts `correlationId` and `idempotencyKey`. The returned `Transfer` carries the recipient when the provider payload or a destination lookup can resolve it, plus `fee`/`totalDebited`/`sourceCurrency` when the provider reports them.
|
|
321
|
+
|
|
322
|
+
### fetch(id)
|
|
323
|
+
|
|
324
|
+
```ts
|
|
325
|
+
const result = await client.transfers.fetch("500");
|
|
326
|
+
// returns Transfer
|
|
327
|
+
```
|
|
328
|
+
|
|
329
|
+
### list(query)
|
|
330
|
+
|
|
331
|
+
```ts
|
|
332
|
+
const result = await client.transfers.list({ page: 1, perPage: 50 });
|
|
333
|
+
// returns Page<Transfer>
|
|
334
|
+
```
|
|
335
|
+
|
|
336
|
+
## WebhookService
|
|
337
|
+
|
|
338
|
+
```ts
|
|
339
|
+
interface WebhookService {
|
|
340
|
+
receive(input: WebhookInput): Promise<Result<WebhookEvent, WebhookValidationError>>;
|
|
341
|
+
}
|
|
342
|
+
```
|
|
343
|
+
|
|
344
|
+
### receive(input)
|
|
345
|
+
|
|
346
|
+
```ts
|
|
347
|
+
const result = await client.webhooks.receive({
|
|
348
|
+
rawBody: req.body, // Uint8Array | string — must be exact bytes (Buffer works)
|
|
349
|
+
signature: req.headers["x-paystack-signature"],
|
|
350
|
+
provider: "paystack", // optional — auto-detected if omitted
|
|
351
|
+
});
|
|
352
|
+
```
|
|
353
|
+
|
|
354
|
+
The `rawBody` must be the exact bytes the provider POSTed. See `docs/security.md` for the raw body contract.
|
|
355
|
+
|
|
356
|
+
## EventSubscription
|
|
357
|
+
|
|
358
|
+
```ts
|
|
359
|
+
type Unsubscribe = () => void;
|
|
360
|
+
|
|
361
|
+
interface EventSubscription {
|
|
362
|
+
on<T extends PaymentEventType>(type: T, handler: EventHandler<T>): Unsubscribe;
|
|
363
|
+
onAny(handler: EventHandler): Unsubscribe;
|
|
364
|
+
}
|
|
365
|
+
```
|
|
366
|
+
|
|
367
|
+
### Events
|
|
368
|
+
|
|
369
|
+
| Event | Payload |
|
|
370
|
+
|-------|---------|
|
|
371
|
+
| `payment.initialized` | `{ type, payment, occurredAt, correlationId }` |
|
|
372
|
+
| `payment.pending` | `{ type, payment, occurredAt, correlationId }` |
|
|
373
|
+
| `payment.succeeded` | `{ type, payment, occurredAt, correlationId }` |
|
|
374
|
+
| `payment.failed` | `{ type, payment, occurredAt, correlationId }` |
|
|
375
|
+
| `verification.completed` | `{ type, payment, occurredAt, correlationId }` |
|
|
376
|
+
| `webhook.received` | `{ type, provider, eventId, eventType, originalType, payload, occurredAt, correlationId }` |
|
|
377
|
+
| `refund.initiated` | `{ type, refund, occurredAt, correlationId }` |
|
|
378
|
+
| `refund.succeeded` | `{ type, refund, occurredAt, correlationId }` |
|
|
379
|
+
| `refund.failed` | `{ type, refund, reason, occurredAt, correlationId }` |
|
|
380
|
+
| `transfer.initiated` | `{ type, transfer, occurredAt, correlationId }` |
|
|
381
|
+
| `transfer.succeeded` | `{ type, transfer, occurredAt, correlationId }` |
|
|
382
|
+
| `transfer.failed` | `{ type, transfer, reason, occurredAt, correlationId }` |
|
|
383
|
+
| `transfer.reversed` | `{ type, transfer, occurredAt, correlationId }` |
|
|
384
|
+
|
|
385
|
+
```ts
|
|
386
|
+
client.events.on("payment.succeeded", (event) => {
|
|
387
|
+
console.log(`Payment ${event.payment.reference} succeeded`);
|
|
388
|
+
});
|
|
389
|
+
|
|
390
|
+
client.events.on("payment.failed", (event) => {
|
|
391
|
+
console.log(`Payment ${event.payment.reference} failed`);
|
|
392
|
+
});
|
|
393
|
+
```
|
|
394
|
+
|
|
395
|
+
## Types
|
|
396
|
+
|
|
397
|
+
### Payment
|
|
398
|
+
|
|
399
|
+
```ts
|
|
400
|
+
interface Payment {
|
|
401
|
+
readonly id?: string;
|
|
402
|
+
readonly providerId: Provider;
|
|
403
|
+
readonly reference: PaymentReference;
|
|
404
|
+
/** Absent while a catalog checkout is still open: the provider prices the cart. */
|
|
405
|
+
readonly amount?: Money;
|
|
406
|
+
readonly fees?: Money;
|
|
407
|
+
readonly netAmount?: Money;
|
|
408
|
+
/** The settlement side of the payment, where the provider publishes it (Bachs). */
|
|
409
|
+
readonly settlementAmount?: Money;
|
|
410
|
+
readonly status: PaymentStatus;
|
|
411
|
+
readonly customer: Customer;
|
|
412
|
+
readonly authorizationUrl?: string;
|
|
413
|
+
readonly accessCode?: string;
|
|
414
|
+
readonly channel?: PaymentChannel;
|
|
415
|
+
readonly attempts: ReadonlyArray<PaymentAttempt>;
|
|
416
|
+
readonly metadata: Metadata;
|
|
417
|
+
readonly createdAt: Date;
|
|
418
|
+
readonly updatedAt: Date;
|
|
419
|
+
readonly paidAt?: Date;
|
|
420
|
+
readonly failureReason?: string;
|
|
421
|
+
}
|
|
422
|
+
```
|
|
423
|
+
|
|
424
|
+
`id` is the provider-assigned numeric ID. It is `undefined` after `initialize()` and only populated by `verify()` / `fetch()`. Use `reference` as the stable lifecycle lookup key.
|
|
425
|
+
|
|
426
|
+
- `fees` and `netAmount` are the provider-charged fee and net settlement amount (`amount - fees`). Available from `verify()` / `fetch()` / `list()` for successful transactions; `undefined` after `initialize()` and for non-successful statuses.
|
|
427
|
+
- `amount` is `undefined` on the `Payment` returned by `initialize()` for a catalog checkout (`products`), because the total is provider-priced. Read it from `verify()`/`fetch()`/`list()` or the webhook payload. Partial refunds are sized in `settlementAmount.currency` when the provider converts the charge (Bachs adaptive pricing).
|
|
428
|
+
- `accessCode` is the provider-issued access code (e.g., Paystack `access_code`). Available after `initialize()`; `undefined` for verified/fetched transactions.
|
|
429
|
+
|
|
430
|
+
### PaymentStatus
|
|
431
|
+
|
|
432
|
+
```ts
|
|
433
|
+
type PaymentStatus =
|
|
434
|
+
| { kind: "initialized" }
|
|
435
|
+
| { kind: "pending" }
|
|
436
|
+
| { kind: "success"; paidAt: Date }
|
|
437
|
+
| { kind: "failed"; reason: string; failedAt: Date }
|
|
438
|
+
| { kind: "abandoned" }
|
|
439
|
+
| { kind: "refunded"; refundedAt: Date; refundId: string };
|
|
440
|
+
```
|
|
441
|
+
|
|
442
|
+
### PaymentRequest
|
|
443
|
+
|
|
444
|
+
```ts
|
|
445
|
+
type PaymentRequest =
|
|
446
|
+
| {
|
|
447
|
+
readonly amount: Money;
|
|
448
|
+
readonly products?: undefined;
|
|
449
|
+
readonly customer: CustomerReference;
|
|
450
|
+
readonly reference: PaymentReference;
|
|
451
|
+
readonly callbackUrl?: string;
|
|
452
|
+
readonly channels?: ReadonlyArray<PaymentChannel>;
|
|
453
|
+
readonly metadata?: Metadata;
|
|
454
|
+
readonly expiresAt?: Date;
|
|
455
|
+
readonly idempotencyKey?: string;
|
|
456
|
+
readonly correlationId?: string;
|
|
457
|
+
}
|
|
458
|
+
| {
|
|
459
|
+
/** Catalog cart. Required to start a subscription on Bachs. */
|
|
460
|
+
readonly products: ReadonlyArray<PaymentRequestItem>;
|
|
461
|
+
readonly amount?: undefined;
|
|
462
|
+
readonly customer: CustomerReference;
|
|
463
|
+
readonly reference: PaymentReference;
|
|
464
|
+
readonly callbackUrl?: string;
|
|
465
|
+
readonly channels?: ReadonlyArray<PaymentChannel>;
|
|
466
|
+
readonly metadata?: Metadata;
|
|
467
|
+
readonly expiresAt?: Date;
|
|
468
|
+
readonly idempotencyKey?: string;
|
|
469
|
+
readonly correlationId?: string;
|
|
470
|
+
};
|
|
471
|
+
|
|
472
|
+
interface PaymentRequestItem {
|
|
473
|
+
readonly productId: string;
|
|
474
|
+
readonly quantity?: number;
|
|
475
|
+
readonly amount?: Money; // buyer-chosen amount for a custom (pay-what-you-want) price
|
|
476
|
+
}
|
|
477
|
+
|
|
478
|
+
type CustomerReference =
|
|
479
|
+
| { kind: "new"; email: string; phone?: string; name?: string }
|
|
480
|
+
| { kind: "existing"; providerCustomerId: string };
|
|
481
|
+
```
|
|
482
|
+
|
|
483
|
+
Supplying `products` creates the checkout from your catalog instead of a raw amount. Bachs
|
|
484
|
+
requires this to start a **subscription** (a recurring checkout needs a recurring catalog
|
|
485
|
+
product); a cart and a raw amount are mutually exclusive at the provider, so `amount` is
|
|
486
|
+
ignored when `products` is present. Paystack rejects catalog checkouts with
|
|
487
|
+
`UnsupportedProviderError`.
|
|
488
|
+
|
|
489
|
+
### Refund
|
|
490
|
+
|
|
491
|
+
```ts
|
|
492
|
+
interface Refund {
|
|
493
|
+
readonly id: string;
|
|
494
|
+
readonly paymentId: string;
|
|
495
|
+
readonly providerId: Provider;
|
|
496
|
+
readonly amount: Money;
|
|
497
|
+
readonly reason: string;
|
|
498
|
+
readonly status: RefundStatus;
|
|
499
|
+
/** The provider's own status when `RefundStatus` cannot express it. */
|
|
500
|
+
readonly providerStatus?: string;
|
|
501
|
+
readonly initiatedAt: Date;
|
|
502
|
+
readonly completedAt?: Date;
|
|
503
|
+
readonly failureReason?: string;
|
|
504
|
+
readonly metadata: Metadata;
|
|
505
|
+
}
|
|
506
|
+
```
|
|
507
|
+
|
|
508
|
+
### RefundStatus
|
|
509
|
+
|
|
510
|
+
```ts
|
|
511
|
+
type RefundStatus =
|
|
512
|
+
| { kind: "pending" }
|
|
513
|
+
| { kind: "processing" }
|
|
514
|
+
| { kind: "succeeded"; settledAt: Date }
|
|
515
|
+
| { kind: "failed"; reason: string; failedAt: Date };
|
|
516
|
+
```
|
|
517
|
+
|
|
518
|
+
### WebhookEvent
|
|
519
|
+
|
|
520
|
+
```ts
|
|
521
|
+
interface WebhookEvent {
|
|
522
|
+
readonly id: string;
|
|
523
|
+
readonly provider: Provider;
|
|
524
|
+
readonly type: string;
|
|
525
|
+
readonly originalType: string;
|
|
526
|
+
readonly createdAt: Date;
|
|
527
|
+
readonly receivedAt: Date;
|
|
528
|
+
readonly payload: Readonly<Record<string, unknown>>;
|
|
529
|
+
readonly raw: Readonly<Record<string, unknown>>;
|
|
530
|
+
}
|
|
531
|
+
```
|
|
532
|
+
|
|
533
|
+
### Result<T, E>
|
|
534
|
+
|
|
535
|
+
```ts
|
|
536
|
+
type Result<T, E> =
|
|
537
|
+
| { readonly ok: true; readonly value: T }
|
|
538
|
+
| { readonly ok: false; readonly error: E };
|
|
539
|
+
|
|
540
|
+
// Constructors
|
|
541
|
+
function ok<T>(value: T): Result<T, never>;
|
|
542
|
+
function err<E>(error: E): Result<never, E>;
|
|
543
|
+
function attempt<T, E>(fn: () => T): Result<T, E>;
|
|
544
|
+
```
|
|
545
|
+
|
|
546
|
+
```ts
|
|
547
|
+
const result = await client.payments.initialize(req);
|
|
548
|
+
|
|
549
|
+
if (result.ok) {
|
|
550
|
+
const payment = result.value; // typed as Payment
|
|
551
|
+
} else {
|
|
552
|
+
const error = result.error; // typed as PaymentError
|
|
553
|
+
}
|
|
554
|
+
```
|
|
555
|
+
|
|
556
|
+
### Money
|
|
557
|
+
|
|
558
|
+
```ts
|
|
559
|
+
// Branded number; the brand symbol is internal (do not construct manually).
|
|
560
|
+
type MinorUnits = number & { readonly [MinorUnitsSymbol]: true };
|
|
561
|
+
|
|
562
|
+
interface Money {
|
|
563
|
+
readonly amount: MinorUnits;
|
|
564
|
+
readonly currency: Currency;
|
|
565
|
+
}
|
|
566
|
+
|
|
567
|
+
// Factory (validates finite, non-negative integer)
|
|
568
|
+
function Money(input: { amount: number; currency: string }): Money;
|
|
569
|
+
```
|
|
570
|
+
|
|
571
|
+
### PaymentReference
|
|
572
|
+
|
|
573
|
+
```ts
|
|
574
|
+
// Branded string; the brand symbol is internal (do not construct manually).
|
|
575
|
+
type PaymentReference = string & { readonly [PaymentReferenceSymbol]: true };
|
|
576
|
+
|
|
577
|
+
// Factory (validates 6–100 chars of [A-Za-z0-9._=,+/-])
|
|
578
|
+
function PaymentReference(value: string): PaymentReference;
|
|
579
|
+
```
|
|
580
|
+
|
|
581
|
+
### Provider
|
|
582
|
+
|
|
583
|
+
```ts
|
|
584
|
+
// "paystack" today; any future provider id also type-checks via (string & {}).
|
|
585
|
+
type Provider = "paystack" | (string & {});
|
|
586
|
+
|
|
587
|
+
// Factory
|
|
588
|
+
function Provider(value: string): Provider;
|
|
589
|
+
```
|
|
590
|
+
|
|
591
|
+
### Currency
|
|
592
|
+
|
|
593
|
+
`Currency` is a branded union of ISO 4217 codes AND a runtime validator — it is
|
|
594
|
+
not an enum, but it offers enum-style constants for compile-time-known codes:
|
|
595
|
+
|
|
596
|
+
```ts
|
|
597
|
+
type Currency =
|
|
598
|
+
| "NGN"
|
|
599
|
+
| "GHS"
|
|
600
|
+
| "ZAR"
|
|
601
|
+
| "KES"
|
|
602
|
+
| "USD"
|
|
603
|
+
| "EUR"
|
|
604
|
+
| "GBP"
|
|
605
|
+
| (string & {}); // any valid 3-letter code still type-checks
|
|
606
|
+
|
|
607
|
+
// Validator factory (throws ValidationError for non-ISO 4217 input):
|
|
608
|
+
function Currency(value: string): Currency;
|
|
609
|
+
|
|
610
|
+
// Enum-style constants merged onto the validator:
|
|
611
|
+
namespace Currency {
|
|
612
|
+
export const NGN: Currency;
|
|
613
|
+
export const USD: Currency;
|
|
614
|
+
}
|
|
615
|
+
|
|
616
|
+
// Both idioms work:
|
|
617
|
+
Currency.NGN; // => "NGN"
|
|
618
|
+
Currency("NGN"); // => "NGN"
|
|
619
|
+
```
|
|
620
|
+
|
|
621
|
+
### Metadata
|
|
622
|
+
|
|
623
|
+
```ts
|
|
624
|
+
type Metadata = Readonly<Record<string, string | number | boolean | null>>;
|
|
625
|
+
```
|
|
626
|
+
|
|
627
|
+
### Customer
|
|
628
|
+
|
|
629
|
+
```ts
|
|
630
|
+
interface Customer {
|
|
631
|
+
readonly id: string;
|
|
632
|
+
readonly email: string;
|
|
633
|
+
readonly phone?: string;
|
|
634
|
+
readonly name?: string;
|
|
635
|
+
readonly metadata?: Metadata;
|
|
636
|
+
}
|
|
637
|
+
```
|
|
638
|
+
|
|
639
|
+
### RecurringCadence
|
|
640
|
+
|
|
641
|
+
```ts
|
|
642
|
+
interface RecurringCadence {
|
|
643
|
+
readonly interval: "day" | "week" | "month" | "year";
|
|
644
|
+
readonly frequency: number; // positive integer; 1 = every interval
|
|
645
|
+
}
|
|
646
|
+
|
|
647
|
+
// Validator factory (throws ValidationError for an unknown interval or bad frequency):
|
|
648
|
+
function RecurringCadence(input: { interval: string; frequency: number }): RecurringCadence;
|
|
649
|
+
```
|
|
650
|
+
|
|
651
|
+
### Product
|
|
652
|
+
|
|
653
|
+
```ts
|
|
654
|
+
type ProductStatus = "active" | "archived";
|
|
655
|
+
type PriceType = "fixed" | "free" | "custom";
|
|
656
|
+
|
|
657
|
+
interface Product {
|
|
658
|
+
readonly id: string;
|
|
659
|
+
readonly providerId: Provider;
|
|
660
|
+
readonly name: string;
|
|
661
|
+
readonly description?: string;
|
|
662
|
+
readonly price: ProductPrice;
|
|
663
|
+
readonly status: ProductStatus;
|
|
664
|
+
readonly billingCycle?: RecurringCadence; // present on recurring products
|
|
665
|
+
readonly trialPeriod?: RecurringCadence; // free period before the first charge
|
|
666
|
+
readonly metadata: Metadata;
|
|
667
|
+
readonly createdAt: Date;
|
|
668
|
+
readonly updatedAt: Date;
|
|
669
|
+
readonly archivedAt?: Date;
|
|
670
|
+
}
|
|
671
|
+
|
|
672
|
+
interface ProductPrice {
|
|
673
|
+
readonly priceType: PriceType;
|
|
674
|
+
readonly currency: Currency;
|
|
675
|
+
readonly amount?: Money; // fixed
|
|
676
|
+
readonly presetAmount?: Money; // custom (pay what you want)
|
|
677
|
+
readonly minimumAmount?: Money;
|
|
678
|
+
readonly maximumAmount?: Money;
|
|
679
|
+
readonly currencyOptions: ReadonlyArray<CurrencyPriceOption>;
|
|
680
|
+
}
|
|
681
|
+
|
|
682
|
+
// isRecurring(product) => boolean — convenience check for billingCycle presence
|
|
683
|
+
```
|
|
684
|
+
|
|
685
|
+
### Subscription
|
|
686
|
+
|
|
687
|
+
```ts
|
|
688
|
+
type SubscriptionStatus =
|
|
689
|
+
| { readonly kind: "trialing"; readonly trialEnd: Date }
|
|
690
|
+
| { readonly kind: "active" }
|
|
691
|
+
| { readonly kind: "pastDue" }
|
|
692
|
+
| { readonly kind: "unpaid" }
|
|
693
|
+
| { readonly kind: "canceled"; readonly canceledAt: Date }
|
|
694
|
+
| { readonly kind: "paused" };
|
|
695
|
+
|
|
696
|
+
interface Subscription {
|
|
697
|
+
readonly id: string;
|
|
698
|
+
readonly providerId: Provider;
|
|
699
|
+
readonly customer: Customer;
|
|
700
|
+
readonly productId?: string;
|
|
701
|
+
readonly productName?: string;
|
|
702
|
+
readonly status: SubscriptionStatus;
|
|
703
|
+
readonly amount: Money;
|
|
704
|
+
readonly billingCycle: RecurringCadence;
|
|
705
|
+
readonly quantity: number;
|
|
706
|
+
readonly currentPeriodStart: Date;
|
|
707
|
+
readonly currentPeriodEnd: Date;
|
|
708
|
+
readonly nextBilledAt?: Date;
|
|
709
|
+
readonly cancelAtPeriodEnd: boolean;
|
|
710
|
+
readonly canceledAt?: Date;
|
|
711
|
+
readonly createdAt: Date;
|
|
712
|
+
readonly metadata: Metadata;
|
|
713
|
+
}
|
|
714
|
+
|
|
715
|
+
// isSubscriptionActive(status) — active or trialing (grants access)
|
|
716
|
+
// isSubscriptionDelinquent(status) — pastDue or unpaid (needs attention)
|
|
717
|
+
// isFinalSubscriptionStatus(status) — canceled
|
|
718
|
+
```
|
|
719
|
+
|
|
720
|
+
An unrecognised provider status maps to `paused`, never to `active`: new statuses must not
|
|
721
|
+
silently grant access.
|
|
722
|
+
|
|
723
|
+
### PortalSession
|
|
724
|
+
|
|
725
|
+
```ts
|
|
726
|
+
interface PortalSession {
|
|
727
|
+
readonly id?: string; // psn_... — correlation only, not a credential
|
|
728
|
+
readonly url: string; // short-lived credential; never log or cache
|
|
729
|
+
}
|
|
730
|
+
```
|
|
731
|
+
|
|
732
|
+
### PaymentChannel
|
|
733
|
+
|
|
734
|
+
```ts
|
|
735
|
+
type PaymentChannel = "card" | "bank" | "ussd" | "qr" | "mobile_money" | "bank_transfer" | (string & {});
|
|
736
|
+
```
|
|
737
|
+
|
|
738
|
+
### PaymentAttempt
|
|
739
|
+
|
|
740
|
+
```ts
|
|
741
|
+
interface PaymentAttempt {
|
|
742
|
+
readonly id: string;
|
|
743
|
+
readonly status: PaymentStatus;
|
|
744
|
+
readonly channel: PaymentChannel;
|
|
745
|
+
readonly ipAddress?: string;
|
|
746
|
+
readonly fees?: Money;
|
|
747
|
+
readonly authorizationCode?: string;
|
|
748
|
+
readonly bin?: string;
|
|
749
|
+
readonly last4?: string;
|
|
750
|
+
readonly bank?: string;
|
|
751
|
+
readonly attemptedAt: Date;
|
|
752
|
+
}
|
|
753
|
+
```
|
|
754
|
+
|
|
755
|
+
### HealthStatus
|
|
756
|
+
|
|
757
|
+
```ts
|
|
758
|
+
interface HealthStatus {
|
|
759
|
+
readonly healthy: boolean;
|
|
760
|
+
readonly latencyMs: number;
|
|
761
|
+
readonly timestamp: Date;
|
|
762
|
+
}
|
|
763
|
+
```
|
|
764
|
+
|
|
765
|
+
### Page\<T\>
|
|
766
|
+
|
|
767
|
+
```ts
|
|
768
|
+
interface Page<T> {
|
|
769
|
+
readonly items: ReadonlyArray<T>;
|
|
770
|
+
readonly total: number;
|
|
771
|
+
readonly page: number;
|
|
772
|
+
readonly perPage: number;
|
|
773
|
+
}
|
|
774
|
+
```
|
|
775
|
+
|
|
776
|
+
### ListQuery
|
|
777
|
+
|
|
778
|
+
```ts
|
|
779
|
+
interface ListQuery {
|
|
780
|
+
readonly page?: number;
|
|
781
|
+
readonly perPage?: number;
|
|
782
|
+
readonly from?: Date;
|
|
783
|
+
readonly to?: Date;
|
|
784
|
+
readonly status?: string;
|
|
785
|
+
readonly customer?: string;
|
|
786
|
+
}
|
|
787
|
+
```
|
|
788
|
+
|
|
789
|
+
### ProviderCapabilities
|
|
790
|
+
|
|
791
|
+
```ts
|
|
792
|
+
interface ProviderCapabilities {
|
|
793
|
+
readonly supportsAuthorizationUrl: boolean;
|
|
794
|
+
readonly supportsRecurring: boolean;
|
|
795
|
+
readonly supportsPartialRefund: boolean;
|
|
796
|
+
readonly supportsWebhooks: boolean;
|
|
797
|
+
readonly supportsTransfers: boolean;
|
|
798
|
+
/** `true` when the provider documents an `Idempotency-Key` on writes (Bachs). */
|
|
799
|
+
readonly supportsIdempotencyKey?: boolean;
|
|
800
|
+
readonly maxAmount?: Money;
|
|
801
|
+
readonly supportedCurrencies: ReadonlyArray<Currency>;
|
|
802
|
+
readonly supportedChannels: ReadonlyArray<PaymentChannel>;
|
|
803
|
+
readonly supportedTransferCurrencies: ReadonlyArray<Currency>;
|
|
804
|
+
}
|
|
805
|
+
```
|
|
806
|
+
|
|
807
|
+
### RefundRequest
|
|
808
|
+
|
|
809
|
+
```ts
|
|
810
|
+
interface RefundRequest {
|
|
811
|
+
readonly paymentId: string;
|
|
812
|
+
readonly amount?: number;
|
|
813
|
+
readonly reason: string;
|
|
814
|
+
readonly reference: string;
|
|
815
|
+
readonly idempotencyKey?: string;
|
|
816
|
+
readonly correlationId?: string;
|
|
817
|
+
}
|
|
818
|
+
```
|
|
819
|
+
|
|
820
|
+
### RefundResult
|
|
821
|
+
|
|
822
|
+
```ts
|
|
823
|
+
interface RefundResult {
|
|
824
|
+
readonly id: string;
|
|
825
|
+
readonly paymentId: string;
|
|
826
|
+
readonly amount: Money;
|
|
827
|
+
readonly status: "pending" | "processing" | "succeeded" | "failed";
|
|
828
|
+
/** The provider's own status when the four-state union cannot express it. */
|
|
829
|
+
readonly providerStatus?: string;
|
|
830
|
+
readonly reason: string;
|
|
831
|
+
readonly reference: string;
|
|
832
|
+
readonly createdAt: Date;
|
|
833
|
+
readonly completedAt?: Date;
|
|
834
|
+
}
|
|
835
|
+
```
|
|
836
|
+
|
|
837
|
+
### WebhookInput
|
|
838
|
+
|
|
839
|
+
```ts
|
|
840
|
+
interface WebhookInput {
|
|
841
|
+
readonly provider?: string;
|
|
842
|
+
readonly rawBody: string | Uint8Array;
|
|
843
|
+
/**
|
|
844
|
+
* Optional single-value signature. Providers read their own headers; this is
|
|
845
|
+
* a fallback for callers that already extracted the value (Paystack). Bachs
|
|
846
|
+
* needs the header pair and ignores it.
|
|
847
|
+
*/
|
|
848
|
+
readonly signature?: string;
|
|
849
|
+
readonly headers?: Readonly<Record<string, string | readonly string[] | undefined>>;
|
|
850
|
+
}
|
|
851
|
+
```
|
|
852
|
+
|
|
853
|
+
### RefundCreateInput
|
|
854
|
+
|
|
855
|
+
```ts
|
|
856
|
+
interface RefundCreateInput {
|
|
857
|
+
readonly paymentId: string;
|
|
858
|
+
readonly amount?: Money;
|
|
859
|
+
readonly reason: string;
|
|
860
|
+
readonly reference?: string;
|
|
861
|
+
readonly idempotencyKey?: string;
|
|
862
|
+
readonly metadata?: Metadata;
|
|
863
|
+
readonly correlationId?: string;
|
|
864
|
+
}
|
|
865
|
+
```
|
|
866
|
+
|
|
867
|
+
### Transfer
|
|
868
|
+
|
|
869
|
+
```ts
|
|
870
|
+
interface Transfer {
|
|
871
|
+
readonly id: string;
|
|
872
|
+
readonly providerId: Provider;
|
|
873
|
+
/** Amount delivered to the destination. */
|
|
874
|
+
readonly amount: Money;
|
|
875
|
+
readonly recipient: TransferRecipient;
|
|
876
|
+
readonly status: TransferStatus;
|
|
877
|
+
readonly reference: string;
|
|
878
|
+
readonly reason?: string;
|
|
879
|
+
readonly transferCode?: string; // provider transfer code (e.g. Paystack TRF_...)
|
|
880
|
+
readonly fee?: Money;
|
|
881
|
+
/** Gross amount debited from the balance, when the provider reports it. */
|
|
882
|
+
readonly totalDebited?: Money;
|
|
883
|
+
/** Currency the balance was debited in (differs from `amount.currency` cross-currency). */
|
|
884
|
+
readonly sourceCurrency?: Currency;
|
|
885
|
+
readonly createdAt: Date;
|
|
886
|
+
readonly completedAt?: Date;
|
|
887
|
+
readonly failureReason?: string;
|
|
888
|
+
readonly metadata: Metadata;
|
|
889
|
+
}
|
|
890
|
+
```
|
|
891
|
+
|
|
892
|
+
`fee` and `totalDebited` are in `sourceCurrency`; `amount` is in the destination
|
|
893
|
+
currency. They only add up (`totalDebited === amount + fee`) for a same-currency
|
|
894
|
+
payout.
|
|
895
|
+
|
|
896
|
+
### TransferStatus
|
|
897
|
+
|
|
898
|
+
```ts
|
|
899
|
+
type TransferStatus =
|
|
900
|
+
| { readonly kind: "pending"; readonly requiresAction?: boolean }
|
|
901
|
+
| { readonly kind: "processing" }
|
|
902
|
+
| { readonly kind: "succeeded"; readonly settledAt: Date }
|
|
903
|
+
| { readonly kind: "failed"; readonly reason: string; readonly failedAt: Date }
|
|
904
|
+
| { readonly kind: "reversed"; readonly reversedAt: Date };
|
|
905
|
+
```
|
|
906
|
+
|
|
907
|
+
`isFinalTransferStatus(status)` returns `true` for `succeeded`, `failed`, and `reversed`.
|
|
908
|
+
|
|
909
|
+
`pending.requiresAction` is set when the provider is waiting on the merchant
|
|
910
|
+
before the payout can proceed (Paystack's `otp` state). There is no
|
|
911
|
+
finalize-transfer call in the SDK, so handle it in the Paystack dashboard or via
|
|
912
|
+
that provider's own tooling.
|
|
913
|
+
|
|
914
|
+
### TransferRecipient
|
|
915
|
+
|
|
916
|
+
```ts
|
|
917
|
+
interface TransferRecipient {
|
|
918
|
+
readonly code: string;
|
|
919
|
+
readonly name: string;
|
|
920
|
+
readonly accountNumber: string;
|
|
921
|
+
readonly bankCode: string;
|
|
922
|
+
readonly currency: Currency;
|
|
923
|
+
/** Provider review state where one exists (Bachs gates new destinations on approval). */
|
|
924
|
+
readonly status?: "pending_review" | "approved" | "rejected";
|
|
925
|
+
readonly createdAt: Date;
|
|
926
|
+
readonly metadata: Metadata;
|
|
927
|
+
}
|
|
928
|
+
```
|
|
929
|
+
|
|
930
|
+
When a provider response carries only the destination id (Paystack's create
|
|
931
|
+
response, a Bachs payout list), the detail fields are the literal `"unknown"` and
|
|
932
|
+
only `code` is trustworthy. Fetch the recipient by code, or keep the object
|
|
933
|
+
returned when you created it — payouts are enriched with a destination lookup
|
|
934
|
+
where the provider supports one.
|
|
935
|
+
|
|
936
|
+
### BankCode
|
|
937
|
+
|
|
938
|
+
```ts
|
|
939
|
+
interface BankCode {
|
|
940
|
+
readonly code: string;
|
|
941
|
+
readonly name: string;
|
|
942
|
+
readonly currency: Currency;
|
|
943
|
+
}
|
|
944
|
+
```
|
|
945
|
+
|
|
946
|
+
### CreateRecipientInput
|
|
947
|
+
|
|
948
|
+
```ts
|
|
949
|
+
interface CreateRecipientInput {
|
|
950
|
+
readonly name: string;
|
|
951
|
+
readonly accountNumber: string;
|
|
952
|
+
readonly bankCode: string;
|
|
953
|
+
readonly currency: Currency;
|
|
954
|
+
/** Defaults to `"bank_account"`; `"mobile_money"` needs `phoneNumber`. */
|
|
955
|
+
readonly type?: "bank_account" | "mobile_money";
|
|
956
|
+
readonly phoneNumber?: string;
|
|
957
|
+
readonly mobileProvider?: string;
|
|
958
|
+
readonly accountName?: string;
|
|
959
|
+
readonly bankName?: string;
|
|
960
|
+
readonly scheme?: string;
|
|
961
|
+
readonly routingNumber?: string;
|
|
962
|
+
readonly sortCode?: string;
|
|
963
|
+
readonly metadata?: Metadata;
|
|
964
|
+
}
|
|
965
|
+
```
|
|
966
|
+
|
|
967
|
+
Crypto destinations are not representable (`Currency` is ISO 4217), so they are
|
|
968
|
+
rejected rather than approximated. Paystack derives its country-specific
|
|
969
|
+
recipient type from the currency (`nuban`/`ghipss`/`basa`/`mobile_money`) and
|
|
970
|
+
fails locally for a pair it cannot express; Bachs takes the kind and the phone
|
|
971
|
+
number directly.
|
|
972
|
+
|
|
973
|
+
### InitiateTransferInput
|
|
974
|
+
|
|
975
|
+
```ts
|
|
976
|
+
interface InitiateTransferInput {
|
|
977
|
+
/** Exactly one of `amount` and `quoteId` (a quote fixes both sides). */
|
|
978
|
+
readonly amount?: Money;
|
|
979
|
+
readonly recipientCode: string;
|
|
980
|
+
readonly reference: string;
|
|
981
|
+
readonly reason?: string;
|
|
982
|
+
readonly currency: Currency;
|
|
983
|
+
/** From `transfers.createQuote()`; providers without it answer `UnsupportedProviderError`. */
|
|
984
|
+
readonly quoteId?: string;
|
|
985
|
+
/** Account-number rails (Paystack: Kenya MPESA requires it). */
|
|
986
|
+
readonly accountReference?: string;
|
|
987
|
+
readonly correlationId?: string;
|
|
988
|
+
readonly idempotencyKey?: string;
|
|
989
|
+
readonly metadata?: Metadata;
|
|
990
|
+
}
|
|
991
|
+
```
|
|
992
|
+
|
|
993
|
+
`amount` XOR `quoteId` is enforced locally with `ValidationError` before any
|
|
994
|
+
request. Paystack requires `reference` to be 16-50 characters of lowercase
|
|
995
|
+
letters, digits, `-` or `_`; the SDK validates that locally and refuses the call
|
|
996
|
+
otherwise. Bachs limits it to 128 characters.
|
|
997
|
+
|
|
998
|
+
### TransferQuote / TransferQuoteInput
|
|
999
|
+
|
|
1000
|
+
```ts
|
|
1001
|
+
interface TransferQuoteInput {
|
|
1002
|
+
readonly fromCurrency: Currency;
|
|
1003
|
+
readonly toCurrency: Currency;
|
|
1004
|
+
readonly amount: Money; // in fromCurrency
|
|
1005
|
+
}
|
|
1006
|
+
|
|
1007
|
+
interface TransferQuote {
|
|
1008
|
+
readonly id: string;
|
|
1009
|
+
readonly providerId: Provider;
|
|
1010
|
+
readonly fromCurrency: Currency;
|
|
1011
|
+
readonly toCurrency: Currency;
|
|
1012
|
+
readonly fromAmount: Money;
|
|
1013
|
+
readonly toAmount: Money;
|
|
1014
|
+
readonly exchangeRate: string;
|
|
1015
|
+
readonly expiresAt?: Date;
|
|
1016
|
+
}
|
|
1017
|
+
```
|
|
1018
|
+
|
|
1019
|
+
`client.transfers.createQuote(input)` locks the rate for a cross-currency
|
|
1020
|
+
payout (Bachs `POST /v1/payouts/quotes`). Pass the returned `id` as `quoteId` to
|
|
1021
|
+
`initiate()` and omit `amount`.
|
|
1022
|
+
|
|
1023
|
+
### ResolveAccountResult
|
|
1024
|
+
|
|
1025
|
+
```ts
|
|
1026
|
+
interface ResolveAccountResult {
|
|
1027
|
+
readonly accountName: string;
|
|
1028
|
+
readonly accountNumber: string;
|
|
1029
|
+
readonly bankId?: number; // provider-internal bank identifier
|
|
1030
|
+
}
|
|
1031
|
+
```
|
|
1032
|
+
|
|
1033
|
+
### HttpClient / HttpRequest / HttpResponse
|
|
1034
|
+
|
|
1035
|
+
```ts
|
|
1036
|
+
interface HttpClient {
|
|
1037
|
+
send(request: HttpRequest): Promise<Result<HttpResponse, PaymentError>>;
|
|
1038
|
+
}
|
|
1039
|
+
|
|
1040
|
+
interface HttpRequest {
|
|
1041
|
+
readonly method: "GET" | "POST" | "PUT" | "PATCH" | "DELETE" | "HEAD";
|
|
1042
|
+
readonly url: string;
|
|
1043
|
+
readonly headers?: Readonly<Record<string, string>>;
|
|
1044
|
+
readonly body?: string;
|
|
1045
|
+
readonly timeoutMs?: number;
|
|
1046
|
+
readonly isRetryable?: boolean;
|
|
1047
|
+
readonly correlationId?: string;
|
|
1048
|
+
readonly idempotencyKey?: string;
|
|
1049
|
+
}
|
|
1050
|
+
|
|
1051
|
+
interface HttpResponse {
|
|
1052
|
+
readonly status: number;
|
|
1053
|
+
readonly headers: Readonly<Record<string, string>>;
|
|
1054
|
+
readonly body: string;
|
|
1055
|
+
}
|
|
1056
|
+
```
|
|
1057
|
+
|
|
1058
|
+
### Clock / IdGenerator
|
|
1059
|
+
|
|
1060
|
+
```ts
|
|
1061
|
+
interface Clock {
|
|
1062
|
+
now(): Date;
|
|
1063
|
+
}
|
|
1064
|
+
|
|
1065
|
+
interface IdGenerator {
|
|
1066
|
+
generate(): string;
|
|
1067
|
+
}
|
|
1068
|
+
```
|
|
1069
|
+
|
|
1070
|
+
### EventHandler / Unsubscribe
|
|
1071
|
+
|
|
1072
|
+
```ts
|
|
1073
|
+
type EventHandler<T extends PaymentEventType = PaymentEventType> = (
|
|
1074
|
+
event: Extract<PaymentEvent, { type: T }>,
|
|
1075
|
+
) => void | Promise<void>;
|
|
1076
|
+
|
|
1077
|
+
type Unsubscribe = () => void;
|
|
1078
|
+
```
|
|
1079
|
+
|
|
1080
|
+
## Error Classes
|
|
1081
|
+
|
|
1082
|
+
All errors extend `PaymentError`:
|
|
1083
|
+
|
|
1084
|
+
| Error | HTTP | isRetryable | When |
|
|
1085
|
+
|-------|------|-------------|------|
|
|
1086
|
+
| `ConfigurationError` | — | No | Bad config at `createPaymentClient()` |
|
|
1087
|
+
| `ValidationError` | 422 | No | Invalid input from app |
|
|
1088
|
+
| `NetworkError` | 502 | Yes | HTTP failure, DNS, TLS |
|
|
1089
|
+
| `TimeoutError` | 504 | Yes | Request timed out |
|
|
1090
|
+
| `ProviderUnavailableError` | 502 | Yes | Provider 5xx after retries |
|
|
1091
|
+
| `ProviderBadRequestError` | 400 | No | Provider 400 |
|
|
1092
|
+
| `ProviderUnauthorizedError` | 401 | No | Provider 401/403 |
|
|
1093
|
+
| `ProviderNotFoundError` | 404 | No | Provider 404 |
|
|
1094
|
+
| `ProviderConflictError` | 409 | No | Provider 409 |
|
|
1095
|
+
| `ProviderRateLimitError` | 429 | Yes | Provider 429 (`Retry-After` honoured, capped at 10 s) |
|
|
1096
|
+
| `ProviderError` | varies | No | Unmapped provider status, including `3xx` (redirects are not followed) |
|
|
1097
|
+
| `VerificationError` | 502 | Yes | Verification API call failed |
|
|
1098
|
+
| `WebhookValidationError` | 401 | No | Invalid signature or body |
|
|
1099
|
+
| `UnsupportedProviderError` | 501 | No | The configured provider does not implement the requested capability (catalog, subscriptions, customers, portal) |
|
|
1100
|
+
| `RefundError` | 400 | No | Refund rejected by provider |
|
|
1101
|
+
| `InternalError` | 500 | No | SDK bug — report it |
|
|
1102
|
+
|
|
1103
|
+
## Health
|
|
1104
|
+
|
|
1105
|
+
```ts
|
|
1106
|
+
const health = await client.health();
|
|
1107
|
+
// [{ healthy: true, latencyMs: 45, timestamp: Date }]
|
|
1108
|
+
```
|