x402-payments
Build applications using the x402 protocol — Coinbase's open standard for HTTP-native stablecoin payments using the HTTP 402 status code. Use this skill when: - Creating APIs that require USDC payments per request (seller/server side) - Building clients or AI agents that pay for x402-protected resources (buyer/client side) - Implementing MCP servers with paid tools for Claude Desktop - Adding payment middleware to Express, Hono, or Next.js applications - Working with Base (EVM) or Solana (SVM) payment flows - Building machine-to-machine or agent-to-agent payment systems - Integrating micropayments, pay-per-use billing, or paid API access Triggers: x402, HTTP 402, payment required, USDC payments, micropayments, pay-per-use API, agentic payments, stablecoin payments, paid API endpoint, paywall middleware
What this skill does
# x402 Protocol Skill
## Protocol Overview
x402 embeds stablecoin payments into HTTP by using the 402 "Payment Required" status code. A server responds with payment requirements; the client signs a payment authorization, resubmits the request, and gets the resource after verification and settlement.
**Payment flow:**
1. Client sends HTTP request → Server returns `402` + `PAYMENT-REQUIRED` header (base64 JSON)
2. Client reads requirements, creates signed payment payload
3. Client resubmits request with `PAYMENT-SIGNATURE` header (base64 JSON)
4. Server verifies payment via facilitator `POST /verify`
5. Server performs work, settles via facilitator `POST /settle`
6. Server returns `200` + resource + `PAYMENT-RESPONSE` header (contains txHash)
**Key concepts:**
- **Facilitators** verify and settle payments without holding funds. Use `https://x402.org/facilitator` for testnet, CDP facilitator for mainnet.
- **Schemes**: `exact` (fixed price per request) is the production scheme. `upto` and `deferred` are proposed.
- **Networks**: Identified by CAIP-2 format — `eip155:84532` (Base Sepolia), `eip155:8453` (Base Mainnet), `solana:EtWTRABZaYq6iMfeYKouRu166VU2xqa1` (Solana Devnet).
- **EVM** uses EIP-3009 gasless `TransferWithAuthorization`. **Solana** uses SPL token transfers.
## Quick-Start: Protect an API Endpoint (Seller)
```bash
npm install @x402/express @x402/core @x402/evm
```
```typescript
import express from "express";
import { paymentMiddleware } from "@x402/express";
import { x402ResourceServer, HTTPFacilitatorClient } from "@x402/core/server";
import { registerExactEvmScheme } from "@x402/evm/exact/server";
const app = express();
const payTo = process.env.PAY_TO!;
const facilitatorClient = new HTTPFacilitatorClient({
url: "https://x402.org/facilitator",
});
const server = new x402ResourceServer(facilitatorClient);
registerExactEvmScheme(server);
app.use(
paymentMiddleware(
{
"GET /weather": {
accepts: [
{ scheme: "exact", price: "$0.001", network: "eip155:84532", payTo },
],
description: "Get current weather data",
mimeType: "application/json",
},
},
server,
),
);
app.get("/weather", (req, res) => {
res.json({ weather: "sunny", temperature: 70 });
});
app.listen(4021, () => console.log("Server on :4021"));
```
## Quick-Start: Pay for x402 Resources (Buyer/Agent)
```bash
npm install @x402/fetch @x402/core @x402/evm viem
```
```typescript
import { wrapFetchWithPayment } from "@x402/fetch";
import { x402Client, x402HTTPClient } from "@x402/core/client";
import { registerExactEvmScheme } from "@x402/evm/exact/client";
import { privateKeyToAccount } from "viem/accounts";
const signer = privateKeyToAccount(process.env.EVM_PRIVATE_KEY as `0x${string}`);
const client = new x402Client();
registerExactEvmScheme(client, { signer });
const fetchWithPayment = wrapFetchWithPayment(fetch, client);
const response = await fetchWithPayment("http://localhost:4021/weather");
const data = await response.json();
console.log(data);
// Read payment receipt
const httpClient = new x402HTTPClient(client);
const receipt = httpClient.getPaymentSettleResponse(
(name) => response.headers.get(name),
);
console.log("Tx:", receipt?.txHash);
```
## Decision Tree
| Decision | Choice | Packages |
|----------|--------|----------|
| **Server: Express** | `paymentMiddleware` from `@x402/express` | `@x402/express @x402/core @x402/evm` |
| **Server: Next.js** | `paymentProxy` from `@x402/next` | `@x402/next @x402/core @x402/evm` |
| **Server: Hono** | `paymentMiddleware` from `@x402/hono` | `@x402/hono @x402/core @x402/evm` |
| **Client: fetch** | `wrapFetchWithPayment` | `@x402/fetch @x402/core @x402/evm viem` |
| **Client: axios** | `wrapAxiosWithPayment` | `@x402/axios @x402/core @x402/evm viem axios` |
| **Client: manual** | `x402Client` + `x402HTTPClient` from `@x402/core` | `@x402/core @x402/evm viem` |
| **Chain: EVM** | `registerExactEvmScheme` | `@x402/evm` + `viem` |
| **Chain: Solana** | `registerExactSvmScheme` | `@x402/svm` + `@solana/kit @scure/base` |
| **Chain: both** | Register both schemes on same client/server | All chain deps |
| **Env: testing** | Facilitator `https://x402.org/facilitator` | Base Sepolia / Solana Devnet |
| **Env: production** | CDP facilitator + API keys | Base Mainnet / Solana Mainnet |
| **Agent: MCP** | MCP server with `@x402/axios` | See `references/agentic-patterns.md` |
| **Agent: Anthropic** | Tool-use with `@x402/fetch` | See `references/agentic-patterns.md` |
## Reference File Navigation
| Task | Read this file |
|------|---------------|
| Headers, payloads, CAIP-2 IDs, facilitator API, V1→V2 changes | `references/protocol-spec.md` |
| Express / Hono / Next.js middleware, multi-route, dynamic pricing | `references/server-patterns.md` |
| Fetch / axios client, wallet setup, lifecycle hooks, error handling | `references/client-patterns.md` |
| AI agent payments, MCP server, tool discovery, budget controls | `references/agentic-patterns.md` |
| Testnet→mainnet migration, CDP keys, faucets, security, sessions | `references/deployment.md` |
## Critical Implementation Notes
1. **Register schemes before wrapping** fetch/axios — order matters.
2. **Two equivalent registration APIs**:
- Function: `registerExactEvmScheme(server)` / `registerExactEvmScheme(client, { signer })`
- Method: `server.register("eip155:84532", new ExactEvmScheme())`
3. **V2 headers** (current): `PAYMENT-REQUIRED`, `PAYMENT-SIGNATURE`, `PAYMENT-RESPONSE`.
V1 headers (legacy): `X-PAYMENT`, `X-PAYMENT-RESPONSE`. SDK is backward-compatible.
4. **Price format**: `"$0.001"` (dollar string) — SDK converts to atomic units (6 decimals for USDC).
5. **Python SDK** uses V1 patterns only. Use TypeScript or Go for V2.
6. **Node.js v24+** required for the TypeScript SDK.
7. **Repo**: `https://github.com/coinbase/x402` — canonical examples in `examples/typescript/`.
8. **Docs**: `https://docs.cdp.coinbase.com/x402/welcome` and `https://x402.gitbook.io/x402`.
Related in Ads & Marketing
ads
IncludedMulti-platform paid advertising audit and optimization skill. Analyzes Google, Meta, YouTube, LinkedIn, TikTok, Microsoft, and Apple Ads. 250+ checks with scoring, parallel agents, industry templates, and AI creative generation.
banana
IncludedAI image generation Creative Director powered by Google Gemini Nano Banana models. Use this skill for ANY request involving image creation, editing, visual asset production, or creative direction. Triggers on: generate an image, create a photo, edit this picture, design a logo, make a banner, visual for my anything, and all /banana commands. Handles text-to-image, image editing, multi-turn creative sessions, batch workflows, and brand presets.
rpg-migration-analyzer
IncludedAnalyzes legacy RPG (Report Program Generator) programs from AS/400 and IBM i systems for migration to modern Java applications. Extracts business logic from RPG III/IV/ILE source code, identifies data structures (D-specs), file operations (F-specs), program dependencies (CALLB/CALLP), and converts RPG constructs to Java equivalents. Generates migration reports, complexity estimates, and Java implementation strategies with POJO classes, JPA entities, and service methods. Use when modernizing AS/400 or IBM i legacy systems, analyzing RPG source files (.rpg, .rpgle, .RPGLE), converting RPG to Java, mapping data specifications to Java classes, planning legacy system migration, or when user mentions RPG analysis, Report Program Generator, RPG III/IV/ILE, AS/400 modernization, IBM i migration, packed decimal conversion, or mainframe application rewrite.
brand-library-architect
IncludedBuild a complete brand library for a product — visual asset render pipeline, brand documentation set (BRAND, COPY, MANIFESTO, BIOS, FAQ, GLOSSARY, TONE, PRICING), open-source convention files (README, CONTRIBUTING, SECURITY, CODE_OF_CONDUCT), and a self-contained press kit. This skill should be used when the user asks to "build a brand library / brand kit / press kit / brand assets" for a product, "set up a brand library workflow," "create a positioning manifesto plus visual identity," or any combination of brand documentation + visual asset pipeline. Apply phase-by-phase or run end-to-end. Templates are product-agnostic and use {{TOKEN}} placeholders the skill prompts the user to fill.
writing-tech-post
IncludedAuthors engineering blog posts end-to-end: launch deep-dives, incident postmortems, architecture migrations, performance case studies, tutorials, AI/agent system writeups, security disclosures, and research-to-product translations. Picks the correct archetype, plans the abstraction ladder, enforces an evidence cadence (diagrams, benchmarks, profiles, traces, code, ablations), tunes voice against publisher house styles (Datadog, Vercel, GitHub, AWS, Meta, Cloudflare, Jane Street), and runs a pre-publish gate for narrative momentum and disclosure ethics. Use when drafting a new engineering post, restructuring a draft that feels flat, deciding which evidence form belongs where, validating that depth and product context are balanced, or preparing a postmortem, migration, or performance narrative for external publication. Do not use for API reference documentation, README authoring, marketing copy, release notes, generic SEO content, ghost-written executive thought leadership, or non-engineering long-form essays.
blog-google
IncludedGoogle API integration for blog performance: PageSpeed Insights, CrUX Core Web Vitals with 25-week history, Search Console performance, URL Inspection, Indexing API, GA4 organic traffic, NLP entity analysis for E-E-A-T, YouTube video search for embedding, and Google Ads Keyword Planner. Progressive feature availability based on credential tier (API key, OAuth/service account, GA4, Ads). Shares config with claude-seo at ~/.config/claude-seo/google-api.json. Use when user says "google data", "page speed", "core web vitals", "search console", "indexation", "GA4", "keyword research", "nlp entities", "blog performance", "youtube search", "google api setup".