@mbanq/core-sdk-js 0.1.1

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 ADDED
@@ -0,0 +1,777 @@
1
+ <p align="center">
2
+ <img src="https://avatars.githubusercontent.com/u/26124358?s=200&v=4" alt="Mbanq Logo" width="120"/>
3
+ </p>
4
+
5
+ # Core SDK JS
6
+
7
+ ![npm version](https://img.shields.io/npm/v/@mbanq/core-sdk-js.svg)
8
+ [![Download](https://img.shields.io/npm/dm/@mbanq/core-sdk-js)](https://www.npmjs.com/package/@mbanq/core-sdk-js)
9
+ ![license](https://img.shields.io/github/license/Mbanq/core-sdk-js)
10
+
11
+ ## Table of Contents
12
+
13
+ - [Introduction](#introduction)
14
+ - [Installation](#installation)
15
+ - [Quick Start](#quick-start)
16
+ - [Setup](#setup)
17
+ - [Axios Instance Logger](#axios-instance-logger)
18
+ - [Middleware](#middleware)
19
+ - [Logging Middleware](#logging-middleware)
20
+ - [Metrics Middleware](#metrics-middleware)
21
+ - [Custom Middleware](#custom-middleware)
22
+ - [API Reference](#api-reference)
23
+ - [Payment Operations](#payment-operations)
24
+ - [Create Payment](#create-payment)
25
+ - [Get Payment](#get-payment)
26
+ - [Update Payment](#update-payment)
27
+ - [List Payments](#list-payments)
28
+ - [Multi-Tenant Support](#multi-tenant-support)
29
+ - [Type Safety & Validation](#type-safety--validation)
30
+ - [Error Handling](#error-handling)
31
+ - [Examples](#examples)
32
+
33
+ ## Introduction
34
+ This library provides a comprehensive JavaScript SDK for interacting with the Mbanq payment API. It offers type-safe payment operations with built-in validation, multi-tenant support, and a modern fluent API design.
35
+ ## Installation
36
+
37
+ ```bash
38
+ npm install @mbanq/core-sdk-js
39
+ ```
40
+
41
+ ## Quick Start
42
+
43
+ Choose your preferred API pattern:
44
+
45
+ ### Modern Fluent API
46
+ ```javascript
47
+ import { CoreSDK } from '@mbanq/core-sdk-js';
48
+
49
+ const coreSDK = new CoreSDK({
50
+ secret: 'your-jwt-secret',
51
+ signee: 'YOUR-SIGNEE',
52
+ baseUrl: 'https://api.cloud.mbanq.com',
53
+ tenantId: 'your-tenant-id'
54
+ });
55
+
56
+ // Create payment using fluent API
57
+ const payment = await coreSDK.payment.create({
58
+ amount: 100.00,
59
+ currency: 'USD',
60
+ description: 'Payment for invoice #123'
61
+ }).execute();
62
+ ```
63
+
64
+ ### Command Pattern
65
+ ```javascript
66
+ import { CoreSDK, GetTransfers } from '@mbanq/core-sdk-js';
67
+
68
+ const coreSDK = new CoreSDK({
69
+ secret: 'your-jwt-secret',
70
+ signee: 'YOUR-SIGNEE',
71
+ baseUrl: 'https://api.cloud.mbanq.com',
72
+ tenantId: 'your-tenant-id'
73
+ });
74
+
75
+ // Get transfers using command pattern
76
+ const command = GetTransfers({
77
+ transferStatus: 'EXECUTION_SCHEDULED',
78
+ tenantId: 'default'
79
+ });
80
+ const transfers = await coreSDK.request(command);
81
+ ```
82
+
83
+ ## Setup
84
+
85
+ ### Authentication Options
86
+
87
+ The SDK supports multiple authentication methods. Choose the one that fits your integration:
88
+
89
+ #### 1. JWT Token Authentication (Recommended)
90
+ Use your API secret and signee for JWT-based authentication:
91
+
92
+ ```javascript
93
+ const client = createClient({
94
+ secret: 'your-jwt-secret',
95
+ signee: 'YOUR-SIGNEE',
96
+ baseUrl: 'https://api.cloud.mbanq.com',
97
+ tenantId: 'your-tenant-id'
98
+ });
99
+ ```
100
+
101
+ #### 2. Bearer Token Authentication
102
+ If you already have a valid access token:
103
+
104
+ ```javascript
105
+ // With "Bearer " prefix (recommended)
106
+ const client = createClient({
107
+ bearerToken: 'Bearer your-access-token',
108
+ baseUrl: 'https://api.cloud.mbanq.com',
109
+ tenantId: 'your-tenant-id'
110
+ });
111
+
112
+ // Without "Bearer " prefix (automatically added)
113
+ const client = createClient({
114
+ bearerToken: 'your-access-token', // "Bearer " will be added automatically
115
+ baseUrl: 'https://api.cloud.mbanq.com',
116
+ tenantId: 'your-tenant-id'
117
+ });
118
+ ```
119
+
120
+ #### 3. OAuth Credential Authentication
121
+ For OAuth 2.0 password grant flow:
122
+
123
+ ```javascript
124
+ const client = createClient({
125
+ credential: {
126
+ client_id: 'your-client-id',
127
+ client_secret: 'your-client-secret',
128
+ username: 'your-username',
129
+ password: 'your-password',
130
+ grant_type: 'password'
131
+ },
132
+ baseUrl: 'https://api.cloud.mbanq.com',
133
+ tenantId: 'your-tenant-id'
134
+ });
135
+ ```
136
+
137
+ #### Authentication Priority
138
+ When multiple authentication methods are provided, the SDK uses them in this order:
139
+ 1. **`bearerToken`** - Takes highest priority if provided
140
+ 2. **`credential`** - OAuth flow is used if no bearerToken
141
+ 3. **`secret` + `signee`** - JWT authentication used as fallback
142
+
143
+ #### Additional Configuration Options
144
+ ```javascript
145
+ const client = createClient({
146
+ // Choose one authentication method from above
147
+ secret: 'your-jwt-secret',
148
+ signee: 'YOUR-SIGNEE',
149
+
150
+ // Required configuration
151
+ baseUrl: 'https://api.cloud.mbanq.com',
152
+ tenantId: 'your-tenant-id',
153
+
154
+ // Optional configuration
155
+ traceId: 'custom-trace-id', // Custom request tracing identifier
156
+ axiosConfig: {
157
+ timeout: 30000, // Request timeout in milliseconds (default: 29000)
158
+ keepAlive: true, // HTTP keep-alive for connection reuse
159
+ headers: {
160
+ 'Custom-Header': 'custom-value' // Additional HTTP headers
161
+ }
162
+ }
163
+ });
164
+ ```
165
+
166
+ ### Security Best Practices
167
+
168
+ #### Credential Management
169
+ - **Never hardcode credentials** in your source code
170
+ - Use environment variables or secure credential management systems
171
+ - Rotate API secrets and tokens regularly
172
+ - Use the minimum required permissions for your integration
173
+
174
+ #### Environment Variables Example
175
+ ```javascript
176
+ const client = createClient({
177
+ secret: process.env.MBANQ_API_SECRET,
178
+ signee: process.env.MBANQ_API_SIGNEE,
179
+ baseUrl: process.env.MBANQ_API_URL,
180
+ tenantId: process.env.MBANQ_TENANT_ID
181
+ });
182
+ ```
183
+
184
+ #### Production Considerations
185
+ - Use HTTPS endpoints only (`https://`)
186
+ - Implement proper error handling to avoid credential leakage in logs
187
+ - Configure appropriate request timeouts
188
+ - Use connection pooling for high-volume applications
189
+
190
+ ### Axios Instance Logger
191
+ You can also configure an Axios instance logger to set up interceptors or other axios-specific configurations:
192
+
193
+ ```javascript
194
+ const axiosLogger = (axiosInstance) => {
195
+ // Add request interceptor
196
+ axiosInstance.interceptors.request.use(
197
+ (config) => {
198
+ console.log('Request:', config.method?.toUpperCase(), config.url);
199
+ return config;
200
+ }
201
+ );
202
+
203
+ // Add response interceptor
204
+ axiosInstance.interceptors.response.use(
205
+ (response) => {
206
+ console.log('Response:', response.status, response.config.url);
207
+ return response;
208
+ }
209
+ );
210
+ };
211
+
212
+ const coreSDK = createClient({
213
+ secret: 'testing123',
214
+ signee: 'TESTING',
215
+ baseUrl: 'https://example.com',
216
+ tenantId: 'testing',
217
+ logger: axiosLogger // Configure Axios instance
218
+ });
219
+ ```
220
+
221
+ ## Middleware
222
+ The SDK supports middleware for cross-cutting concerns like logging and metrics. Middleware functions are executed automatically around command execution.
223
+
224
+ **Note**: This is different from the Axios instance logger above. Middleware loggers handle command-level logging, while the Axios logger handles HTTP request/response logging.
225
+
226
+ ### Available Middleware
227
+
228
+ #### Logging Middleware
229
+ Logs command execution details including inputs, outputs, and errors.
230
+
231
+ ```javascript
232
+ import { createClient, createLoggingMiddleware } from '@mbanq/core-sdk-js';
233
+
234
+ const loggingMiddleware = createLoggingMiddleware(console); // or custom logger
235
+
236
+ const client = createClient({
237
+ secret: 'testing123',
238
+ signee: 'TESTING',
239
+ baseUrl: 'https://example.com',
240
+ tenantId: 'testing',
241
+ middlewares: [loggingMiddleware]
242
+ });
243
+ ```
244
+
245
+ #### Logger Interface
246
+ For custom loggers, implement the Logger interface:
247
+
248
+ ```typescript
249
+ interface Logger {
250
+ info: (message: string, ...args: unknown[]) => void;
251
+ error: (message: string, ...args: unknown[]) => void;
252
+ warn?: (message: string, ...args: unknown[]) => void; // Optional
253
+ log?: (message: string, ...args: unknown[]) => void; // Optional
254
+ }
255
+
256
+ // Example with a custom logger
257
+ const customLogger = {
258
+ info: (message, ...args) => myLoggingService.info(message, args),
259
+ error: (message, ...args) => myLoggingService.error(message, args),
260
+ warn: (message, ...args) => myLoggingService.warn(message, args)
261
+ };
262
+
263
+ const middleware = createLoggingMiddleware(customLogger);
264
+ ```
265
+
266
+ #### Metrics Middleware
267
+ Tracks command execution metrics including counters for started, completed, and error events.
268
+
269
+ ```javascript
270
+ import { createClient, createMetricsMiddleware } from '@mbanq/core-sdk-js';
271
+
272
+ // Your metrics client must implement the MetricsClient interface
273
+ const metricsClient = {
274
+ incrementCounter: (counterName) => {
275
+ // Increment your counter (e.g., Prometheus, StatsD, etc.)
276
+ console.log(`Counter: ${counterName}`);
277
+ },
278
+ recordError: (error) => {
279
+ // Optional: Record error details
280
+ console.error('Command error:', error);
281
+ }
282
+ };
283
+
284
+ const metricsMiddleware = createMetricsMiddleware(metricsClient);
285
+
286
+ const client = createClient({
287
+ secret: 'testing123',
288
+ signee: 'TESTING',
289
+ baseUrl: 'https://example.com',
290
+ tenantId: 'testing',
291
+ middlewares: [metricsMiddleware]
292
+ });
293
+ ```
294
+
295
+ #### MetricsClient Interface
296
+ ```typescript
297
+ interface MetricsClient {
298
+ incrementCounter: (counterName: string) => void;
299
+ recordError?: (error: Error) => void; // Optional
300
+ }
301
+ ```
302
+
303
+ #### Using Multiple Middleware
304
+ ```javascript
305
+ const client = createClient({
306
+ // ... other config
307
+ middlewares: [
308
+ createLoggingMiddleware(console),
309
+ createMetricsMiddleware(metricsClient)
310
+ ]
311
+ });
312
+ ```
313
+
314
+ #### Custom Middleware
315
+ You can create custom middleware by implementing the Middleware interface:
316
+
317
+ ```javascript
318
+ const customMiddleware = {
319
+ before: async (command) => {
320
+ // Called before command execution
321
+ console.log(`Starting ${command.metadata.commandName}`);
322
+ },
323
+ after: async (command, response) => {
324
+ // Called after successful execution
325
+ console.log(`Completed ${command.metadata.commandName}`, response);
326
+ },
327
+ onError: async (command, error) => {
328
+ // Called when command fails
329
+ console.error(`Error in ${command.metadata.commandName}`, error);
330
+ }
331
+ };
332
+
333
+ const client = createClient({
334
+ // ... other config
335
+ middlewares: [customMiddleware]
336
+ });
337
+ ```
338
+
339
+ ## API Reference
340
+
341
+ The SDK provides two API patterns for different operations:
342
+
343
+ ### Modern Fluent API (Recommended)
344
+ For payment operations, use the modern fluent API with method chaining:
345
+
346
+ ```javascript
347
+ // Create payment
348
+ const payment = await apiClient.payment.create(paymentData).execute();
349
+
350
+ // Get payment
351
+ const payment = await apiClient.payment.get('payment-456').execute();
352
+
353
+ // List with filters
354
+ const payments = await apiClient.payment.list()
355
+ .where('status').eq('DRAFT')
356
+ .where('paymentRail').eq('ACH')
357
+ .execute();
358
+ ```
359
+
360
+ ### Command Pattern (Legacy Support)
361
+ For transfer operations, the SDK also supports the traditional command pattern:
362
+
363
+ ```javascript
364
+ // Get transfers with filters
365
+ const getTransfersCommand = GetTransfers({
366
+ transferStatus: 'EXECUTION_SCHEDULED',
367
+ executedAt: '2025-01-22',
368
+ paymentType: 'ACH',
369
+ queryLimit: 200,
370
+ tenantId: 'default'
371
+ });
372
+ const transfers = await coreSDK.request(getTransfersCommand);
373
+
374
+ // Create a new transfer
375
+ const createTransferCommand = CreateTransfer({
376
+ amount: 1000,
377
+ currency: 'USD',
378
+ paymentRail: 'ACH',
379
+ paymentType: 'CREDIT',
380
+ debtor: {
381
+ name: 'Sender Name',
382
+ identifier: '123456789',
383
+ agent: { name: 'Bank Name', identifier: '021000021' }
384
+ },
385
+ creditor: {
386
+ name: 'Recipient Name',
387
+ identifier: '987654321',
388
+ agent: { name: 'Recipient Bank', identifier: '121000248' }
389
+ },
390
+ tenantId: 'default'
391
+ });
392
+ const newTransfer = await coreSDK.request(createTransferCommand);
393
+
394
+ // Get specific transfer by ID
395
+ const getTransferCommand = GetTransfer({
396
+ transferId: 'transfer-123',
397
+ tenantId: 'default'
398
+ });
399
+ const transfer = await coreSDK.request(getTransferCommand);
400
+
401
+ // Mark transfer as successful
402
+ const markSuccessCommand = MarkAsSuccess({
403
+ transferId: 'transfer-123',
404
+ tenantId: 'default'
405
+ });
406
+ await coreSDK.request(markSuccessCommand);
407
+
408
+ // Mark transfer as processing
409
+ const markProcessingCommand = MarkAsProcessing({
410
+ transferId: 'transfer-123',
411
+ tenantId: 'default'
412
+ });
413
+ await coreSDK.request(markProcessingCommand);
414
+
415
+ // Mark transfer as returned
416
+ const markReturnedCommand = MarkAsReturned({
417
+ transferId: 'transfer-123',
418
+ returnCode: 'R01',
419
+ returnReason: 'Insufficient funds',
420
+ tenantId: 'default'
421
+ });
422
+ await coreSDK.request(markReturnedCommand);
423
+
424
+ // Log failed transfer
425
+ const logFailCommand = LogFailTransfer({
426
+ transferId: 'transfer-123',
427
+ errorCode: 'E001',
428
+ errorMessage: 'Processing error',
429
+ tenantId: 'default'
430
+ });
431
+ await coreSDK.request(logFailCommand);
432
+
433
+ // Mark transfer as failed
434
+ const markFailCommand = MarkAsFail({
435
+ transferId: 'transfer-123',
436
+ failureReason: 'Bank rejected',
437
+ tenantId: 'default'
438
+ });
439
+ await coreSDK.request(markFailCommand);
440
+
441
+ // Update trace number
442
+ const updateTraceCommand = UpdateTraceNumber({
443
+ transferId: 'transfer-123',
444
+ traceNumber: 'TRC123456789',
445
+ tenantId: 'default'
446
+ });
447
+ await coreSDK.request(updateTraceCommand);
448
+ ```
449
+
450
+ Available transfer commands: `GetTransfers`, `CreateTransfer`, `GetTransfer`, `MarkAsSuccess`, `MarkAsProcessing`, `MarkAsReturned`, `LogFailTransfer`, `MarkAsFail`, `UpdateTraceNumber`
451
+
452
+ ### Payment Operations
453
+
454
+ #### Create Payment
455
+
456
+ Creates a new payment with comprehensive validation.
457
+
458
+ ```javascript
459
+ const payment = await apiClient.payment.create({
460
+ // Required fields
461
+ amount: 1000,
462
+ currency: 'USD',
463
+ paymentRail: 'ACH', // ACH, WIRE, SWIFT, INTERNAL, FXPAY, CARD
464
+ paymentType: 'CREDIT', // CREDIT or DEBIT
465
+
466
+ // Originator (sender)
467
+ debtor: {
468
+ name: 'John Sender',
469
+ identifier: '123456789', // Account number
470
+ accountType: 'CHECKING', // Optional: CHECKING or SAVINGS
471
+ agent: {
472
+ name: 'First Bank',
473
+ identifier: '021000021' // Routing code
474
+ }
475
+ },
476
+
477
+ // Recipient (receiver)
478
+ creditor: {
479
+ name: 'Jane Receiver',
480
+ identifier: '987654321',
481
+ accountType: 'SAVINGS',
482
+ address: { // Required for WIRE transfers
483
+ streetAddress: '123 Main St',
484
+ city: 'New York',
485
+ state: 'NY',
486
+ country: 'US',
487
+ postalCode: '10001'
488
+ },
489
+ agent: {
490
+ name: 'Second Bank',
491
+ identifier: '121000248'
492
+ }
493
+ },
494
+
495
+ // Optional fields
496
+ clientId: 'client-123',
497
+ reference: ['Invoice-001', 'Payment-ABC'],
498
+ exchangeRate: 1.25,
499
+ chargeBearer: 'OUR', // For SWIFT: OUR, BEN, SHA
500
+ valueDate: '2025-01-15',
501
+ paymentRailMetaData: {
502
+ priority: 'high',
503
+ category: 'business'
504
+ }
505
+ }).execute();
506
+ ```
507
+
508
+ #### Get Payment
509
+
510
+ Retrieves a specific payment by ID.
511
+
512
+ ```javascript
513
+ const payment = await apiClient.payment.get('payment-456').execute();
514
+ ```
515
+
516
+ #### Update Payment
517
+
518
+ Updates an existing payment. All fields are optional.
519
+
520
+ ```javascript
521
+ const updatedPayment = await apiClient.payment.update('payment-456', {
522
+ amount: 1500,
523
+ status: 'EXECUTION_SCHEDULED',
524
+ creditor: {
525
+ name: 'Updated Recipient Name'
526
+ },
527
+ errorCode: 'E001',
528
+ errorMessage: 'Insufficient funds',
529
+ exchangeRate: 1.30,
530
+ reference: ['Updated-Reference'],
531
+ paymentRailMetaData: {
532
+ updated: true
533
+ }
534
+ }).execute();
535
+ ```
536
+
537
+ #### List Payments
538
+
539
+ Retrieves payments with powerful filtering capabilities.
540
+
541
+ ```javascript
542
+ // Simple list
543
+ const payments = await apiClient.payment.list().execute();
544
+
545
+ // With filters and pagination
546
+ const payments = await apiClient.payment.list()
547
+ .where('status').eq('DRAFT')
548
+ .where('paymentRail').eq('ACH')
549
+ .where('paymentType').eq('CREDIT')
550
+ .where('originatorName').eq('John Doe')
551
+ .limit(50)
552
+ .offset(0)
553
+ .execute();
554
+
555
+ // Available filter fields
556
+ // originatorName, originatorAccount, originatorBankRoutingCode
557
+ // recipientName, recipientAccount, recipientBankRoutingCode
558
+ // reference, traceNumber, externalId, clientId
559
+ // dateFormat, locale, originatedBy, paymentRail, paymentType
560
+ // fromValueDate, toValueDate, fromExecuteDate, toExecuteDate
561
+ // status, fromReturnDate, toReturnDate, isSettlement, orderBy, sortOrder
562
+ ```
563
+
564
+ ### Multi-Tenant Support
565
+
566
+ The SDK supports multi-tenant operations through tenant context.
567
+
568
+ #### Default Tenant Operations
569
+ Uses the `tenantId` from client configuration:
570
+
571
+ ```javascript
572
+ const payment = await apiClient.payment.create(paymentData).execute();
573
+ const payments = await apiClient.payment.list().execute();
574
+ ```
575
+
576
+ #### Tenant-Specific Operations
577
+ Override tenant for specific operations:
578
+
579
+ ```javascript
580
+ // Create payment for specific tenant
581
+ const payment = await apiClient.tenant('tenant-123').payment.create(paymentData).execute();
582
+
583
+ // Get payment from specific tenant
584
+ const payment = await apiClient.tenant('tenant-123').payment.get('payment-456').execute();
585
+
586
+ // Update payment in specific tenant
587
+ await apiClient.tenant('tenant-123').payment.update('payment-456', updateData).execute();
588
+
589
+ // List payments from specific tenant with filters
590
+ const payments = await apiClient.tenant('tenant-123').payment.list()
591
+ .where('status').eq('DRAFT')
592
+ .limit(10)
593
+ .execute();
594
+ ```
595
+
596
+ ## Type Safety & Validation
597
+
598
+ The SDK uses [Zod](https://zod.dev/) for runtime type validation and TypeScript for compile-time type safety.
599
+
600
+ ### Supported Payment Rails
601
+ - `ACH` - Automated Clearing House
602
+ - `SAMEDAYACH` - Same Day ACH
603
+ - `WIRE` - Domestic Wire Transfer
604
+ - `SWIFT` - International Wire Transfer
605
+ - `INTERNAL` - Internal Transfer
606
+ - `FXPAY` - Foreign Exchange Payment
607
+ - `CARD` - Card Payment
608
+
609
+ ### Payment Statuses
610
+ - `DRAFT`, `AML_SCREENING`, `AML_REJECTED`
611
+ - `EXECUTION_SCHEDULED`, `EXECUTION_PROCESSING`, `EXECUTION_SUCCESS`, `EXECUTION_FAILURE`
612
+ - `RETURNED`, `CANCELLED`, `COMPLIANCE_FAILURE`, `DELETED`, `UNKNOWN`
613
+
614
+ ### Validation Features
615
+ - **Input Validation**: All create/update operations validate data structure
616
+ - **Response Validation**: API responses are validated before returning
617
+ - **Custom Rules**: WIRE transfers require recipient address with state/country
618
+ - **Type Safety**: Full TypeScript support with inferred types
619
+
620
+ ## Error Handling
621
+ The library uses a consistent error handling pattern. All API calls may throw the following errors:
622
+
623
+ ### Error Types
624
+ - **`CommandError`**: Base error type with `code`, `message`, `statusCode`, and optional `requestId`
625
+ - **Authentication Errors**: Invalid or missing API credentials
626
+ - Invalid JWT secret/signee combination
627
+ - Expired or invalid bearer token
628
+ - OAuth credential authentication failure
629
+ - **Validation Errors**: Invalid parameters provided (uses Zod validation)
630
+ - **API Errors**: Server-side errors with specific error codes
631
+ - **Network Errors**: Network connectivity or timeout issues
632
+
633
+ ### Common Authentication Error Scenarios
634
+ - **Missing credentials**: No authentication method provided
635
+ - **Invalid JWT**: Incorrect secret or signee values
636
+ - **Expired token**: Bearer token has expired and needs refresh
637
+ - **OAuth failure**: Invalid username/password or client credentials
638
+
639
+ ## Examples
640
+
641
+ ### Complete Payment Flow Example
642
+
643
+ ```javascript
644
+ import { createClient } from '@mbanq/core-sdk-js';
645
+
646
+ // Initialize the client
647
+ const apiClient = createClient({
648
+ secret: 'your-secret',
649
+ signee: 'YOUR-SIGNEE',
650
+ baseUrl: 'https://api.cloud.mbanq.com',
651
+ tenantId: 'your-tenant-id'
652
+ });
653
+
654
+ // Create an ACH payment
655
+ const achPayment = await apiClient.payment.create({
656
+ amount: 1500,
657
+ currency: 'USD',
658
+ paymentRail: 'ACH',
659
+ paymentType: 'CREDIT',
660
+ debtor: {
661
+ name: 'Alice Corporation',
662
+ identifier: '111222333',
663
+ accountType: 'CHECKING',
664
+ agent: {
665
+ name: 'First National Bank',
666
+ identifier: '021000021'
667
+ }
668
+ },
669
+ creditor: {
670
+ name: 'Bob Enterprises',
671
+ identifier: '444555666',
672
+ accountType: 'CHECKING',
673
+ agent: {
674
+ name: 'Second Federal Bank',
675
+ identifier: '121000248'
676
+ }
677
+ },
678
+ clientId: 'client-abc123',
679
+ reference: ['Invoice-2025-001']
680
+ }).execute();
681
+
682
+ console.log('Created payment:', achPayment.id);
683
+
684
+ // Create an international WIRE payment
685
+ const wirePayment = await apiClient.payment.create({
686
+ amount: 5000,
687
+ currency: 'USD',
688
+ paymentRail: 'SWIFT',
689
+ paymentType: 'CREDIT',
690
+ debtor: {
691
+ name: 'US Company',
692
+ identifier: '123456789',
693
+ agent: {
694
+ name: 'Chase Bank',
695
+ identifier: 'CHASUS33XXX'
696
+ }
697
+ },
698
+ creditor: {
699
+ name: 'European Partner',
700
+ identifier: '987654321',
701
+ address: {
702
+ streetAddress: '123 Business Ave',
703
+ city: 'London',
704
+ state: 'England',
705
+ country: 'GB',
706
+ postalCode: 'SW1A 1AA'
707
+ },
708
+ agent: {
709
+ name: 'HSBC Bank',
710
+ identifier: 'HBUKGB4BXXX'
711
+ }
712
+ },
713
+ chargeBearer: 'OUR',
714
+ reference: ['Contract-2025-002'],
715
+ exchangeRate: 0.85
716
+ }).execute();
717
+
718
+ // Retrieve and monitor payments
719
+ const payment = await apiClient.payment.get(achPayment.id).execute();
720
+ console.log('Payment status:', payment.status);
721
+
722
+ // Update payment if needed
723
+ if (payment.status === 'DRAFT') {
724
+ await apiClient.payment.update(payment.id, {
725
+ status: 'EXECUTION_SCHEDULED',
726
+ reference: ['Updated-Reference']
727
+ });
728
+ }
729
+
730
+ // List recent payments with filters
731
+ const recentPayments = await apiClient.payment.list()
732
+ .where('status').eq('EXECUTION_SCHEDULED')
733
+ .where('paymentRail').eq('ACH')
734
+ .where('fromExecuteDate').eq('2025-01-01')
735
+ .where('toExecuteDate').eq('2025-01-31')
736
+ .limit(25)
737
+ .execute();
738
+
739
+ console.log(`Found ${recentPayments.length} scheduled ACH payments`);
740
+
741
+ // Multi-tenant example
742
+ const tenantPayment = await apiClient.tenant('different-tenant').payment.create({
743
+ amount: 750,
744
+ currency: 'USD',
745
+ paymentRail: 'INTERNAL',
746
+ paymentType: 'CREDIT',
747
+ debtor: { name: 'Internal Sender', identifier: '111111' },
748
+ creditor: { name: 'Internal Receiver', identifier: '222222' }
749
+ }).execute();
750
+ ```
751
+
752
+ ### Error Handling Example
753
+
754
+ ```javascript
755
+ import { isCommandError } from '@mbanq/core-sdk-js';
756
+
757
+ try {
758
+ const payment = await apiClient.payment.create({
759
+ amount: -100, // Invalid: negative amount
760
+ currency: 'INVALID', // Invalid: not 3-character code
761
+ // Missing required fields
762
+ }).execute();
763
+ } catch (error) {
764
+ if (isCommandError(error)) {
765
+ console.error('Payment creation failed:');
766
+ console.error('Code:', error.code);
767
+ console.error('Message:', error.message);
768
+ if (error.requestId) {
769
+ console.error('Request ID:', error.requestId);
770
+ }
771
+ } else {
772
+ console.error('Unexpected error:', error);
773
+ }
774
+ }
775
+ ```
776
+
777
+ For more detailed information or support, please contact our support team or visit our developer portal.