Start here: need to register a service and create a plan first? Follow the
5-minute setup.
The x402 Payment Flow
When using x402, the client typically doesn’t start with a token. Instead, the server advertises payment requirements via402 Payment Required, and the client retries with a payment proof.
Implementation Steps
1. Extract the x402 token from the request
x402 clients send the payment token in thepayment-signature header (lowercase, per x402 v2 spec):
2. Return 402 if token is missing
When no token is provided, return HTTP 402 with a base64-encodedpayment-required header:
- TypeScript
- Python
3. Verify permissions with the Facilitator
Before processing the request, verify the subscriber has sufficient credits:- TypeScript
- Python
4. Process the request
Execute your business logic after verification passes.5. Settle (burn credits) after successful response
After the request completes successfully, settle the credits and include the receipt in the response:- TypeScript
- Python
x402 Headers Summary
| Header | Direction | Description |
|---|---|---|
payment-signature | Client → Server | x402 access token |
payment-required | Server → Client (402) | Base64-encoded payment requirements |
payment-response | Server → Client (200) | Base64-encoded settlement receipt |
HTTP Response Codes
| Code | Meaning | When to Use |
|---|---|---|
200 | Success | Valid payment proof, request processed |
402 | Payment Required | Missing/invalid payment proof, insufficient credits |
500 | Server Error | Validation system failure |
Using Framework Middleware (Recommended)
For Express.js and FastAPI, use the built-in middleware that handles the entire x402 flow automatically:- Express.js
- FastAPI
Best Practices
Cache Validation Results
Cache Validation Results
For high-traffic endpoints, consider caching validation results briefly (5-30 seconds) to reduce API calls.
Handle Timeouts
Handle Timeouts
Set reasonable timeouts for validation calls (5-10 seconds) and have a
fallback strategy.
Log Payment Events
Log Payment Events
Log all payment validations for debugging and analytics: - Token hash (not
full token) - Validation result - Credits consumed - Timestamp
Return Helpful 402 Responses
Return Helpful 402 Responses
Always include plan information in 402 responses so clients know how to get access.
Security Considerations
- Never log full tokens - Hash them if you need to identify requests
- Use HTTPS - Tokens should only travel over encrypted connections
- Validate on server - Never trust client-side validation
- Set token expiration - Accept reasonable token ages