Quick Start

Get started with b402Layer Payment Infrastructure in under 5 minutes.


Prerequisites

Before you begin, ensure you have:

  • Node.js 18.0 or higher

  • npm or yarn package manager

  • A BNB Chain wallet with some BNB for gas fees

  • Basic knowledge of TypeScript and async/await


Installation

Install the b402Layer Payment SDK:

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

Step 1: Initialize the Client

Create a new client instance with your API credentials:

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

const client = new B402Client({
    apiKey: 'your-api-key',           // Get from dashboard
    network: 'bnb-mainnet',            // or 'bnb-testnet' for testing
});

Getting Your API Key

  1. Connect your wallet

  2. Navigate to API Keys section

  3. Click Generate New Key

  4. Copy and securely store your API key

⚠️ Security Note: Never commit API keys to version control. Use environment variables instead.

const client = new B402Client({
    apiKey: process.env.B402_API_KEY,
    network: process.env.B402_NETWORK || 'bnb-testnet',
});

Step 2: Create a Payment

Create a payment request for your AI agent transaction:

async function createPayment() {
    const payment = await client.payment.create({
        amount: '10.5',                                    // Amount to charge
        currency: 'USDT',                                  // Token symbol
        recipient: '0x742d35Cc6634C0532925a3b844Bc9e7595f0bEb',  // Recipient address
        metadata: {
            orderId: 'order-123',
            description: 'Weather API Service',
            agentId: 'weather-agent-001',
        },
    });

    console.log('Payment ID:', payment.id);
    console.log('Payment Status:', payment.status);
    console.log('Payment URL:', payment.paymentUrl);
    
    return payment;
}

Payment Response

{
    id: 'pay_1a2b3c4d5e6f',
    status: 'pending',
    amount: '10.5',
    currency: 'USDT',
    recipient: '0x742d35Cc6634C0532925a3b844Bc9e7595f0bEb',
    paymentUrl: 'https://pay.b402layer.io/pay_1a2b3c4d5e6f',
    expiresAt: '2024-01-15T10:30:00Z',
    createdAt: '2024-01-15T10:00:00Z',
    metadata: {
        orderId: 'order-123',
        description: 'Weather API Service',
        agentId: 'weather-agent-001',
    }
}

Step 3: Check Payment Status

Query the current status of a payment:

async function checkPayment(paymentId: string) {
    const status = await client.payment.getStatus(paymentId);
    
    console.log('Current Status:', status.state);
    console.log('Transaction Hash:', status.txHash);
    console.log('Confirmations:', status.confirmations);
    
    return status;
}

// Usage
const status = await checkPayment('pay_1a2b3c4d5e6f');

Payment States

State
Description

pending

Payment created, awaiting transaction

processing

Transaction submitted to blockchain

confirming

Transaction confirmed, waiting for required confirmations

confirmed

Payment successfully completed

failed

Payment failed or expired

refunded

Payment refunded to sender


Step 4: Listen to Payment Events

Monitor payment status changes in real-time:

function listenPaymentEvents(paymentId: string) {
    client.payment.on(paymentId, (event) => {
        console.log('Payment Update:', event.status);
        console.log('Timestamp:', event.timestamp);
        
        switch (event.status) {
            case 'processing':
                console.log('💫 Transaction submitted:', event.txHash);
                break;
            case 'confirming':
                console.log('⏳ Confirming... (' + event.confirmations + '/12)');
                break;
            case 'confirmed':
                console.log('✅ Payment confirmed!');
                console.log('Block:', event.blockNumber);
                // Deliver service to customer
                deliverService(event.paymentId);
                break;
            case 'failed':
                console.log('❌ Payment failed:', event.error);
                // Handle failure
                handlePaymentFailure(event.paymentId);
                break;
        }
    });
}

// Usage
listenPaymentEvents('pay_1a2b3c4d5e6f');

Step 5: Complete Flow Example

Here's a complete example combining all steps:

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

// Initialize client
const client = new B402Client({
    apiKey: process.env.B402_API_KEY!,
    network: 'bnb-mainnet',
});

async function processPayment() {
    try {
        // 1. Create payment request
        console.log('Creating payment...');
        const payment = await client.payment.create({
            amount: '10.5',
            currency: 'USDT',
            recipient: '0x742d35Cc6634C0532925a3b844Bc9e7595f0bEb',
            metadata: {
                orderId: 'order-123',
                description: 'Weather API Service',
            },
        });
        
        console.log('✅ Payment created:', payment.id);
        console.log('📋 Payment URL:', payment.paymentUrl);
        
        // 2. Set up event listener
        client.payment.on(payment.id, (event) => {
            console.log('📡 Status update:', event.status);
            
            if (event.status === 'confirmed') {
                console.log('✅ Payment confirmed!');
                console.log('🔗 Transaction:', event.txHash);
            }
        });
        
        // 3. Poll for status (alternative to events)
        const checkStatus = async () => {
            const status = await client.payment.getStatus(payment.id);
            console.log('Current status:', status.state);
            
            if (status.state === 'confirmed') {
                console.log('Payment complete!');
                return true;
            } else if (status.state === 'failed') {
                console.log('Payment failed!');
                return true;
            }
            
            return false;
        };
        
        // Check every 5 seconds
        const interval = setInterval(async () => {
            const done = await checkStatus();
            if (done) {
                clearInterval(interval);
            }
        }, 5000);
        
        return payment;
        
    } catch (error) {
        console.error('❌ Payment error:', error);
        throw error;
    }
}

// Run the example
processPayment()
    .then(() => console.log('Done!'))
    .catch(console.error);

Supported Networks

Network
Chain ID
RPC Endpoint

BNB Mainnet

56

https://bsc-dataseed.binance.org/

BNB Testnet

97

https://data-seed-prebsc-1-s1.binance.org:8545/


Supported Tokens

The Payment Layer currently supports the following tokens on BNB Chain:

  • BNB - Native token

  • USDT - Tether USD (BEP-20)

  • USDC - USD Coin (BEP-20)

  • BUSD - Binance USD (BEP-20)

💡 Need support for additional tokens? Contact us or open an issue on GitHub.


Testing on Testnet

For development and testing, use BNB Testnet:

const client = new B402Client({
    apiKey: process.env.B402_API_KEY!,
    network: 'bnb-testnet',  // Use testnet
});

Get Testnet Tokens

  1. BNB Testnet Faucet: https://testnet.binance.org/faucet-smart

  2. USDT Testnet: Request from our Discord community


Next Steps

Now that you've completed the quick start, explore more advanced features:


Need Help?

  • 📚 Check our FAQ

  • 🐛 Report issues on GitHub

  • 💬 Join the conversation on Twitter


Ready to build the future of AI commerce? Let's go! 🚀

Last updated