LangChain integration for x402 payments - let AI agents pay for APIs with USDC automatically
langchain-x402 is an early-stage Python project in the AI payments / x402 ecosystem, focused on agent-economy, ai-agents, ai-payments, autonomous-agents. It currently has 0 GitHub stars and 0 forks, and sits alongside related tools like crewai-x402, x402-pay, AgenticCommerce, Rustchain, vscode-x402, x402-payments-mcp.
Enable AI agents to pay for APIs with USDC using the x402 protocol.
Built by AgentRails — AI agent payment infrastructure for the x402 protocol.
langchain-x402 integrates the x402 payment protocol with LangChain, allowing your AI agents to autonomously access paid APIs without managing API keys or subscriptions.
x402 is the HTTP-native payment protocol that finally implements the 402 Payment Required status code. Instead of API keys and monthly subscriptions, software pays software—per request, in USDC, with cryptographic proof.
How it works:
402 Payment Required with price infoAll in a single HTTP round-trip.
pip install langchain-x402
import os
from langchain_x402 import X402Wallet, X402PaymentTool
from langchain_openai import ChatOpenAI
from langchain.agents import AgentExecutor, create_react_agent
# 1. Create a wallet with a USDC budget
wallet = X402Wallet(
private_key=os.environ["WALLET_PRIVATE_KEY"],
network="eip155:8453", # Base mainnet (CAIP-2 format)
budget_usd=10.00
)
# 2. Create the payment tool
tool = X402PaymentTool(wallet=wallet)
# 3. 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])
# 4. Agent can now access any x402-enabled API
result = executor.invoke({
"input": "Get the premium analysis from https://sandbox.agentrails.io/api/x402/protected/analysis"
})
The AgentRails Sandbox is a free test environment with x402-protected endpoints you can hit right away. No signup required to see the 402 flow in action.
curl https://sandbox.agentrails.io/api/x402/pricing
{
"endpoints": [
{ "resource": "/api/x402/protected/analysis", "amountUsdc": 0.01 },
{ "resource": "/api/x402/protected/data", "amountUsdc": 0.001 }
],
"supportedNetworks": [
"eip155:5042002", "eip155:84532", "eip155:11155111",
"eip155:8453", "eip155:1"
],
"payTo": "0x6255d8dd3f84ec460fc8b07db58ab06384a2f487"
}
curl -i https://sandbox.agentrails.io/api/x402/protected/analysis
# → 402 Payment Required
# → PAYMENT-REQUIRED: <base64-encoded payment requirements>
wallet = X402Wallet(
private_key=os.environ["WALLET_PRIVATE_KEY"],
network="eip155:84532", # Base Sepolia testnet (CAIP-2 format)
budget_usd=1.00
)
tool = X402PaymentTool(wallet=wallet)
# The tool handles the 402 → sign → retry flow automatically
result = tool.invoke({
"url": "https://sandbox.agentrails.io/api/x402/protected/analysis"
})
| Endpoint | Cost | Description |
|---|---|---|
GET /api/x402/protected/analysis |
$0.01 USDC | AI analysis (premium) |
GET /api/x402/protected/data |
$0.001 USDC | Data endpoint (micropayment) |
GET /api/x402/pricing |
Free | Pricing for all protected endpoints |
GET /api/x402/stats |
Free | Payment statistics |
Full API reference: sandbox.agentrails.io/swagger
The X402PaymentTool automatically detects 402 responses and handles payment negotiation:
tool = X402PaymentTool(
wallet=wallet,
auto_pay=True, # Automatically pay when within budget
timeout=30.0, # Request timeout in seconds
)
Set spending limits at the wallet level:
wallet = X402Wallet(
private_key=key,
network="eip155:8453",
budget_usd=5.00 # Agent can't spend more than $5
)
# Check remaining budget
print(f"Remaining: ${wallet.remaining_usd}")
# Check if can afford a specific amount
if wallet.can_afford(0.01):
print("Can afford $0.01 request")
Limit how much an agent can pay for a single request:
# In the tool input
result = tool.invoke({
"url": "https://sandbox.agentrails.io/api/x402/protected/analysis",
"max_price_usd": 0.05 # Won't pay more than $0.05 for this request
})
Track all payments made by the wallet:
for payment in wallet.payments:
print(f"{payment.resource_url}: ${payment.amount_usd}")
# Get summary
summary = wallet.get_payment_summary()
print(f"Total spent: ${summary['spent_usd']}")
print(f"Payments made: {summary['payment_count']}")
Supports multiple EVM networks using CAIP-2 identifiers:
# Base (recommended - low fees)
wallet = X402Wallet(private_key=key, network="eip155:8453")
# Ethereum
wallet = X402Wallet(private_key=key, network="eip155:1")
# Testnets
wallet = X402Wallet(private_key=key, network="eip155:84532") # Base Sepolia
wallet = X402Wallet(private_key=key, network="eip155:5042002") # Arc testnet
Legacy network names (
base-mainnet,base-sepolia, etc.) are still accepted for backwards compatibility.
X402Wallet(
private_key: str, # Hex-encoded private key
network: str, # CAIP-2 network ID (e.g., "eip155:8453")
budget_usd: float, # Maximum USD to spend
)
Properties:
address - Wallet addressspent_usd - Total USD spentremaining_usd - Remaining budgetpayments - List of PaymentRecord objectsMethods:
can_afford(amount_usd) - Check if budget allows paymentsign_payment(to, amount, valid_before) - Sign EIP-3009 authorizationget_payment_summary() - Get spending summary dictreset_budget(new_budget) - Reset budget and clear historyX402PaymentTool(
wallet: X402Wallet, # Wallet for payments
auto_pay: bool = True, # Auto-pay when within budget
timeout: float = 30.0, # HTTP timeout
)
Tool Input Schema:
{
"url": str, # Required: URL to request
"method": str = "GET", # HTTP method
"body": str | None, # Request body
"headers": dict | None, # Additional headers
"max_price_usd": float | None, # Per-request price limit
}
V2 uses CAIP-2 network identifiers:
| Network ID (CAIP-2) | Chain ID | Environment | Legacy Alias |
|---|---|---|---|
eip155:8453 |
8453 | Production | base-mainnet |
eip155:84532 |
84532 | Testnet | base-sepolia |
eip155:1 |
1 | Production | ethereum-mainnet |
eip155:11155111 |
11155111 | Testnet | ethereum-sepolia |
eip155:5042002 |
5042002 | Testnet | arc-testnet |
eip155:84532 (Base Sepolia) before mainnetwallet.get_payment_summary() regularlySee the examples/ directory:
basic_agent.py - Simple ReAct agent with payment capabilitymulti_api.py - Agent accessing multiple paid APIs| API Keys | x402 |
|---|---|
| 1 key per service | 1 wallet for all services |
| Monthly subscriptions | Pay per request |
| Human signup required | Zero onboarding |
| Credential rotation | No credentials to leak |
| Service-level limits | Agent-level budgets |
MIT License - see LICENSE for details.
Contributions welcome! Please read our contributing guidelines and submit PRs to the GitHub repository.
CrewAI integration for x402 payments - autonomous agent crews that pay for APIs with USDC
Open-source x402 payment processor for AI agents. Sub-400ms settlement on Solana + 7 EVM chains. Let LLMs pay for APIs programmatically with USDC. npm: nory-x402
x402 payment protocol implementation in .NET - enable AI agents to pay for your APIs with USDC micropayments
DePIN for Vintage Hardware — Proof-of-Antiquity blockchain where old machines outmine new ones. AI-powered hardware fingerprinting, 15+ CPU architectures, Solana bridge (wRTC). $0 VC.
Pay for APIs, unlock content, and settle x402 micropayments right inside VS Code.
Give AI agents a wallet — x402 payment tools over Model Context Protocol.
The living ecosystem where AI agents complete tasks through workflow loops, improve through iterative execution, are evaluated by mentor agents or humans in the loop, and turn completed work into reusable work experience and data to improve future agents.
The living ecosystem where AI agents complete tasks through workflow loops, improve through iterative execution, are evaluated by mentor agents or humans in the loop, and turn completed work into reusable work experience and data to improve future agents.
The AI agent with a wallet — spends USDC autonomously to get real work done. Apache-2.0, TypeScript.
The first agentic payment network: policy-controlled, gasless, and real money-ready. OmniClaw CLI + Financial Policy Engine let autonomous agents pay and earn safely at machine speed.
Multi-Agent AI Task Orchestrator 2026
Autonomous AI BD Agent for SolCex Exchange: 24/7 Cross-Chain Token Scoring & Payments 2026