pycer-sdk 0.0.0-stage → 1.0.3

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/README.md CHANGED
@@ -1,3 +1,901 @@
1
- # Temporary Holding Version
1
+ # Pycer SDK
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ [![npm version](https://img.shields.io/npm/v/pycer-sdk)](https://www.npmjs.com/package/pycer-sdk)
4
+ [![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT)
5
+ [![Node.js Version](https://img.shields.io/badge/node-%3E%3D18.0.0-brightgreen)](https://nodejs.org/)
6
+
7
+ Official Node.js SDK for Pycer Pay. A TypeScript SDK with zero runtime dependencies.
8
+
9
+ ## Features
10
+
11
+ - 🚀 **Zero Dependencies** - Uses only Node.js native APIs (fetch, crypto)
12
+ - 📘 **TypeScript First** - Full type safety with comprehensive type definitions
13
+ - 🔄 **ESM + CJS** - Supports both ES Modules and CommonJS
14
+ - 🌲 **Tree-Shakeable** - Import only what you need
15
+ - 🔒 **Secure** - Built-in webhook signature verification with HMAC-SHA256
16
+ - ⚡ **High Performance** - Native fetch API with automatic retries
17
+ - 🛡️ **Error Handling** - Comprehensive error hierarchy for easy debugging
18
+ - 📝 **Idempotency** - Built-in support for safe request retries
19
+
20
+ ## Requirements
21
+
22
+ - Node.js 18.0.0 or higher
23
+ - An OwnPay API key (starts with `op_`)
24
+
25
+ ## Installation
26
+
27
+ ```bash
28
+ npm install pycer-sdk
29
+ ```
30
+
31
+ ```bash
32
+ yarn add pycer-sdk
33
+ ```
34
+
35
+ ```bash
36
+ pnpm add pycer-sdk
37
+ ```
38
+
39
+ ## Quick Start
40
+
41
+ ### Initialize the client
42
+
43
+ Set these variables in your backend environment. If using a `.env` file, load it before initializing the SDK.
44
+
45
+ ```dotenv
46
+ PYCER_API_KEY=op_REPLACE_WITH_YOUR_MERCHANT_API_KEY
47
+ PYCER_ENV=sandbox
48
+ ```
49
+
50
+ ```typescript
51
+ import Pycer from 'pycer-sdk';
52
+
53
+ const client = new Pycer();
54
+ ```
55
+
56
+ Sandbox and production both default to `https://pycer.quantivogroup.com`.
57
+ Enable Sandbox Mode for the payment gateway in the portal before making test
58
+ payments. `PYCER_ENV` chooses SDK endpoint settings. The portal controls whether
59
+ payments use the sandbox.
60
+
61
+ Override the URL with `baseUrl`, `PYCER_SANDBOX_BASE_URL` or
62
+ `PYCER_PRODUCTION_BASE_URL`, or the shared `PYCER_BASE_URL`. The legacy
63
+ `OWNPAY_BASE_URL` remains a fallback. Set `checkoutBaseUrl` for a separate
64
+ public checkout host. You can also pass `apiKey` and `environment` explicitly.
65
+
66
+ ### Initiate a rail payment
67
+
68
+ ```typescript
69
+ const payment = await client.payments.create({
70
+ amount: '100.00',
71
+ currency: 'KES',
72
+ preferredRail: 'SAFARICOM_MPESA',
73
+ partyA: { phone: '+254712345678' },
74
+ partyB: { umid: merchantUmid },
75
+ reference: orderReference,
76
+ });
77
+
78
+ const current = await client.payments.get(payment.transactionId);
79
+ ```
80
+
81
+ Use a decimal string for amounts. Supply the actual merchant UMID. Existing switch
82
+ integrations can use `client.switch.charge()` with `customerPhone` and `merchantUmid`.
83
+ Payment initiation returns the rail result and `transactionId`. For integrations
84
+ migrating from the old flat checkout payload, hosted checkout needs a separate
85
+ session creation contract. Automatic retries apply to GET requests.
86
+
87
+ ### Merchant resources
88
+
89
+ `client.merchant` provides disbursement, payout methods, settlement policy and sweep,
90
+ customer payment methods, merchant payment wallets, account references, commerce,
91
+ and terminals. These operations require the corresponding OwnPay scopes.
92
+
93
+ ### Hosted checkout and vaulted cards
94
+
95
+ Use `client.checkout.create({ amount: '100.00', currency: 'KES' })` to create a session. Redirect the browser to the returned `checkoutUrl` and query `client.checkout.get(session.id)` from your server. Use `client.checkout.url(token)` for an OwnPay-issued payment intent token.
96
+ Pass `'legacy'` as the second argument for a legacy checkout token. Send the
97
+ returned URL to the customer as a browser redirect. The checkout status route
98
+ renders a browser page. Use a confirmed merchant transaction ID with
99
+ `client.payments.get()` for API verification after checkout.
100
+
101
+ Use `client.cards.vault(customerId, { gatewayToken, provider: "stripe", gatewayCustomerId })` to save a Stripe PaymentMethod
102
+ issued by your configured gateway. Use `cards.list(customerId)`,
103
+ `cards.setDefault(customerId, methodId)` and `cards.revoke(customerId, methodId)`
104
+ for the resulting OwnPay card record. Card vaulting and direct card charging
105
+ are separate operations.
106
+
107
+ Call `client.cards.charge({ paymentMethodId, amount, currency, reference })`
108
+ with the OwnPay vault record ID. The Stripe PaymentMethod must be attached
109
+ to the supplied Stripe customer and set up for off-session use with consent.
110
+ Reuse the same merchant reference after an ambiguous outcome. Only
111
+ `completed` confirms booking in OwnPay. If Stripe requires customer action,
112
+ use a customer-present checkout flow after resolving the original intent.
113
+
114
+ | Capability | OwnPay route availability |
115
+ | --- | --- |
116
+ | Create hosted checkout session | Use the merchant checkout sessions API through APISIX. |
117
+ | Direct card charge | Charge an eligible vaulted Stripe card through `POST /ownpay/api/v1/cards/charges`. |
118
+ | Dedicated virtual accounts | Provision a Fineract CASA account with `client.merchant.virtualAccounts.provision({ reference, currency })`. Keep the reference stable for retries. List existing accounts with `client.merchant.virtualAccounts.list()`. Deposit simulation is an admin operation. |
119
+ | Merchant float | Use `client.merchant.float(currency)` to read the merchant working ledger balance for that currency. |
120
+
121
+ Pycer sandbox mode is enabled per gateway in the portal. Live checks require
122
+ the sandbox-enabled merchant URL and scoped key, a disposable customer, and
123
+ an issued checkout token or provider test card token for the relevant flow.
124
+
125
+ ### Platform services
126
+
127
+ Import `Billing`, `Notifications`, `Banking`, `ForeignExchange`, or `DeveloperTools`
128
+ from `pycer-sdk`. Instantiate each with its own `{ baseUrl, token }`. The base
129
+ URL precedes the `/api/v1` prefix. Use the corresponding service OpenAPI for request
130
+ fields and deployment scopes.
131
+
132
+ ## API Reference
133
+
134
+ ### Transactions
135
+
136
+ #### `client.transactions.list(params?, options?)`
137
+
138
+ Lists transactions with optional filtering and pagination.
139
+
140
+ **Parameters:**
141
+
142
+ | Parameter | Type | Required | Description |
143
+ |-----------|------|----------|-------------|
144
+ | `page` | `number` | ❌ | Page number (default: 1) |
145
+ | `per_page` | `number` | ❌ | Items per page (default: 25, max: 100) |
146
+ | `status` | `string` | ❌ | Filter by status |
147
+ | `gateway` | `string` | ❌ | Filter by gateway |
148
+ | `from` | `string` | ❌ | Start date (ISO format) |
149
+ | `to` | `string` | ❌ | End date (ISO format) |
150
+
151
+ **Returns:** `Promise<PaginatedList<Transaction>>`
152
+
153
+ ```typescript
154
+ const result = await client.transactions.list({
155
+ page: 1,
156
+ per_page: 50,
157
+ status: 'completed',
158
+ from: '2024-01-01',
159
+ to: '2024-01-31',
160
+ });
161
+
162
+ console.log('Transactions:', result.items);
163
+ console.log('Total:', result.meta.total);
164
+ console.log('Pages:', result.meta.total_pages);
165
+ ```
166
+
167
+ #### `client.transactions.get(trxId, options?)`
168
+
169
+ Retrieves a transaction by ID (OwnPay reference or gateway ID).
170
+
171
+ **Parameters:**
172
+
173
+ | Parameter | Type | Required | Description |
174
+ |-----------|------|----------|-------------|
175
+ | `trxId` | `string` | ✅ | Transaction ID (e.g., 'OP-ABC123') |
176
+
177
+ **Returns:** `Promise<Transaction>`
178
+
179
+ ---
180
+
181
+ ### Refunds
182
+
183
+ #### `client.refunds.create(params, options?)`
184
+
185
+ Creates a refund for a transaction.
186
+
187
+ **Parameters:**
188
+
189
+ | Parameter | Type | Required | Description |
190
+ |-----------|------|----------|-------------|
191
+ | `transaction_id` | `string \| number` | ✅* | Transaction ID |
192
+ | `trx_id` | `string \| number` | ✅* | OwnPay transaction reference |
193
+ | `amount` | `string \| number` | ❌ | Refund amount (partial refund) |
194
+ | `reason` | `string` | ❌ | Refund reason |
195
+
196
+ *Either `transaction_id` or `trx_id` is required
197
+
198
+ **Returns:** `Promise<Refund>`
199
+
200
+ ```typescript
201
+ // Full refund
202
+ const refund = await client.refunds.create({
203
+ transaction_id: 'OP-ABC123',
204
+ reason: 'Customer request',
205
+ });
206
+
207
+ // Partial refund
208
+ const refund = await client.refunds.create({
209
+ transaction_id: 'OP-ABC123',
210
+ amount: '50.00',
211
+ reason: 'Partial return',
212
+ });
213
+ ```
214
+
215
+ #### `client.refunds.list(params?, options?)`
216
+
217
+ Lists refunds with optional filtering.
218
+
219
+ **Returns:** `Promise<PaginatedList<Refund>>`
220
+
221
+ #### `client.refunds.get(trxId, options?)`
222
+
223
+ Retrieves refund details by transaction reference.
224
+
225
+ **Returns:** `Promise<Refund>`
226
+
227
+ ---
228
+
229
+ ### Customers
230
+
231
+ #### `client.customers.create(params, options?)`
232
+
233
+ Creates a new customer.
234
+
235
+ **Parameters:**
236
+
237
+ | Parameter | Type | Required | Description |
238
+ |-----------|------|----------|-------------|
239
+ | `name` | `string` | ✅ | Customer name (max 150 chars) |
240
+ | `email` | `string` | ❌ | Email address |
241
+ | `phone` | `string` | ❌ | Phone number |
242
+
243
+ **Returns:** `Promise<{ id: number; uuid: string }>`
244
+
245
+ ```typescript
246
+ const customer = await client.customers.create({
247
+ name: 'Jane Smith',
248
+ email: 'jane@example.com',
249
+ phone: '+8801712345678',
250
+ });
251
+
252
+ console.log('Customer ID:', customer.id);
253
+ console.log('Customer UUID:', customer.uuid);
254
+ ```
255
+
256
+ #### `client.customers.list(params?, options?)`
257
+
258
+ Lists customers with pagination.
259
+
260
+ **Returns:** `Promise<PaginatedList<Customer>>`
261
+
262
+ #### `client.customers.get(identifier, options?)`
263
+
264
+ Retrieves a customer by email or phone.
265
+
266
+ **Parameters:**
267
+
268
+ | Parameter | Type | Required | Description |
269
+ |-----------|------|----------|-------------|
270
+ | `identifier` | `string` | ✅ | Email or phone number |
271
+
272
+ **Returns:** `Promise<Customer>`
273
+
274
+ ```typescript
275
+ // By email
276
+ const customer = await client.customers.get('jane@example.com');
277
+
278
+ // By phone
279
+ const customer = await client.customers.get('+8801712345678');
280
+ ```
281
+
282
+ ---
283
+
284
+ ### API Keys
285
+
286
+ > **Note:** API key operations require an API key with both `write` and `admin` scopes, and must include the `X-Super-Admin-Email` header.
287
+
288
+ #### `client.apiKeys.list(options?)`
289
+
290
+ Lists all API keys for the merchant.
291
+
292
+ **Returns:** `Promise<ApiKey[]>`
293
+
294
+ ```typescript
295
+ const keys = await client.apiKeys.list({
296
+ headers: { 'X-Super-Admin-Email': 'admin@example.com' },
297
+ });
298
+ ```
299
+
300
+ #### `client.apiKeys.generate(params?, options?)`
301
+
302
+ Generates a new API key.
303
+
304
+ **Parameters:**
305
+
306
+ | Parameter | Type | Required | Description |
307
+ |-----------|------|----------|-------------|
308
+ | `name` | `string` | ❌ | Key name/label |
309
+ | `scopes` | `string[]` | ❌ | Permission scopes: `['read', 'write', 'admin']` |
310
+
311
+ **Returns:** `Promise<GeneratedApiKey>`
312
+
313
+ ```typescript
314
+ const result = await client.apiKeys.generate(
315
+ {
316
+ name: 'Production Key',
317
+ scopes: ['read', 'write'],
318
+ },
319
+ {
320
+ headers: { 'X-Super-Admin-Email': 'admin@example.com' },
321
+ }
322
+ );
323
+
324
+ // IMPORTANT: Store this key securely! It cannot be retrieved again.
325
+ console.log('New API Key:', result.key);
326
+ console.log('Warning:', result.warning);
327
+ ```
328
+
329
+ #### `client.apiKeys.revoke(keyId, options?)`
330
+
331
+ Revokes an API key.
332
+
333
+ **Parameters:**
334
+
335
+ | Parameter | Type | Required | Description |
336
+ |-----------|------|----------|-------------|
337
+ | `keyId` | `number` | ✅ | API key ID to revoke |
338
+
339
+ ---
340
+
341
+ ### Webhooks
342
+
343
+ #### `client.webhooks.test(options?)`
344
+
345
+ Sends a test webhook to the configured endpoint.
346
+
347
+ **Returns:** `Promise<WebhookTestResult>`
348
+
349
+ ```typescript
350
+ const result = await client.webhooks.test();
351
+ console.log('Status Code:', result.status_code);
352
+ console.log('Response Time:', result.response_time_ms, 'ms');
353
+ ```
354
+
355
+ #### `client.webhooks.deliveries(options?)`
356
+
357
+ Lists recent webhook deliveries.
358
+
359
+ **Returns:** `Promise<WebhookDelivery[]>`
360
+
361
+ ---
362
+
363
+ ### Health
364
+
365
+ #### `client.health.check(options?)`
366
+
367
+ Performs a system health check.
368
+
369
+ **Returns:** `Promise<HealthStatus>`
370
+
371
+ ```typescript
372
+ const health = await client.health.check();
373
+
374
+ console.log('Status:', health.status); // 'healthy' or 'degraded'
375
+ console.log('Version:', health.version);
376
+ console.log('Database:', health.db); // 'connected' or 'error'
377
+ console.log('Gateways:', health.gateways);
378
+ console.log('Customers:', health.customers);
379
+ ```
380
+
381
+ ---
382
+
383
+ ## Webhook Handling
384
+
385
+ ### Verify Webhook Signatures
386
+
387
+ Always verify webhook signatures to ensure payloads are from OwnPay.
388
+
389
+ ```typescript
390
+ import { verifyWebhookSignature } from 'pycer-sdk/webhooks';
391
+
392
+ // Express.js example
393
+ app.post('/webhook', express.raw({ type: 'application/json' }), (req, res) => {
394
+ try {
395
+ const signature = req.headers['x-signature'];
396
+ const timestamp = req.headers['x-timestamp'];
397
+ const payload = req.body; // Raw body (string or Buffer)
398
+
399
+ verifyWebhookSignature({
400
+ payload,
401
+ signature,
402
+ secret: process.env.OWNPAY_WEBHOOK_SECRET,
403
+ timestamp,
404
+ tolerance: 300, // 5 minutes (default)
405
+ });
406
+
407
+ // Signature is valid, process the event
408
+ const event = JSON.parse(payload.toString('utf8'));
409
+ handleWebhookEvent(event);
410
+
411
+ res.status(200).json({ received: true });
412
+ } catch (error) {
413
+ console.error('Webhook verification failed:', error.message);
414
+ res.status(400).json({ error: 'Invalid signature' });
415
+ }
416
+ });
417
+ ```
418
+
419
+ ### Webhook Event Structure
420
+
421
+ ```typescript
422
+ interface WebhookPayload {
423
+ event: string; // e.g., 'payment.completed'
424
+ transaction_id: string; // OwnPay transaction reference
425
+ gateway_trx_id: string; // Gateway transaction ID
426
+ amount: string; // Transaction amount
427
+ currency: string; // Currency code
428
+ fee: string; // Processing fee
429
+ gateway: string; // Gateway slug
430
+ gateway_type: string; // Gateway type
431
+ status: string; // Transaction status
432
+ customer: {
433
+ name: string;
434
+ email: string;
435
+ phone: string;
436
+ };
437
+ metadata: Record<string, unknown>;
438
+ timestamp: string; // ISO timestamp
439
+ }
440
+ ```
441
+
442
+ ### Handle Different Event Types
443
+
444
+ ```typescript
445
+ function handleWebhookEvent(event: WebhookPayload) {
446
+ switch (event.event) {
447
+ case 'payment.completed':
448
+ console.log(`Payment ${event.transaction_id} completed`);
449
+ // Fulfill order, send confirmation email, etc.
450
+ break;
451
+
452
+ case 'payment.failed':
453
+ console.log(`Payment ${event.transaction_id} failed`);
454
+ // Notify customer, retry logic, etc.
455
+ break;
456
+
457
+ case 'refund.completed':
458
+ console.log(`Refund for ${event.transaction_id} completed`);
459
+ // Update records, notify customer
460
+ break;
461
+
462
+ default:
463
+ console.log(`Unhandled event: ${event.event}`);
464
+ }
465
+ }
466
+ ```
467
+
468
+ ---
469
+
470
+ ## Error Handling
471
+
472
+ The SDK provides a comprehensive error hierarchy for precise error handling.
473
+
474
+ ```typescript
475
+ import OwnPay, {
476
+ AuthenticationError,
477
+ PermissionError,
478
+ NotFoundError,
479
+ ValidationError,
480
+ RateLimitError,
481
+ IdempotencyError,
482
+ ApiError,
483
+ NetworkError,
484
+ AbortError,
485
+ } from 'pycer-sdk';
486
+
487
+ try {
488
+ const payment = await client.payments.create({
489
+ amount: '100.00',
490
+ currency: 'KES',
491
+ preferredRail: 'SAFARICOM_MPESA',
492
+ partyA: { phone: '+254712345678' },
493
+ partyB: { umid: merchantUmid },
494
+ });
495
+ } catch (error) {
496
+ if (error instanceof AuthenticationError) {
497
+ // Invalid or revoked API key
498
+ console.error('Authentication failed:', error.message);
499
+ } else if (error instanceof ValidationError) {
500
+ // Invalid parameters
501
+ console.error('Validation failed:', error.message);
502
+ console.error('Field errors:', error.getFieldErrors());
503
+ } else if (error instanceof NotFoundError) {
504
+ // Resource not found
505
+ console.error('Not found:', error.message);
506
+ } else if (error instanceof RateLimitError) {
507
+ // Rate limit exceeded
508
+ console.error(`Rate limited. Retry after ${error.retryAfter} seconds`);
509
+ } else if (error instanceof IdempotencyError) {
510
+ // Duplicate request
511
+ console.error('Idempotency conflict:', error.message);
512
+ } else if (error instanceof ApiError) {
513
+ // Server error (5xx)
514
+ console.error('API error:', error.message, 'Status:', error.status);
515
+ } else if (error instanceof NetworkError) {
516
+ // Connection failure
517
+ console.error('Network error:', error.message);
518
+ } else if (error instanceof AbortError) {
519
+ // Request timeout
520
+ console.error('Request timed out');
521
+ }
522
+ }
523
+ ```
524
+
525
+ ### Error Properties
526
+
527
+ All errors have these common properties:
528
+
529
+ | Property | Type | Description |
530
+ |----------|------|-------------|
531
+ | `message` | `string` | Human-readable error message |
532
+ | `type` | `string` | Error type identifier |
533
+ | `status` | `number` | HTTP status code (if applicable) |
534
+ | `requestId` | `string` | Request ID for debugging |
535
+ | `rawResponse` | `unknown` | Raw API response |
536
+
537
+ ### Validation Errors
538
+
539
+ `ValidationError` provides additional methods:
540
+
541
+ ```typescript
542
+ catch (error) {
543
+ if (error instanceof ValidationError) {
544
+ // Get all errors grouped by field
545
+ const fieldErrors = error.getFieldErrors();
546
+ // { amount: ['Must be positive'], currency: ['Required'] }
547
+
548
+ // Get first error for a specific field
549
+ const amountError = error.getFirstFieldError('amount');
550
+ }
551
+ }
552
+ ```
553
+
554
+ ---
555
+
556
+ ## Request Options
557
+
558
+ All resource methods accept an optional `RequestOptions` parameter:
559
+
560
+ ```typescript
561
+ const payment = await client.payments.create(
562
+ paymentParams,
563
+ {
564
+ // Idempotency key for safe retries
565
+ idempotencyKey: 'unique-key-123',
566
+
567
+ // Custom headers for this request
568
+ headers: {
569
+ 'X-Custom-Header': 'value',
570
+ },
571
+
572
+ // Request timeout override (ms)
573
+ timeout: 60000,
574
+
575
+ // AbortSignal for cancellation
576
+ signal: AbortSignal.timeout(10000),
577
+ }
578
+ );
579
+ ```
580
+
581
+ ### Idempotency
582
+
583
+ Pass `{ idempotencyKey }` to forward `Idempotency-Key` where your OwnPay deployment supports it. Confirm server-side deduplication before repeating a write after an ambiguous outcome.
584
+
585
+ ### Request Cancellation
586
+
587
+ Use `AbortSignal` to cancel long-running requests:
588
+
589
+ ```typescript
590
+ const controller = new AbortController();
591
+
592
+ // Cancel after 5 seconds
593
+ setTimeout(() => controller.abort(), 5000);
594
+
595
+ try {
596
+ const payment = await client.payments.create(
597
+ paymentParams,
598
+ { signal: controller.signal }
599
+ );
600
+ } catch (error) {
601
+ if (error instanceof AbortError) {
602
+ console.log('Request was cancelled');
603
+ }
604
+ }
605
+ ```
606
+
607
+ ---
608
+
609
+ ## Advanced Configuration
610
+
611
+ ### Custom API URL
612
+
613
+ For self-hosted or white-label deployments:
614
+
615
+ ```typescript
616
+ const client = new OwnPay({
617
+ apiKey: 'op_your_key',
618
+ baseUrl: 'https://your-domain.com',
619
+ });
620
+ ```
621
+
622
+ ### Environment Variables
623
+
624
+ Store your API key securely using environment variables:
625
+
626
+ ```typescript
627
+ const client = new OwnPay({
628
+ apiKey: process.env.OWNPAY_API_KEY!,
629
+ baseUrl: process.env.OWNPAY_BASE_URL!,
630
+ });
631
+ ```
632
+
633
+ ### Custom Headers
634
+
635
+ Add custom headers to all requests:
636
+
637
+ ```typescript
638
+ const client = new OwnPay({
639
+ apiKey: 'op_your_key',
640
+ headers: {
641
+ 'X-App-Version': '1.0.0',
642
+ 'X-Client-Id': 'your-app',
643
+ },
644
+ });
645
+ ```
646
+
647
+ ---
648
+
649
+ ## TypeScript Support
650
+
651
+ The SDK is built with TypeScript and provides comprehensive type definitions.
652
+
653
+ ```typescript
654
+ import OwnPay from 'pycer-sdk';
655
+ import type {
656
+ PaymentDetails,
657
+ Transaction,
658
+ Refund,
659
+ Customer,
660
+ WebhookPayload,
661
+ RailPaymentParams,
662
+ ListTransactionsParams,
663
+ } from 'pycer-sdk';
664
+
665
+ // Types are automatically inferred
666
+ const client = new OwnPay({
667
+ apiKey: 'op_key',
668
+ baseUrl: 'https://your-ownpay-domain.com',
669
+ });
670
+ const payment = await client.payments.create({
671
+ amount: '100.00',
672
+ currency: 'KES',
673
+ preferredRail: 'SAFARICOM_MPESA',
674
+ partyA: { phone: '+254712345678' },
675
+ partyB: { umid: merchantUmid },
676
+ });
677
+ // payment is typed as PaymentIntent
678
+ ```
679
+
680
+ ---
681
+
682
+ ## CommonJS Support
683
+
684
+ The SDK supports CommonJS for backward compatibility:
685
+
686
+ ```javascript
687
+ const { OwnPay } = require('pycer-sdk');
688
+
689
+ const client = new OwnPay({
690
+ apiKey: 'op_your_key',
691
+ baseUrl: 'https://your-ownpay-domain.com',
692
+ });
693
+ ```
694
+
695
+ ---
696
+
697
+ ## Tree-Shaking
698
+
699
+ Import only what you need for smaller bundle sizes:
700
+
701
+ ```typescript
702
+ // Import only the client
703
+ import OwnPay from 'pycer-sdk';
704
+
705
+ // Import only webhook utilities
706
+ import { verifyWebhookSignature } from 'pycer-sdk/webhooks';
707
+
708
+ // Import specific types
709
+ import type { Payment, Transaction } from 'pycer-sdk';
710
+
711
+ // Import specific errors
712
+ import { ValidationError, AuthenticationError } from 'pycer-sdk';
713
+ ```
714
+
715
+ ---
716
+
717
+ ## Retry Behavior
718
+
719
+ The transport retries eligible GET failures with bounded attempts. A timed-out write may have reached OwnPay. Check its outcome before submitting another request.
720
+
721
+ ## Examples
722
+
723
+ ### Express.js Webhook Handler
724
+
725
+ ```typescript
726
+ import express from 'express';
727
+ import OwnPay, { verifyWebhookSignature } from 'pycer-sdk';
728
+
729
+ const app = express();
730
+ const client = new OwnPay(process.env.OWNPAY_API_KEY!);
731
+
732
+ // IMPORTANT: Use raw body for webhook verification
733
+ app.post('/webhook', express.raw({ type: 'application/json' }), (req, res) => {
734
+ try {
735
+ const signature = req.headers['x-signature'] as string;
736
+ const timestamp = req.headers['x-timestamp'] as string;
737
+
738
+ // Verify signature
739
+ verifyWebhookSignature({
740
+ payload: req.body,
741
+ signature,
742
+ secret: process.env.OWNPAY_WEBHOOK_SECRET!,
743
+ timestamp,
744
+ });
745
+
746
+ // Parse and handle event
747
+ const event = JSON.parse(req.body.toString());
748
+
749
+ switch (event.event) {
750
+ case 'payment.completed':
751
+ // Update order status, send confirmation, etc.
752
+ console.log(`Payment completed: ${event.transaction_id}`);
753
+ break;
754
+
755
+ case 'payment.failed':
756
+ // Handle failed payment
757
+ console.log(`Payment failed: ${event.transaction_id}`);
758
+ break;
759
+ }
760
+
761
+ res.status(200).json({ received: true });
762
+ } catch (error) {
763
+ console.error('Webhook error:', error);
764
+ res.status(400).json({ error: 'Invalid webhook' });
765
+ }
766
+ });
767
+
768
+ app.listen(3000);
769
+ ```
770
+
771
+ ### Transaction Reporting
772
+
773
+ ```typescript
774
+ async function getTransactionReport(startDate: string, endDate: string) {
775
+ const result = await client.transactions.list({
776
+ from: startDate,
777
+ to: endDate,
778
+ per_page: 100,
779
+ });
780
+
781
+ const totalAmount = result.items.reduce(
782
+ (sum, txn) => sum + parseFloat(txn.amount),
783
+ 0
784
+ );
785
+
786
+ const totalFees = result.items.reduce(
787
+ (sum, txn) => sum + parseFloat(txn.fee),
788
+ 0
789
+ );
790
+
791
+ return {
792
+ transactions: result.items,
793
+ total: result.meta.total,
794
+ totalAmount,
795
+ totalFees,
796
+ netAmount: totalAmount - totalFees,
797
+ };
798
+ }
799
+ ```
800
+
801
+ ---
802
+
803
+ ## Troubleshooting
804
+
805
+ ### Common Issues
806
+
807
+ #### "Invalid API key format"
808
+
809
+ Ensure your API key starts with `op_` and is at least 12 characters long.
810
+
811
+ ```typescript
812
+ // ❌ Wrong
813
+ const client = new OwnPay({
814
+ apiKey: 'sk_live_...',
815
+ baseUrl: 'https://your-ownpay-domain.com',
816
+ });
817
+
818
+ // ✅ Correct
819
+ const client = new OwnPay({
820
+ apiKey: 'op_abcdef123456...',
821
+ baseUrl: 'https://your-ownpay-domain.com',
822
+ });
823
+ ```
824
+
825
+ #### "Authentication failed"
826
+
827
+ - Check that your API key is active and not revoked
828
+ - Ensure you're using the correct key for your environment (test/live)
829
+
830
+ #### "Insufficient scope"
831
+
832
+ Your API key doesn't have the required permissions:
833
+
834
+ - `read` scope: GET requests
835
+ - `write` scope: POST/PUT/PATCH/DELETE requests
836
+ - `admin` scope: API key management operations
837
+
838
+ #### "Webhook verification failed"
839
+
840
+ - Ensure you're using the raw request body (not parsed JSON)
841
+ - Check that the webhook secret matches your configuration
842
+ - Use durable event deduplication. The legacy sender signs the body without signing the timestamp.
843
+
844
+ ### Debug Mode
845
+
846
+ Enable debug logging by checking error details:
847
+
848
+ ```typescript
849
+ try {
850
+ await client.payments.create(paymentParams);
851
+ } catch (error) {
852
+ console.error('Error:', error.toJSON());
853
+ // {
854
+ // name: 'ValidationError',
855
+ // type: 'VALIDATION_ERROR',
856
+ // message: '...',
857
+ // status: 422,
858
+ // requestId: 'req-...'
859
+ // }
860
+ }
861
+ ```
862
+
863
+ ---
864
+
865
+ ## API Reference Summary
866
+
867
+ | Resource | Methods |
868
+ |----------|---------|
869
+ | `client.payments` | `create()`, `get()` |
870
+ | `client.transactions` | `list()`, `get()` |
871
+ | `client.refunds` | `create()`, `list()`, `get()` |
872
+ | `client.customers` | `create()`, `list()`, `get()` |
873
+ | `client.apiKeys` | `list()`, `generate()`, `revoke()` |
874
+ | `client.webhooks` | `test()`, `deliveries()` |
875
+ | `client.health` | `check()` |
876
+
877
+ ---
878
+
879
+ ## Support
880
+
881
+ - 📧 Email: ping@ownpay.org
882
+ - 📖 Documentation: https://ownpay.org/docs
883
+ - 🐛 Issues: https://github.com/johnwatike/superapp-osmas-framework/issues
884
+
885
+ ---
886
+
887
+ ## License
888
+
889
+ This project is licensed under the MIT License - see the [LICENSE](LICENSE) file for details.
890
+
891
+ ---
892
+
893
+ ## Contributing
894
+
895
+ Contributions are welcome! Please read our [Contributing Guide](.github/CONTRIBUTING.md) for details.
896
+
897
+ ---
898
+
899
+ ## Changelog
900
+
901
+ See [CHANGELOG.md](.github/CHANGELOG.md) for a list of changes.