Skip to main content
Start here: need to register a service and create a plan first? Follow the 5-minute setup.
Add payment protection to LangChain and LangChain.js tools using the x402 protocol. The library provides two complementary approaches: Both use the same Nevermined plan, credits, and settlement flow — choose whichever fits your deployment model.

Installation

The @nevermined-io/payments/langchain sub-path export provides the requiresPayment() wrapper. For the HTTP server approach, also install express.

Approach 1: Tool Decorator / Wrapper

x402 Payment Flow (decorator)

Quick Start

In LangChain.js, requiresPayment() is a higher-order function that wraps the tool implementation:
The payment token is read from config.configurable.payment_token. Pass it when invoking the tool or agent.

Invoking with payment

LLM-driven tool calling

LangGraph ReAct agent

The same payment-protected tools work with LangGraph’s create_react_agent:

Dynamic Credits

Three patterns for credit calculation:
The credits function receives { args, result } after tool execution.

Approach 2: HTTP Server with Payment Middleware

For serving the agent over HTTP, use payment middleware on your framework. Payment is handled at the HTTP layer — tools are plain functions with no decorators or payment config.

x402 Payment Flow (HTTP)

Server: LangChain

Server: LangGraph

Replace the tool-call loop with LangGraph’s create_react_agent:
The HTTP app, middleware, and route handlers are identical to the LangChain version above.

Client: Full x402 HTTP Flow

x402 HTTP Headers

The settlement receipt (payment-response) contains:

Decorator Configuration

With Agent ID

Multiple Plans (Python only)

Scheme and Network

The decorator/wrapper automatically detects the payment scheme from plan metadata. Plans with fiat pricing (isCrypto: false) use nvm:card-delegation (Stripe). No code changes are needed on the agent side.

Complete Examples

Working seller/buyer agents with LangGraph — includes both Python and TypeScript variants:
Each includes:
  • src/server.ts / src/agent.ts — LangGraph createReactAgent with payment-protected tools
  • src/demo.tsrequiresPayment wrapper demo (seller only)
  • src/client.ts — HTTP client with full x402 payment flow

Environment Variables

Next Steps

Express Middleware (TS)

Deep dive into paymentMiddleware for Express

FastAPI Middleware (Python)

Deep dive into PaymentMiddleware for FastAPI

x402 Protocol

Deep dive into x402 payment flows

Payment Models

Configure credits, subscriptions, and dynamic pricing