---
title: x402
description: Enable AI agents to pay for APIs with USDC using the x402 payment protocol
---

# x402

[x402](https://x402.org) is the HTTP-native payment protocol that implements the `402 Payment Required` status code. Instead of API keys and monthly subscriptions, software pays software—per request, in USDC, with cryptographic proof.

The `langchain-x402` package provides a LangChain tool that automatically handles x402 payments, allowing your agents to access any x402-enabled API without managing credentials or subscriptions.

## Installation

```bash
pip install langchain-x402
```

## Setup

You'll need:
1. A wallet private key (for signing USDC payments)
2. USDC balance on a supported network (Base, Ethereum, or testnets)

```python
import os

# Set your wallet private key (use environment variables in production)
os.environ["WALLET_PRIVATE_KEY"] = "your-private-key-hex"
```

### Supported Networks

| Network | Chain ID | Environment |
|---------|----------|-------------|
| `base-mainnet` | 8453 | Production |
| `base-sepolia` | 84532 | Testnet |
| `ethereum-mainnet` | 1 | Production |
| `arc-testnet` | 5042002 | Testnet |

## Usage

### Basic Example

```python
from langchain_x402 import X402Wallet, X402PaymentTool
from langchain_openai import ChatOpenAI
from langchain.agents import AgentExecutor, create_react_agent

# Create a wallet with a spending budget
wallet = X402Wallet(
    private_key=os.environ["WALLET_PRIVATE_KEY"],
    network="base-mainnet",
    budget_usd=10.00
)

# Create the payment tool
tool = X402PaymentTool(wallet=wallet)

# Add to your agent
llm = ChatOpenAI(model="gpt-4o")
agent = create_react_agent(llm, tools=[tool], prompt=your_prompt)
executor = AgentExecutor(agent=agent, tools=[tool])

# Agent can now access any x402-enabled API
result = executor.invoke({
    "input": "Get data from https://api.example.com/paid-endpoint"
})
```

### Budget Controls

Set spending limits to control agent costs:

```python
wallet = X402Wallet(
    private_key=key,
    network="base-mainnet",
    budget_usd=5.00  # Agent can't spend more than $5
)

# Check remaining budget
print(f"Remaining: ${wallet.remaining_usd}")

# Get spending summary
summary = wallet.get_payment_summary()
print(f"Total spent: ${summary['spent_usd']}")
print(f"Payments made: {summary['payment_count']}")
```

### Per-Request Price Limits

Limit how much an agent pays for a single request:

```python
result = tool.invoke({
    "url": "https://api.example.com/expensive",
    "max_price_usd": 0.05  # Won't pay more than $0.05
})
```

## How It Works

1. Agent requests a resource using the tool
2. If the server returns `402 Payment Required`, the tool reads the payment requirements
3. Tool signs a USDC payment authorization (EIP-3009)
4. Tool retries the request with the signed payment
5. Server settles on-chain and returns the data

All of this happens automatically in a single tool invocation.

## API Reference

### X402Wallet

```python
X402Wallet(
    private_key: str,      # Hex-encoded private key
    network: str,          # Network name (e.g., "base-mainnet")
    budget_usd: float,     # Maximum USD to spend
)
```

**Properties:**
- `address` - Wallet address
- `spent_usd` - Total USD spent
- `remaining_usd` - Remaining budget
- `payments` - List of payment records

### X402PaymentTool

```python
X402PaymentTool(
    wallet: X402Wallet,    # Wallet for payments
    auto_pay: bool = True, # Auto-pay when within budget
    timeout: float = 30.0, # HTTP timeout in seconds
)
```

**Tool Input:**
- `url` (required) - URL to request
- `method` - HTTP method (default: "GET")
- `body` - Request body
- `headers` - Additional headers
- `max_price_usd` - Per-request price limit

## Resources

- [PyPI Package](https://pypi.org/project/langchain-x402/)
- [GitHub Repository](https://github.com/kmatthewsio/langchain-x402)
- [x402 Protocol Specification](https://x402.org)
- [AgentRails Documentation](https://agentrails.io/docs)
- [Try the Sandbox](https://sandbox.agentrails.io/swagger)
