@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,401 @@
|
|
|
1
|
+
# Migration Guide
|
|
2
|
+
|
|
3
|
+
Migrating from direct provider SDK usage to `@theengineerscanvas/payment`.
|
|
4
|
+
|
|
5
|
+
## Upgrading from the pre-public builds
|
|
6
|
+
|
|
7
|
+
The package moved to public npm under a lowercase scope in RC16:
|
|
8
|
+
|
|
9
|
+
- Replace every `@TheEngineersCanvas/payment` import with
|
|
10
|
+
`@theengineerscanvas/payment` (including the `/nestjs` subpath).
|
|
11
|
+
- Pin the exact version: `bun add --exact @theengineerscanvas/payment@0.1.0-rc.16`.
|
|
12
|
+
- Version labels use the semver form `0.1.0-rc.N`; the old `RC16` label is
|
|
13
|
+
historical. Use `0.1.0-rc.16` in `package.json` and install commands.
|
|
14
|
+
- Remove any GitHub Packages `.npmrc` token configuration; public npm needs no
|
|
15
|
+
registry authentication.
|
|
16
|
+
|
|
17
|
+
## Why Migrate
|
|
18
|
+
|
|
19
|
+
- **One API, any provider.** Switch providers without changing application code.
|
|
20
|
+
- **Built-in event system.** React to payment events through a single pub/sub bus.
|
|
21
|
+
- **Result types.** Explicit error handling with `Result<T, E>` — no guessing which errors to catch.
|
|
22
|
+
- **Type safety.** Branded primitives for `Money`, `PaymentReference`, `Provider` prevent common bugs.
|
|
23
|
+
- **Zero runtime deps.** Nothing to audit, nothing to maintain in your dependency tree.
|
|
24
|
+
|
|
25
|
+
## Before: Direct Paystack Integration
|
|
26
|
+
|
|
27
|
+
```ts
|
|
28
|
+
import https from "https";
|
|
29
|
+
|
|
30
|
+
// Initialize
|
|
31
|
+
const response = await fetch("https://api.paystack.co/transaction/initialize", {
|
|
32
|
+
method: "POST",
|
|
33
|
+
headers: { Authorization: `Bearer ${process.env.PAYSTACK_SECRET_KEY}` },
|
|
34
|
+
body: JSON.stringify({
|
|
35
|
+
email: "customer@example.com",
|
|
36
|
+
amount: 500000, // NGN 5,000 in kobo
|
|
37
|
+
reference: "order-9001",
|
|
38
|
+
callback_url: "https://myapp.com/verify",
|
|
39
|
+
}),
|
|
40
|
+
});
|
|
41
|
+
|
|
42
|
+
const data = await response.json();
|
|
43
|
+
// Is data.status true? What if false? What error message?
|
|
44
|
+
|
|
45
|
+
// Verify
|
|
46
|
+
const verify = await fetch(
|
|
47
|
+
`https://api.paystack.co/transaction/verify/order-9001`,
|
|
48
|
+
{ headers: { Authorization: `Bearer ${process.env.PAYSTACK_SECRET_KEY}` } },
|
|
49
|
+
);
|
|
50
|
+
// Parse status, map to your own types...
|
|
51
|
+
|
|
52
|
+
// Webhook
|
|
53
|
+
app.post("/webhooks/paystack", express.raw({ type: "application/json" }), async (req, res) => {
|
|
54
|
+
const hash = crypto.createHmac("sha512", secret).update(req.body).digest("hex");
|
|
55
|
+
if (hash !== req.headers["x-paystack-signature"]) {
|
|
56
|
+
return res.status(401).send("Invalid signature");
|
|
57
|
+
}
|
|
58
|
+
const event = JSON.parse(req.body);
|
|
59
|
+
// Handle charge.success, transfer.success, etc.
|
|
60
|
+
// Must know Paystack event names
|
|
61
|
+
res.sendStatus(200);
|
|
62
|
+
});
|
|
63
|
+
```
|
|
64
|
+
|
|
65
|
+
## After: @theengineerscanvas/payment
|
|
66
|
+
|
|
67
|
+
```ts
|
|
68
|
+
import { createPaymentClient, Money, PaymentReference } from "@theengineerscanvas/payment";
|
|
69
|
+
|
|
70
|
+
const client = createPaymentClient({
|
|
71
|
+
providers: {
|
|
72
|
+
paystack: { secretKey: process.env.PAYSTACK_SECRET_KEY! },
|
|
73
|
+
},
|
|
74
|
+
defaultProvider: "paystack",
|
|
75
|
+
});
|
|
76
|
+
|
|
77
|
+
// Initialize
|
|
78
|
+
const result = await client.payments.initialize({
|
|
79
|
+
amount: Money({ amount: 500000, currency: "NGN" }),
|
|
80
|
+
reference: PaymentReference("order-9001"),
|
|
81
|
+
customer: { kind: "new", email: "customer@example.com" },
|
|
82
|
+
callbackUrl: "https://myapp.com/verify",
|
|
83
|
+
});
|
|
84
|
+
|
|
85
|
+
if (result.ok) {
|
|
86
|
+
redirect(result.value.authorizationUrl);
|
|
87
|
+
} else {
|
|
88
|
+
// Type-safe error handling
|
|
89
|
+
console.error(result.error.code, result.error.message);
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
// Verify
|
|
93
|
+
const verified = await client.payments.verify(PaymentReference("order-9001"));
|
|
94
|
+
|
|
95
|
+
// Webhook — provider-agnostic
|
|
96
|
+
app.post("/webhooks/payment", express.raw({ type: "application/json" }), async (req, res) => {
|
|
97
|
+
const result = await client.webhooks.receive({
|
|
98
|
+
rawBody: req.body,
|
|
99
|
+
signature: req.headers["x-paystack-signature"] as string,
|
|
100
|
+
});
|
|
101
|
+
|
|
102
|
+
if (!result.ok) {
|
|
103
|
+
return res.status(401).json({ error: result.error.message });
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
// result.value.type is normalized: "payment.succeeded" (not "charge.success")
|
|
107
|
+
res.json({ received: true });
|
|
108
|
+
});
|
|
109
|
+
```
|
|
110
|
+
|
|
111
|
+
## Breaking Changes to Expect
|
|
112
|
+
|
|
113
|
+
### 1. Result<T, E> instead of try/catch
|
|
114
|
+
|
|
115
|
+
```ts
|
|
116
|
+
// Before: try/catch with unknown errors
|
|
117
|
+
try {
|
|
118
|
+
const payment = await paystack.transaction.initialize(args);
|
|
119
|
+
} catch (error) {
|
|
120
|
+
// Is it a network error? Auth error? Validation?
|
|
121
|
+
}
|
|
122
|
+
|
|
123
|
+
// After: explicit Result
|
|
124
|
+
const result = await client.payments.initialize(args);
|
|
125
|
+
if (result.ok) {
|
|
126
|
+
const payment = result.value; // typed as Payment
|
|
127
|
+
} else {
|
|
128
|
+
const error = result.error; // typed as PaymentError
|
|
129
|
+
// error.code, error.category, error.isRetryable
|
|
130
|
+
}
|
|
131
|
+
```
|
|
132
|
+
|
|
133
|
+
### 2. Branded Primitives
|
|
134
|
+
|
|
135
|
+
```ts
|
|
136
|
+
// Before: raw types
|
|
137
|
+
{ amount: 500000, reference: "order-9001" }
|
|
138
|
+
|
|
139
|
+
// After: branded types (validated)
|
|
140
|
+
{ amount: Money({ amount: 500000, currency: "NGN" }), reference: PaymentReference("order-9001") }
|
|
141
|
+
```
|
|
142
|
+
|
|
143
|
+
### 3. Events Instead of Callbacks
|
|
144
|
+
|
|
145
|
+
```ts
|
|
146
|
+
// Instead of passing callbacks, subscribe to events:
|
|
147
|
+
client.events.on("payment.succeeded", (event) => {
|
|
148
|
+
// Fulfill order
|
|
149
|
+
});
|
|
150
|
+
|
|
151
|
+
client.events.on("payment.failed", (event) => {
|
|
152
|
+
// Notify customer
|
|
153
|
+
});
|
|
154
|
+
```
|
|
155
|
+
|
|
156
|
+
### 4. NestJS webhook path renamed (since 0.1.0-RC7)
|
|
157
|
+
|
|
158
|
+
The built-in `WebhookController` default path changed from `webhooks/tec` to
|
|
159
|
+
`webhooks/payment`.
|
|
160
|
+
|
|
161
|
+
```ts
|
|
162
|
+
// RC6 and earlier
|
|
163
|
+
PaymentModule.forRoot(config); // POST /webhooks/tec
|
|
164
|
+
|
|
165
|
+
// RC7+
|
|
166
|
+
PaymentModule.forRoot(config); // POST /webhooks/payment
|
|
167
|
+
```
|
|
168
|
+
|
|
169
|
+
If you (or your provider dashboard) still point at the old path, either keep
|
|
170
|
+
the old path explicitly or update the URL:
|
|
171
|
+
|
|
172
|
+
```ts
|
|
173
|
+
PaymentModule.forRoot(config, { webhookPath: "webhooks/tec" });
|
|
174
|
+
```
|
|
175
|
+
|
|
176
|
+
### 5. Built-in webhook rate limiting (since 0.1.0-RC7)
|
|
177
|
+
|
|
178
|
+
The NestJS module now ships a zero-dependency rate limiter — no
|
|
179
|
+
`@nestjs/throttler` required:
|
|
180
|
+
|
|
181
|
+
```ts
|
|
182
|
+
PaymentModule.forRoot(config, {
|
|
183
|
+
rateLimit: { limit: 30, ttlMs: 60_000 }, // 30 requests / 60s per IP
|
|
184
|
+
});
|
|
185
|
+
```
|
|
186
|
+
|
|
187
|
+
The limiter is in-memory and per-process. Multi-instance deployments should
|
|
188
|
+
rate limit at the reverse proxy instead.
|
|
189
|
+
|
|
190
|
+
## Webhook Handler Migration
|
|
191
|
+
|
|
192
|
+
| Before | After |
|
|
193
|
+
|--------|-------|
|
|
194
|
+
| `charge.success` | `payment.succeeded` |
|
|
195
|
+
| `transfer.success` | Handled by provider adapter |
|
|
196
|
+
| Manual HMAC | `client.webhooks.receive()` handles verification |
|
|
197
|
+
| Provider-specific event names | Normalized `WebhookEvent.type` |
|
|
198
|
+
|
|
199
|
+
## Event-Driven vs Callback Patterns
|
|
200
|
+
|
|
201
|
+
Before: callback-based flow in each handler:
|
|
202
|
+
|
|
203
|
+
```ts
|
|
204
|
+
async function handleWebhook(event) {
|
|
205
|
+
if (event.event === "charge.success") {
|
|
206
|
+
await updateOrder(event.data.reference, "paid");
|
|
207
|
+
await sendReceipt(event.data.customer.email);
|
|
208
|
+
}
|
|
209
|
+
}
|
|
210
|
+
```
|
|
211
|
+
|
|
212
|
+
After: subscribe once, handle everywhere:
|
|
213
|
+
|
|
214
|
+
```ts
|
|
215
|
+
client.events.on("payment.succeeded", async (event) => {
|
|
216
|
+
await updateOrder(event.payment.reference, "paid");
|
|
217
|
+
});
|
|
218
|
+
|
|
219
|
+
client.events.on("payment.succeeded", async (event) => {
|
|
220
|
+
await sendReceipt(event.payment.customer.email);
|
|
221
|
+
});
|
|
222
|
+
```
|
|
223
|
+
|
|
224
|
+
Multiple subscribers, single event source — no duplicate logic across webhook handlers.
|
|
225
|
+
|
|
226
|
+
## Upgrading to RC15
|
|
227
|
+
|
|
228
|
+
Four changes are breaking by design, taken before 1.0 while there are no
|
|
229
|
+
external consumers:
|
|
230
|
+
|
|
231
|
+
1. **`PaymentRequest` is a discriminated union.** `amount` and `products` are
|
|
232
|
+
mutually exclusive, and `Payment.amount` is optional — a catalog checkout is
|
|
233
|
+
priced by the provider, so the `Payment` returned by `initialize()` has no
|
|
234
|
+
amount until you `verify()`/`fetch()` it or read the webhook.
|
|
235
|
+
|
|
236
|
+
```ts
|
|
237
|
+
// before
|
|
238
|
+
client.payments.initialize({ amount: Money(...), products: [...], reference, customer });
|
|
239
|
+
// after — one or the other
|
|
240
|
+
client.payments.initialize({ products: [...], reference, customer });
|
|
241
|
+
```
|
|
242
|
+
|
|
243
|
+
2. **`InitiateTransferInput.amount` is optional**, required only when `quoteId`
|
|
244
|
+
is absent. Use `client.transfers.createQuote()` for a cross-currency payout.
|
|
245
|
+
|
|
246
|
+
3. **`VerificationError` is 422 and non-retryable** (was 502/retryable), and is
|
|
247
|
+
now raised by `verify()`/`fetch()` when the provider rejects the reference.
|
|
248
|
+
|
|
249
|
+
4. **An `http://` base URL throws `ConfigurationError` at construction.** Set
|
|
250
|
+
`allowInsecureBaseUrl: true` on that provider for local stubs only.
|
|
251
|
+
|
|
252
|
+
Behaviour changes that need no code change but are worth knowing:
|
|
253
|
+
|
|
254
|
+
- Refund `amount` is carried as `Money` end to end; a partial refund must use
|
|
255
|
+
the charge's **settlement** currency (Bachs rejects it otherwise, and the SDK
|
|
256
|
+
now refuses locally).
|
|
257
|
+
- Paystack payout references must be 16-50 characters of `[a-z0-9-_]`; the SDK
|
|
258
|
+
validates before sending.
|
|
259
|
+
- `config.retry` and `config.http` now take effect, and invalid values throw.
|
|
260
|
+
- Provider business failures keep their own error class instead of being
|
|
261
|
+
reported as parse failures.
|
|
262
|
+
|
|
263
|
+
## Testing with Mocks
|
|
264
|
+
|
|
265
|
+
`@theengineerscanvas/payment` ships `MockHttpClient` and `createMockClient()` for
|
|
266
|
+
integration testing without hitting the live provider API.
|
|
267
|
+
|
|
268
|
+
### Basic Mock Setup
|
|
269
|
+
|
|
270
|
+
```ts
|
|
271
|
+
import { createMockClient, Money, PaymentReference } from "@theengineerscanvas/payment";
|
|
272
|
+
|
|
273
|
+
const { client, http } = createMockClient();
|
|
274
|
+
|
|
275
|
+
// Seed the mock with expected responses
|
|
276
|
+
http.on("POST", "transaction/initialize", {
|
|
277
|
+
status: 200,
|
|
278
|
+
body: JSON.stringify({
|
|
279
|
+
status: true,
|
|
280
|
+
message: "Authorization URL created",
|
|
281
|
+
data: {
|
|
282
|
+
authorization_url: "https://checkout.paystack.com/test",
|
|
283
|
+
access_code: "ACC_mock",
|
|
284
|
+
reference: "order-001",
|
|
285
|
+
},
|
|
286
|
+
}),
|
|
287
|
+
});
|
|
288
|
+
|
|
289
|
+
http.on("GET", "transaction/verify", {
|
|
290
|
+
status: 200,
|
|
291
|
+
body: JSON.stringify({
|
|
292
|
+
status: true,
|
|
293
|
+
message: "Verification successful",
|
|
294
|
+
data: {
|
|
295
|
+
id: 9999,
|
|
296
|
+
status: "success",
|
|
297
|
+
reference: "order-001",
|
|
298
|
+
amount: 500000,
|
|
299
|
+
currency: "NGN",
|
|
300
|
+
channel: "card",
|
|
301
|
+
paid_at: "2026-07-20T10:00:00.000Z",
|
|
302
|
+
created_at: "2026-07-20T09:55:00.000Z",
|
|
303
|
+
updated_at: "2026-07-20T10:00:00.000Z",
|
|
304
|
+
customer: { id: 1, email: "test@example.com" },
|
|
305
|
+
authorization: null,
|
|
306
|
+
gateway_response: "Successful",
|
|
307
|
+
metadata: null,
|
|
308
|
+
fees: 7500,
|
|
309
|
+
fees_split: null,
|
|
310
|
+
},
|
|
311
|
+
}),
|
|
312
|
+
});
|
|
313
|
+
|
|
314
|
+
// Use the client normally — it hits the mock instead of Paystack
|
|
315
|
+
const result = await client.payments.initialize({
|
|
316
|
+
amount: Money({ amount: 500000, currency: "NGN" }),
|
|
317
|
+
reference: PaymentReference("order-001"),
|
|
318
|
+
customer: { kind: "new", email: "test@example.com" },
|
|
319
|
+
});
|
|
320
|
+
|
|
321
|
+
expect(result.ok).toBe(true);
|
|
322
|
+
```
|
|
323
|
+
|
|
324
|
+
### Inspecting Requests
|
|
325
|
+
|
|
326
|
+
```ts
|
|
327
|
+
// Verify the mock received expected requests
|
|
328
|
+
const requests = http.getRequests();
|
|
329
|
+
expect(requests).toHaveLength(1);
|
|
330
|
+
expect(requests[0].method).toBe("POST");
|
|
331
|
+
expect(requests[0].url).toContain("transaction/initialize");
|
|
332
|
+
|
|
333
|
+
// Reset between tests
|
|
334
|
+
http.reset();
|
|
335
|
+
```
|
|
336
|
+
|
|
337
|
+
### Webhook Testing
|
|
338
|
+
|
|
339
|
+
```ts
|
|
340
|
+
import { createHmac } from "crypto";
|
|
341
|
+
|
|
342
|
+
const secret = "whsec_mock";
|
|
343
|
+
const { client } = createMockClient({ webhookSecret: secret });
|
|
344
|
+
|
|
345
|
+
const payload = JSON.stringify({
|
|
346
|
+
event: "charge.success",
|
|
347
|
+
data: {
|
|
348
|
+
id: 9999,
|
|
349
|
+
status: "success",
|
|
350
|
+
reference: "order-001",
|
|
351
|
+
amount: 500000,
|
|
352
|
+
currency: "NGN",
|
|
353
|
+
channel: "card",
|
|
354
|
+
customer: { id: 1, email: "test@example.com" },
|
|
355
|
+
paid_at: "2026-07-20T10:00:00.000Z",
|
|
356
|
+
created_at: "2026-07-20T09:55:00.000Z",
|
|
357
|
+
updated_at: "2026-07-20T10:00:00.000Z",
|
|
358
|
+
authorization: null,
|
|
359
|
+
gateway_response: "Successful",
|
|
360
|
+
metadata: null,
|
|
361
|
+
fees: null,
|
|
362
|
+
fees_split: null,
|
|
363
|
+
},
|
|
364
|
+
});
|
|
365
|
+
|
|
366
|
+
const signature = createHmac("sha512", secret).update(payload).digest("hex");
|
|
367
|
+
|
|
368
|
+
const result = await client.webhooks.receive({
|
|
369
|
+
rawBody: payload,
|
|
370
|
+
signature,
|
|
371
|
+
});
|
|
372
|
+
|
|
373
|
+
expect(result.ok).toBe(true);
|
|
374
|
+
expect(result.value.type).toBe("payment.succeeded");
|
|
375
|
+
```
|
|
376
|
+
|
|
377
|
+
### NestJS Integration Tests
|
|
378
|
+
|
|
379
|
+
```ts
|
|
380
|
+
import { Test } from "@nestjs/testing";
|
|
381
|
+
import { createMockClient } from "@theengineerscanvas/payment";
|
|
382
|
+
|
|
383
|
+
const { client, http } = createMockClient();
|
|
384
|
+
|
|
385
|
+
const module = await Test.createTestingModule({
|
|
386
|
+
providers: [
|
|
387
|
+
{ provide: "PAYMENT_CLIENT", useValue: client },
|
|
388
|
+
// ... your service that depends on PAYMENT_CLIENT
|
|
389
|
+
],
|
|
390
|
+
}).compile();
|
|
391
|
+
```
|
|
392
|
+
|
|
393
|
+
### Chaining Responses
|
|
394
|
+
|
|
395
|
+
```ts
|
|
396
|
+
http
|
|
397
|
+
.on("POST", "initialize", { status: 200, body: JSON.stringify({ ... }) })
|
|
398
|
+
.on("GET", "verify", { status: 200, body: JSON.stringify({ ... }) });
|
|
399
|
+
```
|
|
400
|
+
|
|
401
|
+
The `on()` method returns `this` for chaining.
|
|
@@ -0,0 +1,86 @@
|
|
|
1
|
+
# Performance
|
|
2
|
+
|
|
3
|
+
Performance characteristics of `@theengineerscanvas/payment`.
|
|
4
|
+
|
|
5
|
+
## Zero-Overhead Design
|
|
6
|
+
|
|
7
|
+
The SDK introduces no middleware pipeline, no proxy layer, no serialization overhead beyond what the provider's HTTP API requires:
|
|
8
|
+
|
|
9
|
+
```
|
|
10
|
+
App → PaymentService → Use Case → Adapter → fetch() → Provider API
|
|
11
|
+
```
|
|
12
|
+
|
|
13
|
+
Each layer adds minimal overhead — the hot path (initialize → verify) involves exactly one function call per layer before hitting the HTTP client.
|
|
14
|
+
|
|
15
|
+
## HTTP Client Performance
|
|
16
|
+
|
|
17
|
+
- Uses native `fetch()` (Node 18+, Bun). No `axios`, no `undici`, no `got`.
|
|
18
|
+
- Connection reuse via HTTP keep-alive (runtime default).
|
|
19
|
+
- Timeout via `AbortController` (configurable, default 30s).
|
|
20
|
+
- One automatic retry on idempotent GETs (500ms fixed delay). No exponential backoff ladder in v1.
|
|
21
|
+
|
|
22
|
+
## Memory Profile
|
|
23
|
+
|
|
24
|
+
- **Stateless.** The SDK owns no database connections, no connection pools, no caches. All memory is stack-local to a single request.
|
|
25
|
+
- **Event bus is in-process.** Handlers run synchronously in the same event loop tick. No queue buffers, no persisted events.
|
|
26
|
+
- **No module-level mutable state.** `createPaymentClient()` returns a frozen object graph.
|
|
27
|
+
|
|
28
|
+
## Cold Start
|
|
29
|
+
|
|
30
|
+
- `createPaymentClient()` initializes in ~1ms (config validation, object construction).
|
|
31
|
+
- First API call adds ~50ms for DNS resolution + TLS handshake (cached by runtime).
|
|
32
|
+
- Subsequent calls reuse the warm connection.
|
|
33
|
+
|
|
34
|
+
## Hot Path — Initialize → Verify
|
|
35
|
+
|
|
36
|
+
```
|
|
37
|
+
initializePayment:
|
|
38
|
+
~0.5ms validate branded types
|
|
39
|
+
~0.3ms adapter maps domain → provider DTO
|
|
40
|
+
~1.0ms JSON.stringify request body
|
|
41
|
+
~200ms Paystack POST /transaction/initialize (network)
|
|
42
|
+
~0.5ms JSON.parse response, map to Payment
|
|
43
|
+
~0.1ms emit event
|
|
44
|
+
Total: ~203ms (200ms is network, ~3ms is SDK)
|
|
45
|
+
|
|
46
|
+
verifyPayment:
|
|
47
|
+
~0.1ms validate PaymentReference
|
|
48
|
+
~150ms Paystack GET /transaction/verify/:ref (network)
|
|
49
|
+
~0.5ms JSON.parse response, map to Payment
|
|
50
|
+
Total: ~151ms (150ms is network, ~1ms is SDK)
|
|
51
|
+
```
|
|
52
|
+
|
|
53
|
+
**The bottleneck is the provider API, not the SDK.**
|
|
54
|
+
|
|
55
|
+
## Webhook Path
|
|
56
|
+
|
|
57
|
+
```
|
|
58
|
+
~0.1ms Buffer → string conversion (if Buffer)
|
|
59
|
+
~0.2ms HMAC-SHA512 computation (per provider's signing algorithm)
|
|
60
|
+
~0.1ms crypto.timingSafeEqual comparison
|
|
61
|
+
~0.5ms JSON.parse webhook body
|
|
62
|
+
~0.3ms map to normalized WebhookEvent
|
|
63
|
+
~0.1ms emit event
|
|
64
|
+
Total: ~1.3ms
|
|
65
|
+
```
|
|
66
|
+
|
|
67
|
+
Webhook processing is sub-millisecond once HMAC is computed.
|
|
68
|
+
|
|
69
|
+
## Bundle Size
|
|
70
|
+
|
|
71
|
+
Zero runtime dependencies. Published size:
|
|
72
|
+
|
|
73
|
+
- ESM: ~44 KB
|
|
74
|
+
- CJS: ~45 KB
|
|
75
|
+
- Gzipped: ~15 KB
|
|
76
|
+
- Type declarations: ~21 KB
|
|
77
|
+
|
|
78
|
+
## When to NOT Optimize
|
|
79
|
+
|
|
80
|
+
The SDK is **not the bottleneck**. If you're seeing latency in payment flows:
|
|
81
|
+
|
|
82
|
+
1. Check provider API latency (Paystack, Stripe — 100-300ms is normal).
|
|
83
|
+
2. Check your database queries (inserting a payment record should be single-digit ms).
|
|
84
|
+
3. Check your event handlers (a slow `payment.succeeded` subscriber blocks subsequent handlers).
|
|
85
|
+
|
|
86
|
+
Do not parallelize provider calls — the API enforces ordering (verify must happen after initialize). If you need to process without user wait, use the event system.
|
|
@@ -0,0 +1,150 @@
|
|
|
1
|
+
# Provider Guide
|
|
2
|
+
|
|
3
|
+
A focused guide on implementing a new payment provider adapter for `@theengineerscanvas/payment`.
|
|
4
|
+
|
|
5
|
+
## Provider Contract Checklist
|
|
6
|
+
|
|
7
|
+
| Method | Required | HTTP Method | Notes |
|
|
8
|
+
|--------|----------|-------------|-------|
|
|
9
|
+
| `initialize` | Yes | POST | Create payment, return authorization URL |
|
|
10
|
+
| `verify` | Yes | GET | Confirm payment by reference |
|
|
11
|
+
| `fetch` | Yes | GET | Look up by provider-assigned ID |
|
|
12
|
+
| `list` | Yes | GET | Paginated list with filters |
|
|
13
|
+
| `refund` | Yes | POST | Full or partial refund |
|
|
14
|
+
| `parseWebhook` | Yes | — | Signature verify + event normalize |
|
|
15
|
+
| `fetchRefund` | No | GET | Fetch specific refund by ID |
|
|
16
|
+
| `health` | Yes | — | Liveness check |
|
|
17
|
+
|
|
18
|
+
## Provider Capabilities
|
|
19
|
+
|
|
20
|
+
```ts
|
|
21
|
+
interface ProviderCapabilities {
|
|
22
|
+
readonly supportsAuthorizationUrl: boolean; // redirect-based flows
|
|
23
|
+
readonly supportsRecurring: boolean; // reserved for v2
|
|
24
|
+
readonly supportsPartialRefund: boolean; // refunds less than full amount
|
|
25
|
+
readonly supportsWebhooks: boolean; // provider sends webhooks
|
|
26
|
+
readonly maxAmount?: Money; // max transaction amount
|
|
27
|
+
readonly supportedCurrencies: ReadonlyArray<Currency>;
|
|
28
|
+
readonly supportedChannels: ReadonlyArray<PaymentChannel>;
|
|
29
|
+
}
|
|
30
|
+
```
|
|
31
|
+
|
|
32
|
+
## Money Mapping
|
|
33
|
+
|
|
34
|
+
All amounts in the SDK are in **minor units** (kobo/cents). Map provider amounts directly:
|
|
35
|
+
|
|
36
|
+
```ts
|
|
37
|
+
// Paystack: amount is in kobo
|
|
38
|
+
amount: Money({ amount: data.amount, currency: data.currency })
|
|
39
|
+
|
|
40
|
+
// Stripe: amount is in cents
|
|
41
|
+
amount: Money({ amount: data.amount, currency: data.currency.toUpperCase() })
|
|
42
|
+
|
|
43
|
+
// Bachs: amount is a decimal string in major units ("29.00") and must be
|
|
44
|
+
// converted at the adapter boundary, never with floating point maths.
|
|
45
|
+
amount: fromBachsAmount(data.amount, data.currency) // "29.00" -> 2900
|
|
46
|
+
amount: toBachsAmount(Money({ amount: 2900, currency: "USD" })) // -> "29.00"
|
|
47
|
+
```
|
|
48
|
+
|
|
49
|
+
## Status Mapping
|
|
50
|
+
|
|
51
|
+
Map provider-specific statuses to `PaymentStatus`:
|
|
52
|
+
|
|
53
|
+
```ts
|
|
54
|
+
type PaymentStatus =
|
|
55
|
+
| { kind: "initialized" }
|
|
56
|
+
| { kind: "pending" }
|
|
57
|
+
| { kind: "success"; paidAt: Date }
|
|
58
|
+
| { kind: "failed"; reason: string; failedAt: Date }
|
|
59
|
+
| { kind: "abandoned" }
|
|
60
|
+
| { kind: "refunded"; refundedAt: Date; refundId: string };
|
|
61
|
+
```
|
|
62
|
+
|
|
63
|
+
| Paystack | Stripe | Domain |
|
|
64
|
+
|----------|--------|--------|
|
|
65
|
+
| `"abandoned"` | `"canceled"` | `"abandoned"` |
|
|
66
|
+
| `"ongoing"` | `"requires_payment_method"` | `"pending"` |
|
|
67
|
+
| `"success"` | `"succeeded"` | `"success"` |
|
|
68
|
+
| `"failed"` | `"payment_failed"` | `"failed"` |
|
|
69
|
+
|
|
70
|
+
## Webhook Mechanics
|
|
71
|
+
|
|
72
|
+
### Signature Verification
|
|
73
|
+
|
|
74
|
+
Each provider signs webhooks differently:
|
|
75
|
+
|
|
76
|
+
| Provider | Header | Algorithm |
|
|
77
|
+
|----------|--------|-----------|
|
|
78
|
+
| Paystack | `x-paystack-signature` | HMAC-SHA512 (hex) |
|
|
79
|
+
| Stripe | `stripe-signature` | HMAC-SHA256, `t=timestamp,v1=mac` |
|
|
80
|
+
| Bachs | `x-bachs-signature-v2` (preferred) or `x-bachs-signature` + `x-bachs-timestamp` | HMAC-SHA256 (hex) over `"{timestamp}.{rawBody}"`; V2 may carry several `v1=` during secret rotation — accept any match; reject timestamps outside the tolerance (300 s default) |
|
|
81
|
+
|
|
82
|
+
Use the `WebhookVerifier` port or implement provider-specific logic in the adapter's `parseWebhook` method.
|
|
83
|
+
|
|
84
|
+
### Event Normalization
|
|
85
|
+
|
|
86
|
+
Map provider event types to normalized ones:
|
|
87
|
+
|
|
88
|
+
```ts
|
|
89
|
+
type WebhookEventType =
|
|
90
|
+
| "payment.initialized" | "payment.pending"
|
|
91
|
+
| "payment.succeeded" | "payment.failed"
|
|
92
|
+
| "refund.initiated" | "refund.succeeded" | "refund.failed"
|
|
93
|
+
| "unknown";
|
|
94
|
+
```
|
|
95
|
+
|
|
96
|
+
## Error Mapping
|
|
97
|
+
|
|
98
|
+
Map provider error responses to `ProviderError` subclasses:
|
|
99
|
+
|
|
100
|
+
| Provider Response | Domain Error |
|
|
101
|
+
|-------------------|--------------|
|
|
102
|
+
| HTTP 400 | `ProviderBadRequestError` |
|
|
103
|
+
| HTTP 401/403 | `ProviderUnauthorizedError` |
|
|
104
|
+
| HTTP 404 | `ProviderNotFoundError` |
|
|
105
|
+
| HTTP 409 | `ProviderConflictError` |
|
|
106
|
+
| HTTP 429 | `ProviderRateLimitError` |
|
|
107
|
+
| HTTP 5xx | `ProviderUnavailableError` |
|
|
108
|
+
| Network error | `NetworkError` |
|
|
109
|
+
| Timeout | `TimeoutError` |
|
|
110
|
+
|
|
111
|
+
## References Format
|
|
112
|
+
|
|
113
|
+
Each provider has constraints on the payment reference:
|
|
114
|
+
|
|
115
|
+
| Provider | Format | Max Length |
|
|
116
|
+
|----------|--------|------------|
|
|
117
|
+
| Paystack | `[A-Za-z0-9._=,+\-]` | 100 chars |
|
|
118
|
+
| Stripe | `[a-zA-Z0-9_]` | 500 chars |
|
|
119
|
+
|
|
120
|
+
The SDK validates references with a generic regex (`[A-Za-z0-9._=,+\-]`, 6-100 chars). Provider-specific validation happens at the API, not the SDK.
|
|
121
|
+
|
|
122
|
+
## Testing
|
|
123
|
+
|
|
124
|
+
Run the contract test suite against your adapter:
|
|
125
|
+
|
|
126
|
+
```bash
|
|
127
|
+
bun run test -- tests/contract/provider-contract.spec.ts
|
|
128
|
+
```
|
|
129
|
+
|
|
130
|
+
## Paystack Reference Implementation
|
|
131
|
+
|
|
132
|
+
See `src/infrastructure/providers/paystack/` for the complete reference implementation:
|
|
133
|
+
|
|
134
|
+
- `paystack-adapter.ts` — Full adapter
|
|
135
|
+
- `paystack-types.ts` — API DTOs
|
|
136
|
+
- `paystack-mapper.ts` — DTO → domain mapping
|
|
137
|
+
- `paystack-webhook.ts` — Signature verification and parsing
|
|
138
|
+
- `register.ts` — Provider registration
|
|
139
|
+
|
|
140
|
+
## Bachs Reference Implementation
|
|
141
|
+
|
|
142
|
+
See `src/infrastructure/providers/bachs/` for a second reference, useful when a provider
|
|
143
|
+
differs from Paystack in ways that matter:
|
|
144
|
+
|
|
145
|
+
- `bachs-money.ts` — exact minor-units ⇄ major-unit decimal-string conversion (never floats)
|
|
146
|
+
- `bachs-webhook.ts` — multi-signature (rotation) HMAC verification with a replay window
|
|
147
|
+
- `bachs-adapter.ts` — id-prefix dispatch in `verify()`, charge pre-read before refunding, payouts mapped onto the transfers port
|
|
148
|
+
- `register.ts` — Provider registration; the sandbox host is derived from the API key prefix
|
|
149
|
+
|
|
150
|
+
Integration guide for consumers: `docs/bachs-guide.md`.
|