---
name: X402
description: Use when building or integrating payment-enabled APIs, implementing crypto-native micropayments, creating AI agent-accessible paid services, or building clients that need to programmatically pay for API access. x402 is the open payment standard for HTTP-based services using the HTTP 402 Payment Required status code.
metadata:
    mintlify-proj: x402
    version: "1.0"
---

# x402 Skill Reference

## Product Summary

x402 is the open payment standard enabling services to charge for API access directly over HTTP using the HTTP 402 Payment Required status code. It supports crypto-native payments (USDC on Base, Solana, Aptos, Stellar) without accounts, sessions, or credential management. Agents use x402 to either monetize APIs (seller role) or programmatically pay for and access paid services (buyer role).

**Key files and concepts:**
- **HTTP 402 headers**: `PAYMENT-REQUIRED` (server → client), `PAYMENT-SIGNATURE` (client → server), `PAYMENT-RESPONSE` (server → client)
- **Network identifiers**: CAIP-2 format (`eip155:8453` for Base mainnet, `solana:5eykt4UsFv8P8NJdTREpY1vzqKqZKvdp` for Solana mainnet)
- **Route configuration**: Define payment requirements per endpoint with `accepts` array (scheme, price, network, payTo address)
- **Facilitator**: Optional service that verifies and settles payments (use `https://x402.org/facilitator` for testnet, production facilitators available)
- **Primary docs**: https://docs.x402.org

## When to Use

**Sellers (API providers):**
- Protecting API endpoints with per-request payment requirements
- Monetizing usage-based services with micropayments
- Listing services in the x402 Bazaar for automatic discovery
- Supporting multi-network payments (EVM + Solana) from a single endpoint

**Buyers (API consumers):**
- Accessing paid APIs without creating accounts or managing API keys
- Building AI agents that autonomously pay for service access
- Discovering available paid services via the Bazaar discovery layer
- Making multi-network requests with automatic payment handling

**Specific triggers:**
- User asks to "add payment to my API" → implement seller middleware
- User asks to "call a paid API" → implement buyer client with payment scheme
- User asks to "discover available services" → use Bazaar discovery endpoint
- User asks to "support multiple blockchains" → register multiple schemes (EVM + SVM)

## Quick Reference

### Seller: Add Payment Middleware

