@w3payments/core
v1.2.2
Published
Framework-agnostic payment orchestration layer for W3 Payments ecosystem
Downloads
690
Maintainers
Readme
@w3payments/core
Framework-agnostic payment orchestration engine for the W3 Payments Platform. This package provides the core business logic for payment processing, vendor management, and lifecycle coordination without any UI dependencies.
Installation
npm install @w3payments/coreDependencies: Automatically installs @w3payments/common and @w3payments/adapters.
Key Features
- W3Payments orchestration class - Main API for payment processing
- AdapterRegistry management - Dynamic vendor registration and routing
- Payment lifecycle coordination - End-to-end payment workflow management
- Error handling and validation - Comprehensive error types and validation
- Framework agnostic - Use with React, Vue, Angular, Node.js, or vanilla JS
🚀 Quick Start
Basic Setup
import { W3Payments } from '@w3payments/core';
import type { PaymentClientOptions } from '@w3payments/common';
// Initialize with configuration
const w3payments = new W3Payments({
config: {
environment: 'sandbox', // or 'production'
meshpay: {
clientId: process.env.MESH_CLIENT_ID!,
clientSecret: process.env.MESH_CLIENT_SECRET!,
},
},
});
// Initialize the payment engine
await w3payments.initialize();Creating Payment Intents
import type { CreatePaymentOptions } from '@w3payments/common';
// Create a payment intent
const paymentOptions: CreatePaymentOptions = {
amount: '100.00',
currency: 'USD',
destinations: [{
address: '1A1zP1eP5QGefi2DMPTfTL5SLmv7DivfNa',
networkId: 'bitcoin',
symbol: 'BTC'
}],
targetCurrency: 'BTC',
targetNetwork: 'bitcoin'
};
const session = await w3payments.paymentIntents.create(paymentOptions);
console.log('Payment session created:', session.id);Retrieving Payment Status
// Check payment status
const status = await w3payments.paymentIntents.retrieve(
session.id,
session.vendorId
);
console.log('Payment status:', status.status);
// Outputs: 'pending' | 'processing' | 'completed' | 'failed'🏗 Architecture Overview
Main Components
W3Payments (Orchestrator)
├── PaymentIntents (Payment lifecycle)
├── AdapterRegistry (Vendor management)
└── ErrorHandler (Error processing)Payment Flow
sequenceDiagram
participant Client
participant W3Payments
participant AdapterRegistry
participant VendorAdapter
Client->>W3Payments: create(paymentOptions)
W3Payments->>AdapterRegistry: selectAdapter(criteria)
AdapterRegistry->>W3Payments: return adapter
W3Payments->>VendorAdapter: createSession(options)
VendorAdapter->>W3Payments: return session
W3Payments->>Client: return session
Client->>W3Payments: retrieve(sessionId, vendorId)
W3Payments->>VendorAdapter: getSessionStatus(sessionId)
VendorAdapter->>W3Payments: return status
W3Payments->>Client: return status🎯 Core API Reference
W3Payments Class
The main orchestration class that coordinates all payment operations.
Constructor
import type { PaymentClientOptions } from '@w3payments/common';
const options: PaymentClientOptions = {
config: {
environment: 'sandbox' | 'production',
vendors: {
meshpay: {
clientId: string,
clientSecret: string
}
}
}
};
const w3payments = new W3Payments(options);Methods
initialize(): Promise<void>
Initialize the payment engine and register adapters.
await w3payments.initialize();
// Must be called before using any payment methodspaymentIntents.create(options): Promise<CheckoutSession>
Create a new payment intent session.
import type { CreatePaymentOptions, CheckoutSession } from '@w3payments/common';
const options: CreatePaymentOptions = {
amount: '50.00',
currency: 'USD',
destinations: [{
address: 'recipient-address',
networkId: 'ethereum',
symbol: 'USDC'
}],
targetCurrency: 'USDC',
targetNetwork: 'ethereum'
};
const session: CheckoutSession = await w3payments.paymentIntents.create(options);paymentIntents.retrieve(sessionId, vendorId): Promise<PaymentResult>
Retrieve payment status and details.
import type { PaymentResult } from '@w3payments/common';
const result: PaymentResult = await w3payments.paymentIntents.retrieve(
'session_123',
'meshpay'
);
console.log(result.status); // 'pending' | 'processing' | 'completed' | 'failed'
console.log(result.transactionId); // Vendor transaction ID
console.log(result.amount); // Final amount
console.log(result.currency); // Final currencyAdapterRegistry Class
Manages vendor adapters and routing logic.
Methods
register(vendorId, adapter): void
Register a new payment vendor adapter.
import { AdapterRegistry } from '@w3payments/core';
import type { VendorAdapter } from '@w3payments/common';
const registry = new AdapterRegistry();
// Register custom adapter
registry.register('custom-vendor', new CustomVendorAdapter({
apiKey: 'your-api-key'
}));getAdapter(criteria): VendorAdapter | null
Get the best adapter for given payment criteria.
const adapter = registry.getAdapter({
currency: 'BTC',
amount: '0.001',
targetNetwork: 'bitcoin'
});
if (adapter) {
const session = await adapter.createSession(paymentOptions);
}listAdapters(): string[]
List all registered adapter IDs.
const adapters = registry.listAdapters();
console.log('Available adapters:', adapters);
// Output: ['meshpay', 'custom-vendor']🔧 Configuration Options
Environment Configuration
import type { PaymentClientOptions } from '@w3payments/common';
const config: PaymentClientOptions = {
config: {
// Environment
environment: 'production', // 'sandbox' | 'production'
// Vendor configurations
vendors: {
meshpay: {
clientId: process.env.MESH_CLIENT_ID!,
clientSecret: process.env.MESH_CLIENT_SECRET!,
}
},
// Optional: Custom adapter settings
adapterSettings: {
timeout: 30000, // Request timeout in ms
retries: 3, // Number of retry attempts
fallbackStrategy: 'next' // 'next' | 'none'
}
}
};Vendor-Specific Options
MeshPay Configuration
const options: PaymentClientOptions = {
config: {
environment: 'sandbox',
meshpay: {
clientId: 'mesh_client_xxx',
clientSecret: 'mesh_secret_xxx',
// Optional MeshPay-specific settings
settings: {
transferFinishTimeout: 60000,
catalogPageSize: 20
}
}
}
};⚠️ Error Handling
Built-in Error Types
import { PaymentError, AdapterError } from '@w3payments/core';
try {
const session = await w3payments.paymentIntents.create(options);
} catch (error) {
if (error instanceof PaymentError) {
console.error('Payment failed:', error.message);
console.error('Error code:', error.code);
console.error('Details:', error.details);
} else if (error instanceof AdapterError) {
console.error('Adapter error:', error.message);
console.error('Vendor:', error.vendorId);
} else {
console.error('Unexpected error:', error);
}
}Error Codes
| Code | Description | Action |
|------|-------------|---------|
| INVALID_AMOUNT | Amount is invalid or out of range | Check amount format and limits |
| UNSUPPORTED_CURRENCY | Currency not supported by any adapter | Use supported currency or add adapter |
| ADAPTER_NOT_FOUND | No suitable adapter for request | Check configuration and adapter availability |
| ADAPTER_ERROR | Vendor adapter returned error | Check vendor service status and credentials |
| NETWORK_ERROR | Network request failed | Retry request or check connectivity |
| INVALID_CONFIG | Configuration is invalid | Review configuration parameters |
Error Recovery
import { PaymentError } from '@w3payments/core';
async function createPaymentWithFallback(options: CreatePaymentOptions) {
try {
return await w3payments.paymentIntents.create(options);
} catch (error) {
if (error instanceof PaymentError && error.code === 'ADAPTER_NOT_FOUND') {
// Try with different currency or add fallback logic
const fallbackOptions = { ...options, targetCurrency: 'USDC' };
return await w3payments.paymentIntents.create(fallbackOptions);
}
throw error; // Re-throw unhandled errors
}
}🧪 Testing Support
Mock Adapters
import { AdapterRegistry } from '@w3payments/core';
import type { VendorAdapter, CheckoutSession } from '@w3payments/common';
// Create mock adapter for testing
class MockAdapter implements VendorAdapter {
async createSession(options: CreatePaymentOptions): Promise<CheckoutSession> {
return {
id: 'mock_session_123',
vendorId: 'mock',
url: 'https://mock.example.com/checkout',
status: 'pending'
};
}
async getSessionStatus(sessionId: string): Promise<PaymentResult> {
return {
status: 'completed',
transactionId: 'mock_tx_456',
amount: '100.00',
currency: 'USD'
};
}
}
// Use in tests
const registry = new AdapterRegistry();
registry.register('mock', new MockAdapter());Test Configuration
const testConfig: PaymentClientOptions = {
config: {
environment: 'sandbox',
vendors: {
// Use test credentials
meshpay: {
clientId: 'test_client_id',
clientSecret: 'test_client_secret'
}
}
}
};🔗 Integration Examples
Express.js Backend
import express from 'express';
import { W3Payments } from '@w3payments/core';
const app = express();
app.use(express.json());
const w3payments = new W3Payments({ config: { /* ... */ } });
await w3payments.initialize();
// Create payment endpoint
app.post('/api/payments/create', async (req, res) => {
try {
const session = await w3payments.paymentIntents.create(req.body);
res.json(session);
} catch (error) {
res.status(500).json({ error: error.message });
}
});
// Status check endpoint
app.get('/api/payments/:id/:vendor', async (req, res) => {
try {
const status = await w3payments.paymentIntents.retrieve(
req.params.id,
req.params.vendor
);
res.json(status);
} catch (error) {
res.status(500).json({ error: error.message });
}
});Next.js API Routes
// pages/api/payments/create.ts
import { W3Payments } from '@w3payments/core';
import type { NextApiRequest, NextApiResponse } from 'next';
const w3payments = new W3Payments({ config: { /* ... */ } });
export default async function handler(req: NextApiRequest, res: NextApiResponse) {
if (req.method !== 'POST') {
return res.status(405).json({ error: 'Method not allowed' });
}
try {
const session = await w3payments.paymentIntents.create(req.body);
res.json(session);
} catch (error) {
res.status(500).json({ error: error.message });
}
}🔒 Security Best Practices
Environment Variables
# .env.local
MESH_CLIENT_ID=your_mesh_client_id
MESH_CLIENT_SECRET=your_mesh_client_secret
# Never commit secrets to version control
# Use environment-specific configuration filesConfiguration Validation
import { W3Payments } from '@w3payments/core';
// Validate configuration before initialization
function validateConfig(config: any): boolean {
if (!config.meshpay?.clientId) {
throw new Error('MeshPay client ID is required');
}
if (!config.meshpay?.clientSecret) {
throw new Error('MeshPay client secret is required');
}
return true;
}
const config = {
environment: process.env.NODE_ENV === 'production' ? 'production' : 'sandbox',
meshpay: {
clientId: process.env.MESH_CLIENT_ID!,
clientSecret: process.env.MESH_CLIENT_SECRET!,
}
};
validateConfig(config);
const w3payments = new W3Payments({ config });📚 Related Packages
- @w3payments/common - Types and utilities (required dependency)
- @w3payments/adapters - Vendor implementations (required dependency)
- @w3payments/react - React UI components (uses this package)
📄 License
Proprietary - All rights reserved
💡 Pro Tip: Always initialize W3Payments in your application startup sequence and handle errors gracefully with appropriate fallbacks for production resilience.
