npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2026 – Pkg Stats / Ryan Hefner

@w3payments/core

v1.2.2

Published

Framework-agnostic payment orchestration layer for W3 Payments ecosystem

Downloads

690

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/core

Dependencies: 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 methods
paymentIntents.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 currency

AdapterRegistry 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 files

Configuration 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

📄 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.