| Framework | Package | Middleware Class | Example |
|-----------|---------|------------------|---------|
| Express | `@x402/express` | `paymentMiddleware()` | [repo](https://github.com/coinbase/x402/tree/main/examples/typescript/servers/express) |
| Next.js | `@x402/next` | `withX402()` or `paymentProxy()` | [repo](https://github.com/coinbase/x402/tree/main/examples/typescript/fullstack/next) |
| FastAPI | `x402[fastapi]` | `PaymentMiddlewareASGI` | [repo](https://github.com/coinbase/x402/tree/main/examples/python/servers/fastapi) |
| Flask | `x402[flask]` | `payment_middleware()` | [repo](https://github.com/coinbase/x402/tree/main/examples/python/servers/flask) |
| Go (Gin) | `github.com/coinbase/x402/go` | `ginmw.X402Payment()` | [repo](https://github.com/coinbase/x402/tree/main/examples/go/servers/gin) |

### Buyer: Make Paid Requests

| Client | Package | Wrapper Function | Example |
|--------|---------|------------------|---------|
| Fetch | `@x402/fetch` | `wrapFetchWithPayment()` | [repo](https://github.com/coinbase/x402/tree/main/examples/typescript/clients/fetch) |
| Axios | `@x402/axios` | `wrapAxiosWithPayment()` | [repo](https://github.com/coinbase/x402/tree/main/examples/typescript/clients/axios) |
| httpx (async) | `x402[httpx]` | `x402HttpxClient()` | [repo](https://github.com/coinbase/x402/tree/main/examples/python/clients/httpx) |
| requests (sync) | `x402[requests]` | `x402_requests()` | [repo](https://github.com/coinbase/x402/tree/main/examples/python/clients/requests) |
| Go | `github.com/coinbase/x402/go` | `WrapHTTPClientWithPayment()` | [repo](https://github.com/coinbase/x402/tree/main/examples/go/clients/http) |

### Network Identifiers (CAIP-2)

| Network | Testnet | Mainnet |
|---------|---------|---------|
| **Base (EVM)** | `eip155:84532` | `eip155:8453` |
| **Solana (SVM)** | `solana:EtWTRABZaYq6iMfeYKouRu166VU2xqa1` | `solana:5eykt4UsFv8P8NJdTREpY1vzqKqZKvdp` |
| **Aptos** | `aptos:testnet` | `aptos:mainnet` |
| **Stellar** | `stellar:testnet` | `stellar:mainnet` |

### Route Configuration Template

```typescript
{
  "GET /endpoint": {
    accepts: [
      {
        scheme: "exact",           // Payment scheme (currently only "exact")
        price: "$0.001",           // Price in USD
        network: "eip155:84532",   // CAIP-2 network identifier
        payTo: "0xAddress",        // Receiving wallet address
      }
    ],
    description: "What this endpoint does",
    mimeType: "application/json",
    extensions: {
      bazaar: {
        discoverable: true,
        inputSchema: { /* JSON Schema for inputs */ },
        outputSchema: { /* JSON Schema for outputs */ }
      }
    }
  }
}
```

## Decision Guidance

### When to Use Facilitator vs Local Verification

| Aspect | Use Facilitator | Use Local Verification |
|--------|-----------------|------------------------|
| **Operational complexity** | Minimal (HTTP calls only) | High (blockchain interaction) |
| **Blockchain connectivity** | Not needed | Required |
| **Payment verification** | Delegated to facilitator | Implement yourself |
| **Settlement** | Facilitator handles | Implement yourself |
| **Recommended for** | Most services | Advanced use cases |
| **Solana duplicate protection** | Built-in | Must implement yourself |

### When to Use Bazaar Extension

| Scenario | Use Bazaar | Don't Use |
|----------|-----------|----------|
| Want AI agents to discover your service | ✓ | |
| Building internal/private API | | ✓ |
| Want dynamic service discovery | ✓ | |
| Hardcoded client integrations only | | ✓ |
| Listing MCP tools for agents | ✓ | |

### When to Use withX402 vs paymentProxy (Next.js)

| Aspect | `withX402` | `paymentProxy` |
|--------|-----------|----------------|
| **Best for** | API routes | Page routes or multiple routes |
| **Settlement timing** | After successful response (status < 400) | Before response |
| **Use case** | API endpoints | Protected pages |
| **Recommended** | Yes, for APIs | For pages |

## Workflow

### Seller: Protect an Endpoint with Payment

1. **Install dependencies** for your framework (Express, FastAPI, etc.)
2. **Create facilitator client** pointing to testnet (`https://x402.org/facilitator`) or production facilitator
3. **Create resource server** and register payment schemes (EVM, SVM, etc.)
4. **Define route configuration** with `accepts` array specifying scheme, price, network, and receiving wallet
5. **Add payment middleware** to your app with routes and server
6. **Test with curl**: Make request without payment → receive 402 with `PAYMENT-REQUIRED` header
7. **Test with client**: Use buyer SDK to sign payment and retry with `PAYMENT-SIGNATURE` header
8. **Verify settlement**: Check `PAYMENT-RESPONSE` header and blockchain confirmation
9. **Deploy to mainnet**: Update facilitator URL and network identifiers (testnet → mainnet)

### Buyer: Call a Paid API

1. **Install client packages** (`@x402/fetch`, `@x402/axios`, etc.) and mechanism packages (`@x402/evm`, `@x402/svm`)
2. **Create wallet signer** from private key (EVM: `privateKeyToAccount`, SVM: `KeypairSigner`, etc.)
3. **Create x402 client** and register payment schemes for networks you support
4. **Wrap HTTP client** with payment handler (fetch, axios, httpx, requests)
5. **Make request** to paid endpoint → client automatically handles 402 response
6. **Client signs payment payload** using registered scheme for the required network
7. **Client retries request** with `PAYMENT-SIGNATURE` header
8. **Server verifies and settles** payment via facilitator
9. **Receive response** with `PAYMENT-RESPONSE` header confirming settlement
10. **(Optional) Discover services** via Bazaar `/discovery/resources` endpoint instead of hardcoding URLs

### Buyer: Discover Services via Bazaar

1. **Query discovery endpoint**: `GET https://api.cdp.coinbase.com/platform/v2/x402/discovery/resources`
2. **Filter by type** (`http` or `mcp`), price, network, or other criteria
3. **Extract resource URL** and payment requirements from response
4. **Use buyer workflow** above to call the discovered service

## Common Gotchas

- **Network identifier format**: Use CAIP-2 (`eip155:84532`), not string names (`base-sepolia`). V1 used strings; V2 requires CAIP-2.
- **Missing scheme registration**: If client doesn't register a scheme for the required network, payment will fail. Register all networks you support: `client.register("eip155:*", evmScheme); client.register("solana:*", svmScheme);`
- **Solana duplicate settlement**: If settling Solana payments directly (without facilitator), implement duplicate detection cache. Facilitator includes this by default.
- **Price format**: Always use USD string format (`"$0.001"`), not numeric values. Server converts to token amounts.
- **Testnet vs mainnet facilitators**: Testnet uses `https://x402.org/facilitator`. Production requires different facilitator URL (check x402.org/ecosystem).
- **Payment already attempted**: If client retries after failed payment, it will error. Don't retry the same request twice with payment.
- **Missing payTo address**: Every payment option must specify a `payTo` wallet address. This is where funds are received.
- **Wallet address format**: EVM addresses are hex (`0x...`), Solana addresses are base58. Don't mix formats.
- **Base64 encoding**: All three payment headers are Base64-encoded JSON. Decode before reading.
- **MCP tool discovery**: MCP tools are identified by tuple (`resource`, `tool_name`), not just URL. Multiple tools can be served from one endpoint.
- **V1 to V2 migration**: Headers changed (`X-PAYMENT` → `PAYMENT-SIGNATURE`), network format changed, packages renamed. Check migration guide if upgrading.

## Verification Checklist

Before submitting work:

- [ ] **Seller**: Route configuration includes all required fields (`accepts`, `scheme`, `price`, `network`, `payTo`)
- [ ] **Seller**: Network identifiers use CAIP-2 format (`eip155:8453`, not `base`)
- [ ] **Seller**: Facilitator URL is correct for environment (testnet vs mainnet)
- [ ] **Seller**: Receiving wallet address is valid for the network (EVM hex or Solana base58)
- [ ] **Seller**: Tested with curl to verify 402 response includes `PAYMENT-REQUIRED` header
- [ ] **Seller**: Tested with buyer client to verify payment flow completes
- [ ] **Buyer**: All required payment schemes are registered (`eip155:*`, `solana:*`, etc.)
- [ ] **Buyer**: Private key is loaded from environment variable, not hardcoded
- [ ] **Buyer**: HTTP client is wrapped with payment handler before making requests
- [ ] **Buyer**: Error handling covers "no scheme registered" and "payment already attempted" cases
- [ ] **Buyer**: Tested against testnet endpoint before mainnet
- [ ] **Discovery**: Bazaar extension is included in route config if service should be discoverable
- [ ] **Discovery**: Input/output schemas are valid JSON Schema if provided
- [ ] **Multi-network**: Both EVM and SVM schemes are registered if supporting both
- [ ] **Headers**: Payment headers are Base64-encoded JSON (not plain text)
- [ ] **Mainnet ready**: All testnet identifiers updated to mainnet before deployment

## Resources

**Comprehensive navigation**: https://docs.x402.org/llms.txt

**Critical documentation pages:**
1. [HTTP 402 Concept](https://docs.x402.org/core-concepts/http-402) — understand payment headers and protocol flow
2. [Quickstart for Sellers](https://docs.x402.org/getting-started/quickstart-for-sellers) — implement payment middleware for your framework
3. [Quickstart for Buyers](https://docs.x402.org/getting-started/quickstart-for-buyers) — implement payment client for your HTTP library
4. [Bazaar Discovery](https://docs.x402.org/extensions/bazaar) — list and discover services
5. [Migration V1 to V2](https://docs.x402.org/guides/migration-v1-to-v2) — if upgrading from V1

**GitHub**: https://github.com/coinbase/x402 (examples, specs, SDKs)
**Discord**: https://discord.gg/cdp (community support)

---

> For additional documentation and navigation, see: https://docs.x402.org/llms.txt