This is an info Alert.
x402 Logo
  • Product
    • Core Products
      • SmartProxy
        Cost control dashboard for AI agents
      • Paywall Service
        Easy API monetization solution
      • Transaction Explorer
        Complete payment observability
  • Resources
    • x402 Ecosystem
      • Facilitators
        Payment processors powering x402
      • APIs & Services
        APIs that accept x402 payments
      • Agent Frameworks
        AI frameworks with x402 integration
      • SDKs & Libraries
        Developer tools and SDKs
    • Learn & Support
      • Networks
        Blockchain networks supporting x402
      • Use Cases
        Real-world x402 implementations
      • Documentation
        Complete x402 documentation
      • Comparisons
        How x402 compares to alternatives
    • Community
      • Blog
        Latest insights and updates
      • Support
        Get help with your integration
      • Companies
        Companies building with x402
      • About
        Learn about xpay and our mission
  • Pricing
  • Blog
  • Docs
Sign In
Get Started
LangChain

LangChain x402 Integration

LangChain's comprehensive framework combines with x402 protocol to create AI agents that can autonomously purchase data, access premium APIs, and conduct micropayments. With LangChain's robust tools system and x402's sub-2-second settlement, you can build production-ready agents that handle financial transactions intelligently while maintaining security and spending controls.
Intermediate
Python
Production Ready

⚡ x402 Integration Method

Integration Type: Tools Functions

LangChain's Tools system provides seamless x402 integration through custom payment tools with built-in error handling, retry logic, and spending controls for production payment workflows.

Setup Complexity
Medium
Maintenance
Low
Documentation
Excellent
Examples
Available

Installation & Setup

Install the necessary packages to get started with x402 payments in LangChain:

# Install the necessary packages
pip install langchain langchain-openai x402-langchain

The x402-langchain package is a helper library that simplifies wrapping facilitators into LangChain-compatible tools, bridging our facilitator ecosystem with your agent framework.

Integration Examples

Autonomous Data Purchase Agent

Build an AI agent that autonomously purchases premium market data using x402 micropayments with spending controls and error handling

Python
Intermediate
⏱️ 45 minutes
from x402_langchain import create_x402_agent
from langchain.chat_models import ChatOpenAI
from langchain.tools import BaseTool

# Configure x402 agent with spending limits
agent = create_x402_agent(
    private_key=os.getenv('X402_PRIVATE_KEY'),
    llm=ChatOpenAI(model="gpt-4"),
    spending_limits={
        'daily': 10.0,
        'per_transaction': 1.0,
        'hourly': 2.0
    },
    network='polygon'
)

class MarketDataTool(BaseTool):
    name = "market_data_purchase"
    description = "Purchase real-time market data with x402 payments"
    
    async def _arun(self, symbol: str) -> str:
        try:
            # Agent automatically handles 402 payment flow
            data = await agent.fetch_data(
                f"https://api.premium-data.com/stock/{symbol}"
            )
            return f"Market data for {symbol}: {data['price']}"
        except PaymentRequiredError as e:
            return f"Payment failed: {e}"
        except RateLimitError:
            return "Rate limited, try again later"

# Agent can now autonomously purchase data
result = await agent.run(
    "Get the latest price for AAPL and analyze the trend"
)
Prerequisites:

LangChain installation

x402-langchain package

Circle wallet setup

Polygon RPC access


Multi-Agent Payment Orchestration

Coordinate payments between multiple specialized agents for complex workflow automation

Python
Advanced
⏱️ 2 hours
from x402_langchain import AsyncX402Agent
import asyncio

class PaymentOrchestrator:
    def __init__(self):
        self.data_agent = AsyncX402Agent(
            role="data_purchaser",
            spending_limit=5.0
        )
        self.analysis_agent = AsyncX402Agent(
            role="compute_purchaser", 
            spending_limit=3.0
        )
    
    async def execute_workflow(self, query):
        # Parallel payment execution
        tasks = [
            self.data_agent.purchase_data(
                "https://api.financial-data.com/premium"
            ),
            self.analysis_agent.purchase_compute(
                "https://ml-compute.com/analysis"
            )
        ]
        
        try:
            data, analysis = await asyncio.gather(*tasks)
            return self.synthesize_results(data, analysis)
        except Exception as e:
            await self.handle_payment_failure(e)
            
    async def handle_payment_failure(self, error):
        # Implement fallback payment strategy
        if isinstance(error, InsufficientFundsError):
            await self.request_budget_increase()
        elif isinstance(error, NetworkError):
            await self.retry_with_backoff()

