Start here: need to register a service and create a plan first? Follow the
5-minute setup.
PaymentMiddleware handles verification and settlement automatically.
x402 Payment Flow
Installation
The
[fastapi] extra installs FastAPI and Starlette dependencies required for the middleware.Quick Start: One-Line Payment Protection
ThePaymentMiddleware from payments_py.x402.fastapi handles the entire x402 flow:
- Returns
402withpayment-requiredheader when no token is provided - Verifies the x402 token via the Nevermined facilitator
- Burns credits after request completion
- Returns
payment-responseheader with settlement receipt
x402 Headers
The middleware follows the x402 HTTP transport spec:Route Configuration
Fixed Credits
Path Parameters
With Agent ID
Using RouteConfig
For more explicit configuration, useRouteConfig:
When
scheme is omitted, the middleware calls resolve_scheme() to auto-detect the correct scheme from plan metadata. Plans with fiat pricing (isCrypto: false) automatically use nvm:card-delegation (Stripe).Dynamic Credits
Calculate credits based on request data:Payment Scheme (Crypto vs. Fiat)
The middleware auto-detects the payment scheme from plan metadata. Plans with fiat pricing (isCrypto: false) automatically use nvm:card-delegation (Stripe), while crypto plans use nvm:erc4337.
You can explicitly override the scheme in the route configuration:
The middleware 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. You can explicitly override with
the scheme parameter.Middleware Options
Accessing Payment Context
After verification, the payment context is available inrequest.state.payment_context:
Complete Example
See the complete working example in the http-simple-agent-py tutorial on GitHub.With Observability
For full observability integration with Helicone:Client Implementation
For fiat plans, clients can use
resolve_scheme() to auto-detect the payment scheme before generating tokens. See the x402 developer guide for details on scheme resolution and X402TokenOptions.Environment Variables
Alternative: Manual Dependency Injection
For more control or complex scenarios, you can use FastAPI’s dependency injection instead of middleware:Manual Dependency Injection Pattern
Manual Dependency Injection Pattern
Next Steps
Payment Patterns
Advanced credit charging patterns
x402 Protocol
Deep dive into x402 payment flows
Payment Models
Configure credits, subscriptions, and dynamic pricing
http-simple-agent-py Tutorial
Complete working example on GitHub