API Reference

Complete API reference for the b402Layer Payment SDK.


Installation

npm install @b402Layer/payment-sdk
# or
yarn add @b402Layer/payment-sdk

B402Client

Main client class for interacting with b402Layer Payment Infrastructure.

Constructor

new B402Client(config: ClientConfig)

ClientConfig

Property
Type
Required
Description

apiKey

string

Yes

Your API key from dashboard

network

string

Yes

Network: 'bnb-mainnet' or 'bnb-testnet'

timeout

number

No

Request timeout in ms (default: 30000)

retries

number

No

Number of retry attempts (default: 3)

Example

import { B402Client } from '@b402Layer/payment-sdk';

const client = new B402Client({
    apiKey: process.env.B402_API_KEY!,
    network: 'bnb-mainnet',
    timeout: 60000,
    retries: 5
});

Payment Methods

client.payment.create()

Create a new payment request.

client.payment.create(params: CreatePaymentParams): Promise<Payment>

CreatePaymentParams

Property
Type
Required
Description

amount

string

Yes

Payment amount

currency

string

Yes

Token symbol (BNB, USDT, USDC, BUSD)

recipient

string

Yes

Recipient wallet address

metadata

object

No

Custom metadata

expiresIn

number

No

Expiration time in seconds

webhook

string

No

Webhook URL for notifications

Returns: Payment

interface Payment {
    id: string;
    status: PaymentStatus;
    amount: string;
    currency: string;
    recipient: string;
    payer?: string;
    txHash?: string;
    blockNumber?: number;
    confirmations?: number;
    paymentUrl: string;
    expiresAt: string;
    createdAt: string;
    updatedAt: string;
    metadata?: Record<string, any>;
}

Example

const payment = await client.payment.create({
    amount: '10.5',
    currency: 'USDT',
    recipient: '0x742d35Cc6634C0532925a3b844Bc9e7595f0bEb',
    metadata: {
        orderId: 'order-123',
        description: 'API Service Payment'
    },
    expiresIn: 600,  // 10 minutes
    webhook: 'https://myapp.com/webhooks/payment'
});

console.log('Payment ID:', payment.id);
console.log('Payment URL:', payment.paymentUrl);

client.payment.getStatus()

Get the current status of a payment.

client.payment.getStatus(paymentId: string): Promise<PaymentStatus>

Returns: PaymentStatus

interface PaymentStatus {
    id: string;
    state: 'pending' | 'processing' | 'confirming' | 'confirmed' | 'failed' | 'expired' | 'refunded';
    txHash?: string;
    blockNumber?: number;
    confirmations?: number;
    timestamp: string;
}

Example

const status = await client.payment.getStatus('pay_1a2b3c4d5e6f');

console.log('Status:', status.state);
console.log('Transaction:', status.txHash);
console.log('Confirmations:', status.confirmations);

client.payment.on()

Listen to payment status updates in real-time.

client.payment.on(
    paymentId: string,
    callback: (event: PaymentEvent) => void
): void

PaymentEvent

interface PaymentEvent {
    paymentId: string;
    status: PaymentState;
    txHash?: string;
    blockNumber?: number;
    confirmations?: number;
    timestamp: string;
    error?: string;
}

Example

client.payment.on('pay_1a2b3c4d5e6f', (event) => {
    console.log('Payment update:', event.status);
    
    if (event.status === 'confirmed') {
        console.log('✅ Payment confirmed!');
        deliverService(event.paymentId);
    } else if (event.status === 'failed') {
        console.log('❌ Payment failed:', event.error);
        handleFailure(event.paymentId);
    }
});

client.payment.cancel()

Cancel a pending payment.

client.payment.cancel(paymentId: string): Promise<void>

Example

await client.payment.cancel('pay_1a2b3c4d5e6f');
console.log('Payment cancelled');

client.payment.refund()

Refund a completed payment.

client.payment.refund(
    paymentId: string,
    reason?: string
): Promise<Refund>

Returns: Refund

interface Refund {
    id: string;
    paymentId: string;
    amount: string;
    currency: string;
    status: 'pending' | 'processing' | 'completed' | 'failed';
    txHash?: string;
    reason?: string;
    createdAt: string;
}

Example

const refund = await client.payment.refund(
    'pay_1a2b3c4d5e6f',
    'Service not delivered'
);

console.log('Refund ID:', refund.id);
console.log('Refund status:', refund.status);

client.payment.list()

List all payments with optional filters.

client.payment.list(filters?: PaymentFilters): Promise<Payment[]>

PaymentFilters

Property
Type
Description

status

PaymentState

Filter by status

currency

string

Filter by currency

from

Date

Start date

to

Date

End date

limit

number

Maximum results (default: 100)