orchestrator = PaymentOrchestrator()
result = await orchestrator.execute_workflow(
    "Analyze market trends for tech stocks"
)
Prerequisites:

Advanced LangChain

Multi-agent patterns

Async programming

Payment error handling

Choosing Your Facilitator

The X402PaymentTool is generic and works with any facilitator that has a compatible client. Here's how you might initialize different clients based on your specific needs:

For Enterprise (CDP)
from x402_facilitators import CDPClient
client = CDPClient(api_key="...")

See the CDP Facilitator Guide for details.

For Zero Fees (Mogami)
from x402_facilitators import MogamiClient
client = MogamiClient(wallet_pk="...")

See the Mogami Facilitator Guide for details.

For Developer Experience (thirdweb)
from x402_facilitators import ThirdwebClient
client = ThirdwebClient(secret_key="...")

See the thirdweb Facilitator Guide for details.

Custom Setup
# Use any facilitator from our hub
from x402_facilitators import CustomClient
client = CustomClient(config={"..."})

Browse all 8 facilitators in our hub.

Need help choosing? Visit our Facilitator Comparison Hub to compare features, fees, and integration complexity across all 8 facilitators.

Quick Info
Category

RAG & Knowledge

Primary Language

Python

License

MIT

Latest Version

0.3.13

Resources
Official WebsiteDocumentationGitHub Repository
Community Stats

GitHub Stars

117,000

Weekly Downloads

2,500,000

Community Size

Very Large

Payment-Enabled Use Cases

Autonomous data acquisition agents

Pay-per-use API access systems

Premium content purchasing bots

Real-time market data agents

Computational resource purchasing

Agent-to-agent commerce platforms

Subscription management automation

Micropayment-enabled RAG systems

Strengths

Production-ready payment integration

Comprehensive security controls

Sub-2-second payment settlement

Zero protocol fees (only gas costs)

Supports micropayments from $0.001

Robust error handling and retry logic

Extensive LangChain ecosystem

Strong community and documentation

Limitations

Requires blockchain knowledge

Gas fees for very small payments

Network dependency for payments

Security complexity for key management

Learning curve for payment concepts

Testnet setup required for development

Get the Complete Template

Access a complete, runnable repository with working LangChain x402 integration examples, configuration templates, and step-by-step setup guides.

View on GitHub: LangChain x402 Template
⭐ Includes Docker setup, environment templates, and production deployment guides

Ready to Build Payment-Enabled Agents?

Get started with our complete LangChain x402 integration template. Includes working examples, facilitator configurations, and production-ready code.

View GitHub TemplateBrowse All Facilitators
💡 Most developers have a working integration in under 30 minutes
x402 Logo

We're building essential tools that sit between AI agents and autonomous payments, ensuring agents never overspend while enabling instant API monetization.

Community
DocumentationGitHubDiscord
Stay Updated
Subscribe to receive the latest xpay updates and agent payment control guides.
Social
  • Agentic Economy
    • Timeline
    • Protocols
  • x402 Facilitators
    • Overview
    • CDP Facilitator
    • Corbits
    • Mogami
    • thirdweb
    • PayAI
    • Meridian
    • x402.org
  • x402 APIs & Services
    • Overview
    • Firecrawl
    • Neynar
    • Pinata
    • Hyperbolic
    • Zyte API
    • Gloria AI
    • Bonsai
  • Agent Frameworks
    • Overview
    • LangChain
    • AutoGPT
    • Claude MCP
    • CrewAI
    • Autogen
    • OpenAI Assistants
  • x402 SDKs & Libraries
    • Overview
    • @coinbase/x402
    • x402-python
    • x402-rs
    • go-x402
    • mogami-x402
    • php-x402
  • x402 Networks
    • Overview
    • Base
    • Polygon
    • Ethereum
    • Arbitrum
    • Optimism
    • BNB Chain
  • x402 Use Cases
    • Overview
    • API Monetization
    • Agent Spending Controls
    • Content Monetization
    • Data Marketplaces
    • Compute Resources
    • Micropayment Streaming
  • x402 Comparisons
    • Overview
    • x402 vs Stripe
    • x402 vs Lightning
    • x402 vs Web Monetization
    • x402 vs Unlock Protocol
  • x402 Companies
    • Overview
    • Coinbase
    • Circle
    • Anthropic
    • OpenAI

© 2024 x402 Protocol. All rights reserved.Privacy PolicyTerms of ServiceAcceptable Use Policy