pycer-sdk 0.0.0-stage → 1.0.2

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