offset

number

Pagination offset

Example

const payments = await client.payment.list({
    status: 'confirmed',
    currency: 'USDT',
    from: new Date('2024-01-01'),
    to: new Date('2024-01-31'),
    limit: 50
});

console.log('Found', payments.length, 'payments');

Batch Payment Methods

client.payment.createBatch()

Create multiple payments in a single transaction.

client.payment.createBatch(
    payments: CreatePaymentParams[]
): Promise<BatchPayment>

Returns: BatchPayment

interface BatchPayment {
    id: string;
    payments: Payment[];
    totalAmount: string;
    totalFee: string;
    status: 'pending' | 'processing' | 'completed' | 'failed';
    createdAt: string;
}

Example

const batch = await client.payment.createBatch([
    {
        recipient: '0xAgent1...',
        amount: '5.0',
        currency: 'USDT'
    },
    {
        recipient: '0xAgent2...',
        amount: '10.0',
        currency: 'USDT'
    }
]);

console.log('Batch ID:', batch.id);
console.log('Total:', batch.totalAmount);

Webhook Methods

client.webhook.create()

Register a webhook endpoint.

client.webhook.create(config: WebhookConfig): Promise<Webhook>

WebhookConfig

Property
Type
Required
Description

url

string

Yes

Webhook endpoint URL

events

string[]

Yes

Events to subscribe to

secret

string

No

Webhook signing secret

Example

const webhook = await client.webhook.create({
    url: 'https://myapp.com/webhooks/b402',
    events: ['payment.confirmed', 'payment.failed'],
    secret: 'whsec_...'
});

console.log('Webhook ID:', webhook.id);

client.webhook.verify()

Verify webhook signature.

client.webhook.verify(
    payload: string,
    signature: string,
    secret: string
): boolean

Example

// In your webhook handler
app.post('/webhooks/b402', (req, res) => {
    const signature = req.headers['x-b402-signature'];
    const payload = JSON.stringify(req.body);
    
    const isValid = client.webhook.verify(
        payload,
        signature,
        process.env.WEBHOOK_SECRET!
    );
    
    if (!isValid) {
        return res.status(401).send('Invalid signature');
    }
    
    // Process webhook
    const event = req.body;
    console.log('Webhook event:', event.type);
    
    res.status(200).send('OK');
});

Utility Methods

client.utils.estimateFee()

Estimate transaction fee for a payment.

client.utils.estimateFee(
    amount: string,
    currency: string
): Promise<FeeEstimate>

Returns: FeeEstimate

interface FeeEstimate {
    gasFee: string;
    platformFee: string;
    totalFee: string;
    currency: string;
}

Example

const fee = await client.utils.estimateFee('10.0', 'USDT');

console.log('Gas fee:', fee.gasFee);
console.log('Platform fee:', fee.platformFee);
console.log('Total fee:', fee.totalFee);

client.utils.validateAddress()

Validate a wallet address.

client.utils.validateAddress(address: string): boolean

Example

const isValid = client.utils.validateAddress('0x742d35Cc6634C0532925a3b844Bc9e7595f0bEb');
console.log('Valid address:', isValid);

Error Handling

All SDK methods throw typed errors that you can catch and handle:

import { 
    B402Error,
    PaymentNotFoundError,
    InsufficientFundsError,
    NetworkError
} from '@b402Layer/payment-sdk';

try {
    const payment = await client.payment.create({
        amount: '10.5',
        currency: 'USDT',
        recipient: '0x742d35Cc6634C0532925a3b844Bc9e7595f0bEb'
    });
} catch (error) {
    if (error instanceof PaymentNotFoundError) {
        console.error('Payment not found');
    } else if (error instanceof InsufficientFundsError) {
        console.error('Insufficient funds');
    } else if (error instanceof NetworkError) {
        console.error('Network error:', error.message);
    } else if (error instanceof B402Error) {
        console.error('B402 error:', error.code, error.message);
    } else {
        console.error('Unknown error:', error);
    }
}

Error Types

Error Class
Description

B402Error

Base error class

PaymentNotFoundError

Payment ID not found

InsufficientFundsError

Insufficient balance

InvalidAddressError

Invalid wallet address

PaymentExpiredError

Payment has expired

NetworkError

Network/RPC error

ValidationError

Invalid parameters

AuthenticationError

Invalid API key

RateLimitError

Rate limit exceeded


TypeScript Types

The SDK is fully typed. Import types as needed:

import {
    Payment,
    PaymentStatus,
    PaymentEvent,
    CreatePaymentParams,
    BatchPayment,
    Webhook,
    FeeEstimate
} from '@b402Layer/payment-sdk';

Next Steps


Full API documentation available on GitHub

Last updated