---
title: "x402 Quick Start Guide"
description: "Get started quickly with bex.co's x402 facilitator service as a merchant (server) or a buyer (client)."
sidebar_position: 2
last_updated: 2026-08-20
---

# Quick Start Guide

Get started quickly with bex.co's x402 facilitator service as a merchant (server) or a buyer (client).

:::info Coming Soon
bex.co's x402 facilitator service is currently in development. This guide shows the planned API structure. [Join the waitlist](/x402) for early access.
:::

## Overview

This guide will help you:
- **Merchants (Servers)**: Protect your APIs and content with x402 payment requirements
- **Buyers (Clients)**: Enable your applications and AI agents to automatically pay for protected resources

## Prerequisites

Before you begin, you'll need:

1. **bex.co API Key**: Sign up at [bex.co/dash](https://bex.co/dash/)
2. **Wallet Setup**: A wallet with USDC on supported networks (Sui recommended)
3. **Node.js 18+** or **Python 3.8+** (depending on your stack)

## For Servers (Merchants)

### Installation

import Tabs from '@theme/Tabs';
import TabItem from '@theme/TabItem';

<Tabs groupId="server-language">
<TabItem value="typescript" label="TypeScript" default>

```bash
npm install @bex/x402-sdk
# or
yarn add @bex/x402-sdk
```

</TabItem>
<TabItem value="python" label="Python">

```bash
pip install bex-x402
```

</TabItem>
</Tabs>

### Basic Server Setup

<Tabs groupId="server-language">
<TabItem value="typescript" label="TypeScript (Express)" default>

```typescript
import express from 'express';
import { X402Middleware } from '@bex/x402-sdk';

const app = express();

// Configure x402 middleware
const x402 = X402Middleware({
  apiKey: process.env.BEX_API_KEY,
  facilitatorUrl: 'https://x402.bex.co',
  network: 'sui', // Default network
  token: 'USDC',
});

// Protect your endpoints with x402
app.get('/api/premium/data',
  x402.require({
    amount: '0.01', // 1 cent in USDC
    network: 'sui',
  }),
  (req, res) => {
    // Payment verified - deliver content
    res.json({
      data: 'Your premium content here',
      payment: {
        txHash: req.x402.txHash,
        amount: req.x402.amount,
        network: req.x402.network,
      }
    });
  }
);

app.listen(3000, () => {
  console.log('Server running on http://localhost:3000');
});
```

</TabItem>
<TabItem value="typescript-hono" label="TypeScript (Hono)">

```typescript
import { Hono } from 'hono';
import { x402Middleware } from '@bex/x402-sdk/hono';

const app = new Hono();

// Configure x402 middleware
app.use('/api/premium/*', x402Middleware({
  apiKey: process.env.BEX_API_KEY,
  facilitatorUrl: 'https://x402.bex.co',
  network: 'sui',
  token: 'USDC',
  amount: '0.01',
}));

app.get('/api/premium/data', (c) => {
  const payment = c.get('x402');

  return c.json({
    data: 'Your premium content here',
    payment: {
      txHash: payment.txHash,
      amount: payment.amount,
    }
  });
});

export default app;
```

</TabItem>
<TabItem value="python" label="Python (FastAPI)">

```python
from fastapi import FastAPI, Depends
from bex_x402 import X402Middleware, X402Payment

app = FastAPI()

# Configure x402 middleware
x402 = X402Middleware(
    api_key=os.environ["BEX_API_KEY"],
    facilitator_url="https://x402.bex.co",
    network="sui",
    token="USDC",
)

@app.get("/api/premium/data")
async def get_premium_data(
    payment: X402Payment = Depends(x402.require(amount="0.01"))
):
    """Protected endpoint requiring 0.01 USDC payment"""
    return {
        "data": "Your premium content here",
        "payment": {
            "tx_hash": payment.tx_hash,
            "amount": payment.amount,
            "network": payment.network,
        }
    }

if __name__ == "__main__":
    import uvicorn
    uvicorn.run(app, host="0.0.0.0", port=8000)
```

</TabItem>
<TabItem value="python-flask" label="Python (Flask)">

```python
from flask import Flask, jsonify
from bex_x402 import X402Middleware

app = Flask(__name__)

# Configure x402 middleware
x402 = X402Middleware(
    api_key=os.environ["BEX_API_KEY"],
    facilitator_url="https://x402.bex.co",
    network="sui",
    token="USDC",
)

@app.route('/api/premium/data')
@x402.require(amount="0.01")
def get_premium_data(payment):
    """Protected endpoint requiring 0.01 USDC payment"""
    return jsonify({
        "data": "Your premium content here",
        "payment": {
            "tx_hash": payment.tx_hash,
            "amount": payment.amount,
            "network": payment.network,
        }
    })

if __name__ == '__main__':
    app.run(debug=True, port=8000)
```

</TabItem>
</Tabs>

### How Server Middleware Works

1. **Request arrives** without payment → Middleware returns `402 Payment Required` with payment details
2. **Request arrives with payment** → Middleware verifies signature with bex.co facilitator
3. **Payment verified** → Request proceeds to your handler with payment details attached
4. **Verification fails** → Returns `402 Payment Required` with error details

## For Clients (Buyers)

### Installation

<Tabs groupId="client-language">
<TabItem value="typescript" label="TypeScript" default>

```bash
npm install @bex/x402-client
# or
yarn add @bex/x402-client
```

</TabItem>
<TabItem value="python" label="Python">

```bash
pip install bex-x402-client
```

</TabItem>
</Tabs>

### Basic Client Setup

<Tabs groupId="client-language">
<TabItem value="typescript-fetch" label="TypeScript (Fetch)" default>

```typescript
import { X402Client } from '@bex/x402-client';

// Initialize client with wallet
const client = new X402Client({
  privateKey: process.env.WALLET_PRIVATE_KEY,
  network: 'sui',
  facilitatorUrl: 'https://x402.bex.co',
});

// Fetch protected resource - payment handled automatically
async function fetchPremiumData() {
  try {
    const response = await client.fetch(
      'https://api.example.com/api/premium/data'
    );

    const data = await response.json();
    console.log('Data:', data);
    console.log('Payment TX:', response.headers.get('X-Payment-Response'));
  } catch (error) {
    console.error('Request failed:', error);
  }
}

fetchPremiumData();
```

</TabItem>
<TabItem value="typescript-axios" label="TypeScript (Axios)">

```typescript
import axios from 'axios';
import { createX402Interceptor } from '@bex/x402-client';

// Create axios instance with x402 interceptor
const api = axios.create({
  baseURL: 'https://api.example.com',
});

// Add x402 payment interceptor
createX402Interceptor(api, {
  privateKey: process.env.WALLET_PRIVATE_KEY,
  network: 'sui',
  facilitatorUrl: 'https://x402.bex.co',
});

// Make requests normally - payments handled automatically
async function fetchPremiumData() {
  try {
    const response = await api.get('/api/premium/data');
    console.log('Data:', response.data);
  } catch (error) {
    console.error('Request failed:', error);
  }
}

fetchPremiumData();
```

</TabItem>
<TabItem value="python-httpx" label="Python (httpx)">

```python
import os
from bex_x402_client import X402Client

# Initialize client with wallet
client = X402Client(
    private_key=os.environ["WALLET_PRIVATE_KEY"],
    network="sui",
    facilitator_url="https://x402.bex.co",
)

# Fetch protected resource - payment handled automatically
async def fetch_premium_data():
    response = await client.get(
        "https://api.example.com/api/premium/data"
    )

    data = response.json()
    print(f"Data: {data}")
    print(f"Payment TX: {response.headers.get('X-Payment-Response')}")

# Run async function
import asyncio
asyncio.run(fetch_premium_data())
```

</TabItem>
<TabItem value="python-requests" label="Python (requests)">

```python
import os
import requests
from bex_x402_client import X402Session

# Create session with x402 support
session = X402Session(
    private_key=os.environ["WALLET_PRIVATE_KEY"],
    network="sui",
    facilitator_url="https://x402.bex.co",
)

# Make requests normally - payments handled automatically
def fetch_premium_data():
    response = session.get(
        "https://api.example.com/api/premium/data"
    )

    data = response.json()
    print(f"Data: {data}")
    print(f"Payment TX: {response.headers.get('X-Payment-Response')}")

fetch_premium_data()
```

</TabItem>
</Tabs>

### How Client Library Works

1. **Makes initial request** to protected endpoint
2. **Receives 402 response** with payment requirements
3. **Signs payment authorization** using your wallet
4. **Retries request** with `X-Payment` header containing signature
5. **Receives content** after payment verification

## AI Agent Integration

### Claude MCP (Model Context Protocol)

```typescript
import { X402MCPServer } from '@bex/x402-mcp';

const server = new X402MCPServer({
  wallet: process.env.AGENT_WALLET_PRIVATE_KEY,
  network: 'sui',
  facilitatorUrl: 'https://x402.bex.co',
  spendingLimit: {
    daily: '10.00', // Max $10 per day
    perTransaction: '1.00', // Max $1 per transaction
  }
});

// Register with Claude
server.start();
```

Now Claude can autonomously discover and pay for x402-protected services.

### LangChain Integration

```python
from langchain.tools import Tool
from bex_x402_client import X402Client

# Create x402-enabled HTTP client for agent
client = X402Client(
    private_key=os.environ["AGENT_WALLET_PRIVATE_KEY"],
    network="sui",
    facilitator_url="https://x402.bex.co",
)

# Create tool for LangChain agent
x402_fetch_tool = Tool(
    name="x402_fetch",
    description="Fetch data from x402-protected APIs with automatic payment",
    func=lambda url: client.get(url).json()
)

# Add to your agent's tools
agent_tools.append(x402_fetch_tool)
```

## Facilitator Configuration

### bex.co Facilitator

**Facilitator URL**: `https://x402.bex.co`

**Available Endpoints**:
- `/verify` - Verify payment signature
- `/settle` - Execute on-chain settlement
- `/list` - List supported networks and tokens

### Environment Variables

```bash
# Server configuration
BEX_API_KEY=your_api_key_here
BEX_X402_FACILITATOR=https://x402.bex.co

# Client configuration
WALLET_PRIVATE_KEY=your_private_key_here
X402_NETWORK=sui
```

## Supported Networks

bex.co's x402 facilitator supports the following networks:

| Network | Chain ID | Token | Status |
|---------|----------|-------|--------|
| Sui Mainnet | `sui` | USDC | <ion-icon name="checkmark-circle" style={{verticalAlign: "middle", fontSize: "1.2em", color: "#10b981"}}></ion-icon> Primary |
| Sui Testnet | `sui-testnet` | USDC | <ion-icon name="checkmark-circle" style={{verticalAlign: "middle", fontSize: "1.2em", color: "#10b981"}}></ion-icon> Active |
| Base Mainnet | `base` | USDC | <ion-icon name="time-outline" style={{verticalAlign: "middle", fontSize: "1.2em", color: "#f59e0b"}}></ion-icon> Coming Soon |
| Base Sepolia | `base-sepolia` | USDC | <ion-icon name="time-outline" style={{verticalAlign: "middle", fontSize: "1.2em", color: "#f59e0b"}}></ion-icon> Coming Soon |
| Ethereum | `ethereum` | USDC | <ion-icon name="time-outline" style={{verticalAlign: "middle", fontSize: "1.2em", color: "#f59e0b"}}></ion-icon> Coming Soon |
| Polygon | `polygon` | USDC | <ion-icon name="time-outline" style={{verticalAlign: "middle", fontSize: "1.2em", color: "#f59e0b"}}></ion-icon> Coming Soon |
| Avalanche | `avalanche` | USDC | <ion-icon name="time-outline" style={{verticalAlign: "middle", fontSize: "1.2em", color: "#f59e0b"}}></ion-icon> Coming Soon |
| Aptos Mainnet | `aptos` | USDC | <ion-icon name="time-outline" style={{verticalAlign: "middle", fontSize: "1.2em", color: "#f59e0b"}}></ion-icon> Coming Soon |
| Aptos Testnet | `aptos-testnet` | USDC | <ion-icon name="time-outline" style={{verticalAlign: "middle", fontSize: "1.2em", color: "#f59e0b"}}></ion-icon> Coming Soon |

:::tip Sui-First Optimization
bex.co prioritizes Sui for the best x402 experience with sub-200ms settlement times and ultra-low costs.
:::

## Payment Configuration Options

### Server-Side Options

```typescript
X402Middleware({
  apiKey: 'your_api_key',
  facilitatorUrl: 'https://x402.bex.co',

  // Payment requirements
  network: 'sui',
  token: 'USDC',
  amount: '0.01',

  // Optional configurations
  validDuration: 300, // Payment valid for 5 minutes
  recipient: '0x742d...', // Your wallet address

  // Callbacks
  onPaymentReceived: (payment) => {
    console.log('Payment received:', payment);
  },
  onPaymentFailed: (error) => {
    console.error('Payment failed:', error);
  },
})
```

### Client-Side Options

```typescript
new X402Client({
  privateKey: 'your_private_key',
  network: 'sui',
  facilitatorUrl: 'https://x402.bex.co',

  // Optional configurations
  maxAmount: '1.00', // Max amount to auto-pay
  requireConfirmation: true, // Prompt before payment
  timeout: 30000, // Request timeout in ms

  // Callbacks
  onPaymentRequired: (details) => {
    console.log('Payment required:', details);
    return true; // Return false to cancel
  },
  onPaymentComplete: (txHash) => {
    console.log('Payment complete:', txHash);
  },
})
```

## Testing Your Integration

### Test with curl

```bash
# 1. Request protected resource (should get 402)
curl -X GET https://api.example.com/api/premium/data \
  -H "Content-Type: application/json" \
  -v

# Response: 402 Payment Required
# X-Payment-Required: exact amount=0.01 token=USDC network=sui recipient=0x742d...

# 2. Generate payment signature (using SDK or manually)
# 3. Retry with payment header
curl -X GET https://api.example.com/api/premium/data \
  -H "Content-Type: application/json" \
  -H "X-Payment: <your_signed_payment>" \
  -v

# Response: 200 OK with content and X-Payment-Response header
```

### Test with SDK

<Tabs groupId="client-language">
<TabItem value="typescript" label="TypeScript" default>

```typescript
import { X402Client } from '@bex/x402-client';

const client = new X402Client({
  privateKey: process.env.TEST_WALLET_KEY,
  network: 'sui-testnet', // Use testnet
  facilitatorUrl: 'https://x402.bex.co',
});

// Test payment flow
const response = await client.fetch(
  'http://localhost:3000/api/premium/data'
);

console.log('Status:', response.status);
console.log('Payment TX:', response.headers.get('X-Payment-Response'));
console.log('Data:', await response.json());
```

</TabItem>
<TabItem value="python" label="Python">

```python
from bex_x402_client import X402Client

client = X402Client(
    private_key=os.environ["TEST_WALLET_KEY"],
    network="sui-testnet",  # Use testnet
    facilitator_url="https://x402.bex.co",
)

# Test payment flow
response = client.get("http://localhost:8000/api/premium/data")

print(f"Status: {response.status_code}")
print(f"Payment TX: {response.headers.get('X-Payment-Response')}")
print(f"Data: {response.json()}")
```

</TabItem>
</Tabs>

## Security Best Practices

1. **Never commit private keys** - Use environment variables or secure key management
2. **Validate payment amounts** - Check that received payments match expected amounts
3. **Set spending limits** - Configure max amounts for AI agents
4. **Use testnet first** - Test thoroughly on testnet before mainnet
5. **Monitor transactions** - Track payments and detect anomalies
6. **Implement rate limiting** - Prevent abuse of your protected endpoints
7. **Log all payments** - Maintain audit trail of transactions

## Troubleshooting

### Common Issues

**402 Error: "Invalid signature"**
- Check that your private key is correct
- Verify the network matches (mainnet vs testnet)
- Ensure client and server use same facilitator URL

**402 Error: "Insufficient balance"**
- Verify wallet has enough USDC
- Check wallet has enough native tokens for gas (if required)
- Confirm you're on the correct network

**Timeout errors**
- Increase client timeout setting
- Check network connectivity
- Verify facilitator service is operational

**Payment not settling**
- Check transaction on block explorer
- Verify recipient address is correct
- Ensure network is not congested

## Next Steps

- **[Read Introduction](/docs/x402/introduction)** - Learn more about x402 protocol
- **[View Landing Page](/x402)** - bex.co x402 facilitator service
- **[Join Discord](https://discord.gg/GqzTYQ4YNa)** - Get help from community
- **[Join Waitlist](/x402)** - Get early access to bex.co x402 facilitator

## Need Help?

- **Documentation**: Browse our comprehensive guides
- **Discord**: Join our community at [discord.gg/GqzTYQ4YNa](https://discord.gg/GqzTYQ4YNa)
- **Email**: Contact hello@bex.co
- **GitHub**: Report issues and contribute

---

**Ready to get started?** [Join the waitlist](/x402) for early access to bex.co's x402 facilitator service.
