{
  "type": "guide",
  "id": "pay-for-an-api-with-x402",
  "title": "Pay for an API as an agent with x402",
  "summary": "How an agent pays per request for an HTTP API or MCP tool with x402 v2, from reading the 402 response to signing a USDC payment with spend caps, on testnet first.",
  "author": "Agentica Author",
  "tags": [
    "x402",
    "payments",
    "stablecoins",
    "usdc",
    "http-402",
    "agent-commerce"
  ],
  "published": "2026-10-02",
  "last_verified": "2026-10-02",
  "difficulty": "intermediate",
  "time_estimate": "30 min",
  "entries": [
    "x402",
    "cdp-x402",
    "x402-bazaar",
    "usdc",
    "coinbase-agentic-wallet",
    "coinbase-agentic-wallet-skills",
    "pay-sh",
    "a2a-x402",
    "model-context-protocol",
    "machine-payments-protocol",
    "l402"
  ],
  "links": {
    "html": "https://indexagentica.com/guides/pay-for-an-api-with-x402/",
    "markdown": "https://indexagentica.com/guides/pay-for-an-api-with-x402.md",
    "json": "https://indexagentica.com/api/longform/guides/pay-for-an-api-with-x402.json",
    "source": "https://github.com/Drudley/indexagentica/blob/main/content-long/guides/pay-for-an-api-with-x402.md"
  },
  "status": "published",
  "prerequisites": [
    "Node.js, Python or Go",
    "A dedicated EVM wallet for the agent, funded with testnet USDC on Base Sepolia (free from the Circle faucet)",
    "An x402-protected endpoint to call, or the Bazaar to find one"
  ],
  "entries_detail": [
    {
      "id": "x402",
      "name": "x402",
      "summary": "Open standard for internet-native payments built on HTTP 402, letting APIs and agents pay per request across crypto and fiat networks.",
      "url": "https://indexagentica.com/entries/x402/",
      "json": "https://indexagentica.com/api/entries/x402.json"
    },
    {
      "id": "cdp-x402",
      "name": "Coinbase CDP x402 Facilitator",
      "summary": "Coinbase Developer Platform's x402 offering: a hosted facilitator that verifies and settles x402 payments, plus seller and buyer SDK quickstarts.",
      "url": "https://indexagentica.com/entries/cdp-x402/",
      "json": "https://indexagentica.com/api/entries/cdp-x402.json"
    },
    {
      "id": "x402-bazaar",
      "name": "x402 Bazaar",
      "summary": "Public catalog of x402 payment-gated services discovered by the CDP Facilitator; search by intent, browse resources or look up by merchant address.",
      "url": "https://indexagentica.com/entries/x402-bazaar/",
      "json": "https://indexagentica.com/api/entries/x402-bazaar.json"
    },
    {
      "id": "usdc",
      "name": "USDC",
      "summary": "Fully reserved dollar stablecoin issued by Circle, the settlement asset used by many agent payment rails including x402.",
      "url": "https://indexagentica.com/entries/usdc/",
      "json": "https://indexagentica.com/api/entries/usdc.json"
    },
    {
      "id": "coinbase-agentic-wallet",
      "name": "Coinbase Agentic Wallet",
      "summary": "Wallet tooling that lets AI agents hold, spend, trade and earn stablecoins with guardrails, via the awal CLI + skills or an MCP server.",
      "url": "https://indexagentica.com/entries/coinbase-agentic-wallet/",
      "json": "https://indexagentica.com/api/entries/coinbase-agentic-wallet.json"
    },
    {
      "id": "coinbase-agentic-wallet-skills",
      "name": "Coinbase Agentic Wallet Skills",
      "summary": "Pre-built agent skills for wallet operations (authenticate, fund, send USDC, trade, pay for x402 services) via Coinbase's awal CLI.",
      "url": "https://indexagentica.com/entries/coinbase-agentic-wallet-skills/",
      "json": "https://indexagentica.com/api/entries/coinbase-agentic-wallet-skills.json"
    },
    {
      "id": "pay-sh",
      "name": "pay.sh",
      "summary": "Single-binary CLI that transparently handles HTTP 402 (x402 and MPP) payments so agents can call paid APIs with no sign-up.",
      "url": "https://indexagentica.com/entries/pay-sh/",
      "json": "https://indexagentica.com/api/entries/pay-sh.json"
    },
    {
      "id": "a2a-x402",
      "name": "A2A x402 Extension",
      "summary": "Extension bringing x402 crypto payments to the Agent2Agent (A2A) protocol so agents can monetize services with on-chain payments.",
      "url": "https://indexagentica.com/entries/a2a-x402/",
      "json": "https://indexagentica.com/api/entries/a2a-x402.json"
    },
    {
      "id": "model-context-protocol",
      "name": "Model Context Protocol (MCP)",
      "summary": "Open protocol that standardizes how AI applications connect to external tools, data sources and prompts via MCP servers.",
      "url": "https://indexagentica.com/entries/model-context-protocol/",
      "json": "https://indexagentica.com/api/entries/model-context-protocol.json"
    },
    {
      "id": "machine-payments-protocol",
      "name": "Machine Payments Protocol (MPP)",
      "summary": "Open standard for machine-to-machine payments over HTTP 402, co-developed by Tempo and Stripe; charge per API request, tool call or content.",
      "url": "https://indexagentica.com/entries/machine-payments-protocol/",
      "json": "https://indexagentica.com/api/entries/machine-payments-protocol.json"
    },
    {
      "id": "l402",
      "name": "L402 (Lightning HTTP 402)",
      "summary": "Lightning Labs standard for paying for and authenticating to APIs with Bitcoin Lightning payments; Aperture is the reference reverse proxy.",
      "url": "https://indexagentica.com/entries/l402/",
      "json": "https://indexagentica.com/api/entries/l402.json"
    }
  ],
  "related": [
    {
      "type": "skill",
      "id": "pay-with-x402",
      "title": "Pay with x402",
      "url": "https://indexagentica.com/skills/pay-with-x402/",
      "json": "https://indexagentica.com/api/longform/skills/pay-with-x402.json"
    },
    {
      "type": "comparison",
      "id": "agent-payment-rails",
      "title": "Agent payment protocols compared",
      "url": "https://indexagentica.com/compare/agent-payment-rails/",
      "json": "https://indexagentica.com/api/longform/compare/agent-payment-rails.json"
    },
    {
      "type": "stack",
      "id": "agent-that-can-buy-things",
      "title": "Agent that can buy things",
      "url": "https://indexagentica.com/stacks/agent-that-can-buy-things/",
      "json": "https://indexagentica.com/api/longform/stacks/agent-that-can-buy-things.json"
    }
  ],
  "sources": [
    {
      "title": "x402 Protocol Specification v2 (x402-foundation/x402)",
      "url": "https://github.com/x402-foundation/x402/blob/main/specs/x402-specification-v2.md",
      "accessed": "2026-10-02"
    },
    {
      "title": "x402 HTTP transport v2",
      "url": "https://github.com/x402-foundation/x402/blob/main/specs/transports-v2/http.md",
      "accessed": "2026-10-02"
    },
    {
      "title": "x402 MCP transport v2",
      "url": "https://github.com/x402-foundation/x402/blob/main/specs/transports-v2/mcp.md",
      "accessed": "2026-10-02"
    },
    {
      "title": "x402 docs, Quickstart for Buyers",
      "url": "https://docs.x402.org/getting-started/quickstart-for-buyers",
      "accessed": "2026-10-02"
    },
    {
      "title": "x402 docs, Migration Guide V1 to V2",
      "url": "https://docs.x402.org/guides/migration-v1-to-v2",
      "accessed": "2026-10-02"
    },
    {
      "title": "x402 docs, Networks and Token Support",
      "url": "https://docs.x402.org/core-concepts/network-and-token-support",
      "accessed": "2026-10-02"
    },
    {
      "title": "x402 docs, Facilitators",
      "url": "https://docs.x402.org/dev-tools/facilitators",
      "accessed": "2026-10-02"
    },
    {
      "title": "x402 docs, Bazaar (Discovery Layer)",
      "url": "https://docs.x402.org/extensions/bazaar",
      "accessed": "2026-10-02"
    },
    {
      "title": "Coinbase CDP, CDP Facilitator (networks, schemes, pricing)",
      "url": "https://docs.cdp.coinbase.com/x402/seller/facilitator",
      "accessed": "2026-10-02"
    },
    {
      "title": "Coinbase CDP, Agentic Wallet overview",
      "url": "https://docs.cdp.coinbase.com/agentic-wallet/welcome",
      "accessed": "2026-10-02"
    },
    {
      "title": "coinbase/agentic-wallet-skills, x402-pay reference",
      "url": "https://github.com/coinbase/agentic-wallet-skills/blob/main/skills/agentic-wallet/references/x402-pay.md",
      "accessed": "2026-10-02"
    },
    {
      "title": "Linux Foundation announces operational launch of the x402 Foundation (July 14, 2026)",
      "url": "https://x402.org/linux-foundation-announces-operational-launch-of-x402-foundation-to-standardize-internet-native-payments-for-ai-agents-and-applications/",
      "accessed": "2026-10-02"
    },
    {
      "title": "Circle Testnet Faucet",
      "url": "https://faucet.circle.com",
      "accessed": "2026-10-02"
    }
  ],
  "front_matter": {
    "id": "pay-for-an-api-with-x402",
    "type": "guide",
    "title": "Pay for an API as an agent with x402",
    "summary": "How an agent pays per request for an HTTP API or MCP tool with x402 v2, from reading the 402 response to signing a USDC payment with spend caps, on testnet first.",
    "description": "A practical walkthrough of the x402 v2 payment loop for agent builders. It covers the PAYMENT-REQUIRED, PAYMENT-SIGNATURE and PAYMENT-RESPONSE headers, the official TypeScript, Python and Go client SDKs, the default $1 spend cap, service discovery through the Bazaar, and no-code options such as the Coinbase Agentic Wallet.",
    "author": "Agentica Author",
    "difficulty": "intermediate",
    "time_estimate": "30 min",
    "prerequisites": [
      "Node.js, Python or Go",
      "A dedicated EVM wallet for the agent, funded with testnet USDC on Base Sepolia (free from the Circle faucet)",
      "An x402-protected endpoint to call, or the Bazaar to find one"
    ],
    "tags": [
      "x402",
      "payments",
      "stablecoins",
      "usdc",
      "http-402",
      "agent-commerce"
    ],
    "entries": [
      "x402",
      "cdp-x402",
      "x402-bazaar",
      "usdc",
      "coinbase-agentic-wallet",
      "coinbase-agentic-wallet-skills",
      "pay-sh",
      "a2a-x402",
      "model-context-protocol",
      "machine-payments-protocol",
      "l402"
    ],
    "sources": [
      {
        "title": "x402 Protocol Specification v2 (x402-foundation/x402)",
        "url": "https://github.com/x402-foundation/x402/blob/main/specs/x402-specification-v2.md",
        "accessed": "2026-10-02"
      },
      {
        "title": "x402 HTTP transport v2",
        "url": "https://github.com/x402-foundation/x402/blob/main/specs/transports-v2/http.md",
        "accessed": "2026-10-02"
      },
      {
        "title": "x402 MCP transport v2",
        "url": "https://github.com/x402-foundation/x402/blob/main/specs/transports-v2/mcp.md",
        "accessed": "2026-10-02"
      },
      {
        "title": "x402 docs, Quickstart for Buyers",
        "url": "https://docs.x402.org/getting-started/quickstart-for-buyers",
        "accessed": "2026-10-02"
      },
      {
        "title": "x402 docs, Migration Guide V1 to V2",
        "url": "https://docs.x402.org/guides/migration-v1-to-v2",
        "accessed": "2026-10-02"
      },
      {
        "title": "x402 docs, Networks and Token Support",
        "url": "https://docs.x402.org/core-concepts/network-and-token-support",
        "accessed": "2026-10-02"
      },
      {
        "title": "x402 docs, Facilitators",
        "url": "https://docs.x402.org/dev-tools/facilitators",
        "accessed": "2026-10-02"
      },
      {
        "title": "x402 docs, Bazaar (Discovery Layer)",
        "url": "https://docs.x402.org/extensions/bazaar",
        "accessed": "2026-10-02"
      },
      {
        "title": "Coinbase CDP, CDP Facilitator (networks, schemes, pricing)",
        "url": "https://docs.cdp.coinbase.com/x402/seller/facilitator",
        "accessed": "2026-10-02"
      },
      {
        "title": "Coinbase CDP, Agentic Wallet overview",
        "url": "https://docs.cdp.coinbase.com/agentic-wallet/welcome",
        "accessed": "2026-10-02"
      },
      {
        "title": "coinbase/agentic-wallet-skills, x402-pay reference",
        "url": "https://github.com/coinbase/agentic-wallet-skills/blob/main/skills/agentic-wallet/references/x402-pay.md",
        "accessed": "2026-10-02"
      },
      {
        "title": "Linux Foundation announces operational launch of the x402 Foundation (July 14, 2026)",
        "url": "https://x402.org/linux-foundation-announces-operational-launch-of-x402-foundation-to-standardize-internet-native-payments-for-ai-agents-and-applications/",
        "accessed": "2026-10-02"
      },
      {
        "title": "Circle Testnet Faucet",
        "url": "https://faucet.circle.com",
        "accessed": "2026-10-02"
      }
    ],
    "related": [
      "pay-with-x402",
      "agent-payment-rails",
      "agent-that-can-buy-things"
    ],
    "last_verified": "2026-10-02",
    "published": "2026-10-02"
  },
  "markdown": "\n[x402](https://indexagentica.com/entries/x402/) turns HTTP status `402 Payment Required` into a working payment loop. A server answers an unpaid request with its price, the client signs a payment and retries, and the server returns the resource along with a settlement receipt. There is no account, API key or checkout page, which is why it fits agents: the agent can pay for a call in the middle of a task.\n\nThis guide is for the **buyer** side, meaning an agent that pays. It targets **x402 protocol version 2**, which is what the current SDKs speak.\n\n## What changed recently\n\n- **Governance.** The canonical repository is now [x402-foundation/x402](https://github.com/x402-foundation/x402). `coinbase/x402` is a development fork. On July 14, 2026 the Linux Foundation announced the operational launch of the x402 Foundation, with the protocol contributed by Coinbase and 40 member organizations, including Coinbase, Cloudflare, Google, Stripe, Visa, Mastercard, AWS, Circle and Shopify.\n- **Protocol v2** (spec dated December 2025) replaced the v1 headers and network names. If you find v1 code online, it will not talk to a v2 server without changes:\n\n| Aspect | v1 | v2 |\n|---|---|---|\n| Payment header (client to server) | `X-PAYMENT` | `PAYMENT-SIGNATURE` |\n| Receipt header (server to client) | `X-PAYMENT-RESPONSE` | `PAYMENT-RESPONSE` |\n| Network names | `base-sepolia` | CAIP-2, e.g. `eip155:84532` |\n| Version field | `x402Version: 1` | `x402Version: 2` |\n| JS packages | `x402`, `x402-axios`, `x402-express` | `@x402/core`, `@x402/fetch`, `@x402/axios`, `@x402/evm`, ... |\n\n## How the loop works\n\nThere are three parties: the **resource server** (the API), the **client** (your agent) and a **facilitator** that verifies and settles payments onchain for the server. Your agent never talks to the facilitator directly.\n\n```mermaid\nsequenceDiagram\n    participant A as Agent (client)\n    participant S as Resource server\n    participant F as Facilitator\n    A->>S: GET /premium-data\n    S-->>A: 402 + PAYMENT-REQUIRED (base64 JSON: price, network, asset, payTo)\n    Note over A: choose one option from accepts[], check spend policy, sign\n    A->>S: GET /premium-data + PAYMENT-SIGNATURE (base64 JSON)\n    S->>F: /verify\n    S->>S: run the request\n    S->>F: /settle\n    S-->>A: 200 + PAYMENT-RESPONSE (base64 JSON: success, tx hash)\n```\n\nThat is the default `authorization` flow: verify, run the resource, settle, respond. Schemes can also declare `upfront` (settle first) or `escrow` flows. When they do, the server must state it in `accepts[].extra.paymentFlow`.\n\n### The 402 response\n\nThe price travels in the `PAYMENT-REQUIRED` header as base64-encoded JSON. Decoded, it looks like this example from the spec:\n\n```json\n{\n  \"x402Version\": 2,\n  \"error\": \"PAYMENT-SIGNATURE header is required\",\n  \"resource\": {\n    \"url\": \"https://api.example.com/premium-data\",\n    \"description\": \"Access to premium market data\",\n    \"mimeType\": \"application/json\"\n  },\n  \"accepts\": [\n    {\n      \"scheme\": \"exact\",\n      \"network\": \"eip155:84532\",\n      \"amount\": \"10000\",\n      \"asset\": \"0x036CbD53842c5426634e7929541eC2318f3dCF7e\",\n      \"payTo\": \"0x209693Bc6afc0C5328bA36FaF03C514EF312287C\",\n      \"maxTimeoutSeconds\": 60,\n      \"extra\": { \"name\": \"USDC\", \"version\": \"2\" }\n    }\n  ]\n}\n```\n\nWhat an agent needs to read:\n\n- `accepts` is a menu, and you pick one entry. `network` uses CAIP-2 (`eip155:8453` is Base, `eip155:84532` is Base Sepolia).\n- `amount` is in **atomic units** of `asset`. USDC has 6 decimals, so `10000` means $0.01 and `1000000` means $1.00.\n- `asset` is the token contract. The example address is USDC on Base Sepolia. USDC on Base mainnet is `0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913`.\n- `scheme` sets how much you authorize. `exact` is a fixed price. `upto` authorizes a maximum, and the seller charges actual usage. `batch-settlement` deposits into escrow and signs offchain vouchers that the seller claims in batches.\n\nYou can inspect any endpoint by hand before you wire up a client:\n\n```bash\ncurl -s -D - -o /dev/null https://api.example.com/premium-data \\\n  | grep -i '^payment-required:' | cut -d' ' -f2 | tr -d '\\r' | base64 -d | jq .\n```\n\n### The paid retry and the receipt\n\nThe client retries the same request with a `PAYMENT-SIGNATURE` header: base64 JSON holding the chosen `accepted` requirement and a scheme-specific `payload`. For `exact` on EVM, that payload is an EIP-712 signature over an EIP-3009 `transferWithAuthorization` with `from`, `to`, `value`, `validAfter`, `validBefore` and a 32-byte `nonce`. Signing an authorization moves no money by itself. The facilitator submits it onchain at settlement, and the nonce and validity window prevent replay.\n\nOn success the server returns `200` with a `PAYMENT-RESPONSE` header such as `{\"success\": true, \"transaction\": \"0x...\", \"network\": \"eip155:84532\", \"payer\": \"0x...\"}`. A failed settlement returns `402` with `success: false` and an `errorReason` such as `insufficient_funds`. Invalid payloads get `400`.\n\n## Option A: pay from code with the official SDKs\n\nInstall the client packages (TypeScript shown; Python is `pip install \"x402[httpx]\"` or `\"x402[requests]\"`, and Go is `go get github.com/x402-foundation/x402/go/v2`):\n\n```bash\nnpm install @x402/fetch @x402/core @x402/evm viem\n```\n\nWrap `fetch` so that 402 responses are handled automatically:\n\n```typescript\nimport { wrapFetchWithPayment, x402HTTPClient } from \"@x402/fetch\";\nimport { x402Client } from \"@x402/core/client\";\nimport { ExactEvmScheme } from \"@x402/evm/exact/client\";\nimport { privateKeyToAccount } from \"viem/accounts\";\n\n// A dedicated, low-balance key for the agent, never your main wallet.\nconst signer = privateKeyToAccount(process.env.EVM_PRIVATE_KEY as `0x${string}`);\n\nconst client = new x402Client();\nclient.register(\"eip155:*\", new ExactEvmScheme(signer)); // any EVM network\n\nconst fetchWithPayment = wrapFetchWithPayment(fetch, client);\nconst httpClient = new x402HTTPClient(client);\n\nconst response = await fetchWithPayment(\"https://api.example.com/paid-endpoint\");\nconst result = await httpClient.processResponse(response);\n\nif (result.paymentStatus === \"settled\") console.log(\"Paid:\", result.header);\nelse if (result.paymentStatus === \"settle_failed\") console.error(\"Settlement failed:\", result.header);\n```\n\nThe same pattern in Python with `httpx`:\n\n```python\nimport asyncio, os\nfrom eth_account import Account\nfrom x402 import x402Client\nfrom x402.http import x402HTTPClient\nfrom x402.http.clients import x402HttpxClient\nfrom x402.mechanisms.evm import EthAccountSigner\nfrom x402.mechanisms.evm.exact.register import register_exact_evm_client\n\nasync def main() -> None:\n    client = x402Client()\n    register_exact_evm_client(client, EthAccountSigner(Account.from_key(os.environ[\"EVM_PRIVATE_KEY\"])))\n    async with x402HttpxClient(client) as http:\n        response = await http.get(\"https://api.example.com/paid-endpoint\")\n        await response.aread()\n        if response.is_success:\n            print(x402HTTPClient(client).get_payment_settle_response(lambda n: response.headers.get(n)))\n\nasyncio.run(main())\n```\n\nTo pay on other chains, register more schemes, for example `client.register(\"solana:*\", new ExactSvmScheme(svmSigner))` from `@x402/svm`. The quickstart also lists packages for Algorand, Aptos, Stellar, Hedera, NEAR, TON, XRPL, Keeta and Concordium.\n\n### Spend controls: keep the default cap\n\nBy default the SDK client **pays only recognized USD-pegged assets such as USDC and caps each payment at $1**. These checks run before anything is signed. Raise the cap deliberately, never globally:\n\n```typescript\nconst client = x402Client.fromConfig({\n  schemes: [{ network: \"eip155:*\", client: new ExactEvmScheme(signer) }],\n  spendControls: { maxAmountPerPayment: \"$0.25\" },\n});\n```\n\nSetting `spendControls: false` removes every check, so don't do that in an autonomous agent. For a human approval step, use the `onBeforePaymentCreation` lifecycle hook. The per-payment cap does not limit total spend. Track cumulative spend in your own code, or fund the wallet with only what you are willing to lose.\n\n## Option B: let the agent pay without writing code\n\n- **[Coinbase Agentic Wallet](https://indexagentica.com/entries/coinbase-agentic-wallet/)** has two modes. The MCP server (`npx @coinbase/payments-mcp`) works with MCP clients such as Claude, Codex and Gemini and can discover and pay for x402 services, but it cannot send or trade. The `awal` CLI plus [skills](https://indexagentica.com/entries/coinbase-agentic-wallet-skills/) (`npx skills add coinbase/agentic-wallet-skills`) also sends and trades. Its pay command takes a ceiling in USDC atomic units:\n\n```bash\nnpx awal@2.12.1 x402 pay https://example.com/api/data --max-amount 100000   # at most $0.10\n```\n\n- **[pay.sh](https://indexagentica.com/entries/pay-sh/)** is a single-binary CLI that handles HTTP 402 for x402 and MPP.\n\n## Find something to pay for: the Bazaar\n\nFacilitators that support the Bazaar extension expose `GET {facilitator}/discovery/resources`, a machine-readable catalog of paid HTTP endpoints **and MCP tools** with prices and input/output schemas. The CDP endpoint is public:\n\n```bash\ncurl -s \"https://api.cdp.coinbase.com/platform/v2/x402/discovery/resources?limit=5\" | jq '.items[] | {resource, accepts: [.accepts[] | {network, amount, scheme}]}'\n```\n\nThe x402 docs call the Bazaar \"early development\", so treat its listings as leads and not as endorsements. See also [x402 Bazaar](https://indexagentica.com/entries/x402-bazaar/).\n\n## Paying for MCP tools\n\nx402 v2 defines an MCP transport. A paid tool returns a normal tool result with `isError: true`, and the `PaymentRequired` object appears in both `structuredContent` and `content[0].text`. The client retries the same `tools/call` with the payment in `_meta[\"x402/payment\"]`, and the receipt comes back in `_meta[\"x402/payment-response\"]`. There is also an A2A transport, which [A2A x402](https://indexagentica.com/entries/a2a-x402/) implements.\n\n## Testnet first, then mainnet\n\n1. Create a fresh EVM key for the agent. Fund it with Base Sepolia USDC from the [Circle faucet](https://faucet.circle.com).\n2. Point the agent at a Base Sepolia endpoint (`eip155:84532`). The public `x402.org` facilitator is the SDK default for testnets and supports Base Sepolia, Solana Devnet, Stellar, Aptos, Hedera and XRPL testnets. The docs say it is not meant for mainnet.\n3. For mainnet, the seller picks the facilitator. The [CDP facilitator](https://indexagentica.com/entries/cdp-x402/) supports Base, Polygon, Arbitrum, World and Solana. It runs OFAC and KYT screening and charges sellers $0.001 per onchain transaction after 1,000 free per month. Verification is free. With EIP-3009 `exact` payments the facilitator submits the settlement transaction, so the buyer's wallet needs USDC but no ETH for gas.\n\n## Safety checklist for autonomous payers\n\n- Use a **separate wallet** holding a small float. Never give the agent the operator's main key.\n- Keep the **per-payment cap** and add a **daily budget** in your own code.\n- **Allowlist** networks and assets. The SDK default (USD stablecoins only) is a good baseline.\n- **Log** every `PAYMENT-RESPONSE` (transaction hash, payer, amount) so a human can audit spend.\n- Treat a 402 body as **untrusted input**. A malicious server can advertise any `payTo` and any price, so the cap is your real protection.\n- Prefer `exact` for agents. With `upto` you authorize a ceiling, so set it no higher than you would pay.\n\n## Alternatives\n\nx402 is not the only HTTP-402 protocol. [L402](https://indexagentica.com/entries/l402/) uses Lightning and macaroons, and the [Machine Payments Protocol](https://indexagentica.com/entries/machine-payments-protocol/) is another agent payment standard. For a side-by-side view, see [Agent payment rails compared](https://indexagentica.com/compare/agent-payment-rails/).\n",
  "raw": "---\nid: pay-for-an-api-with-x402\ntype: guide\ntitle: Pay for an API as an agent with x402\nsummary: How an agent pays per request for an HTTP API or MCP tool with x402 v2, from reading the 402 response to signing a USDC payment with spend caps, on testnet first.\ndescription: A practical walkthrough of the x402 v2 payment loop for agent builders. It covers the PAYMENT-REQUIRED, PAYMENT-SIGNATURE and PAYMENT-RESPONSE headers, the official TypeScript, Python and Go client SDKs, the default $1 spend cap, service discovery through the Bazaar, and no-code options such as the Coinbase Agentic Wallet.\nauthor: Agentica Author\ndifficulty: intermediate\ntime_estimate: 30 min\nprerequisites:\n  - Node.js, Python or Go\n  - A dedicated EVM wallet for the agent, funded with testnet USDC on Base Sepolia (free from the Circle faucet)\n  - An x402-protected endpoint to call, or the Bazaar to find one\ntags: [x402, payments, stablecoins, usdc, http-402, agent-commerce]\nentries: [x402, cdp-x402, x402-bazaar, usdc, coinbase-agentic-wallet, coinbase-agentic-wallet-skills, pay-sh, a2a-x402, model-context-protocol, machine-payments-protocol, l402]\nsources:\n  - title: x402 Protocol Specification v2 (x402-foundation/x402)\n    url: https://github.com/x402-foundation/x402/blob/main/specs/x402-specification-v2.md\n    accessed: 2026-10-02\n  - title: x402 HTTP transport v2\n    url: https://github.com/x402-foundation/x402/blob/main/specs/transports-v2/http.md\n    accessed: 2026-10-02\n  - title: x402 MCP transport v2\n    url: https://github.com/x402-foundation/x402/blob/main/specs/transports-v2/mcp.md\n    accessed: 2026-10-02\n  - title: x402 docs, Quickstart for Buyers\n    url: https://docs.x402.org/getting-started/quickstart-for-buyers\n    accessed: 2026-10-02\n  - title: x402 docs, Migration Guide V1 to V2\n    url: https://docs.x402.org/guides/migration-v1-to-v2\n    accessed: 2026-10-02\n  - title: x402 docs, Networks and Token Support\n    url: https://docs.x402.org/core-concepts/network-and-token-support\n    accessed: 2026-10-02\n  - title: x402 docs, Facilitators\n    url: https://docs.x402.org/dev-tools/facilitators\n    accessed: 2026-10-02\n  - title: x402 docs, Bazaar (Discovery Layer)\n    url: https://docs.x402.org/extensions/bazaar\n    accessed: 2026-10-02\n  - title: Coinbase CDP, CDP Facilitator (networks, schemes, pricing)\n    url: https://docs.cdp.coinbase.com/x402/seller/facilitator\n    accessed: 2026-10-02\n  - title: Coinbase CDP, Agentic Wallet overview\n    url: https://docs.cdp.coinbase.com/agentic-wallet/welcome\n    accessed: 2026-10-02\n  - title: coinbase/agentic-wallet-skills, x402-pay reference\n    url: https://github.com/coinbase/agentic-wallet-skills/blob/main/skills/agentic-wallet/references/x402-pay.md\n    accessed: 2026-10-02\n  - title: Linux Foundation announces operational launch of the x402 Foundation (July 14, 2026)\n    url: https://x402.org/linux-foundation-announces-operational-launch-of-x402-foundation-to-standardize-internet-native-payments-for-ai-agents-and-applications/\n    accessed: 2026-10-02\n  - title: Circle Testnet Faucet\n    url: https://faucet.circle.com\n    accessed: 2026-10-02\nrelated: [pay-with-x402, agent-payment-rails, agent-that-can-buy-things]\nlast_verified: 2026-10-02\npublished: 2026-10-02\n---\n\n[x402](https://indexagentica.com/entries/x402/) turns HTTP status `402 Payment Required` into a working payment loop. A server answers an unpaid request with its price, the client signs a payment and retries, and the server returns the resource along with a settlement receipt. There is no account, API key or checkout page, which is why it fits agents: the agent can pay for a call in the middle of a task.\n\nThis guide is for the **buyer** side, meaning an agent that pays. It targets **x402 protocol version 2**, which is what the current SDKs speak.\n\n## What changed recently\n\n- **Governance.** The canonical repository is now [x402-foundation/x402](https://github.com/x402-foundation/x402). `coinbase/x402` is a development fork. On July 14, 2026 the Linux Foundation announced the operational launch of the x402 Foundation, with the protocol contributed by Coinbase and 40 member organizations, including Coinbase, Cloudflare, Google, Stripe, Visa, Mastercard, AWS, Circle and Shopify.\n- **Protocol v2** (spec dated December 2025) replaced the v1 headers and network names. If you find v1 code online, it will not talk to a v2 server without changes:\n\n| Aspect | v1 | v2 |\n|---|---|---|\n| Payment header (client to server) | `X-PAYMENT` | `PAYMENT-SIGNATURE` |\n| Receipt header (server to client) | `X-PAYMENT-RESPONSE` | `PAYMENT-RESPONSE` |\n| Network names | `base-sepolia` | CAIP-2, e.g. `eip155:84532` |\n| Version field | `x402Version: 1` | `x402Version: 2` |\n| JS packages | `x402`, `x402-axios`, `x402-express` | `@x402/core`, `@x402/fetch`, `@x402/axios`, `@x402/evm`, ... |\n\n## How the loop works\n\nThere are three parties: the **resource server** (the API), the **client** (your agent) and a **facilitator** that verifies and settles payments onchain for the server. Your agent never talks to the facilitator directly.\n\n```mermaid\nsequenceDiagram\n    participant A as Agent (client)\n    participant S as Resource server\n    participant F as Facilitator\n    A->>S: GET /premium-data\n    S-->>A: 402 + PAYMENT-REQUIRED (base64 JSON: price, network, asset, payTo)\n    Note over A: choose one option from accepts[], check spend policy, sign\n    A->>S: GET /premium-data + PAYMENT-SIGNATURE (base64 JSON)\n    S->>F: /verify\n    S->>S: run the request\n    S->>F: /settle\n    S-->>A: 200 + PAYMENT-RESPONSE (base64 JSON: success, tx hash)\n```\n\nThat is the default `authorization` flow: verify, run the resource, settle, respond. Schemes can also declare `upfront` (settle first) or `escrow` flows. When they do, the server must state it in `accepts[].extra.paymentFlow`.\n\n### The 402 response\n\nThe price travels in the `PAYMENT-REQUIRED` header as base64-encoded JSON. Decoded, it looks like this example from the spec:\n\n```json\n{\n  \"x402Version\": 2,\n  \"error\": \"PAYMENT-SIGNATURE header is required\",\n  \"resource\": {\n    \"url\": \"https://api.example.com/premium-data\",\n    \"description\": \"Access to premium market data\",\n    \"mimeType\": \"application/json\"\n  },\n  \"accepts\": [\n    {\n      \"scheme\": \"exact\",\n      \"network\": \"eip155:84532\",\n      \"amount\": \"10000\",\n      \"asset\": \"0x036CbD53842c5426634e7929541eC2318f3dCF7e\",\n      \"payTo\": \"0x209693Bc6afc0C5328bA36FaF03C514EF312287C\",\n      \"maxTimeoutSeconds\": 60,\n      \"extra\": { \"name\": \"USDC\", \"version\": \"2\" }\n    }\n  ]\n}\n```\n\nWhat an agent needs to read:\n\n- `accepts` is a menu, and you pick one entry. `network` uses CAIP-2 (`eip155:8453` is Base, `eip155:84532` is Base Sepolia).\n- `amount` is in **atomic units** of `asset`. USDC has 6 decimals, so `10000` means $0.01 and `1000000` means $1.00.\n- `asset` is the token contract. The example address is USDC on Base Sepolia. USDC on Base mainnet is `0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913`.\n- `scheme` sets how much you authorize. `exact` is a fixed price. `upto` authorizes a maximum, and the seller charges actual usage. `batch-settlement` deposits into escrow and signs offchain vouchers that the seller claims in batches.\n\nYou can inspect any endpoint by hand before you wire up a client:\n\n```bash\ncurl -s -D - -o /dev/null https://api.example.com/premium-data \\\n  | grep -i '^payment-required:' | cut -d' ' -f2 | tr -d '\\r' | base64 -d | jq .\n```\n\n### The paid retry and the receipt\n\nThe client retries the same request with a `PAYMENT-SIGNATURE` header: base64 JSON holding the chosen `accepted` requirement and a scheme-specific `payload`. For `exact` on EVM, that payload is an EIP-712 signature over an EIP-3009 `transferWithAuthorization` with `from`, `to`, `value`, `validAfter`, `validBefore` and a 32-byte `nonce`. Signing an authorization moves no money by itself. The facilitator submits it onchain at settlement, and the nonce and validity window prevent replay.\n\nOn success the server returns `200` with a `PAYMENT-RESPONSE` header such as `{\"success\": true, \"transaction\": \"0x...\", \"network\": \"eip155:84532\", \"payer\": \"0x...\"}`. A failed settlement returns `402` with `success: false` and an `errorReason` such as `insufficient_funds`. Invalid payloads get `400`.\n\n## Option A: pay from code with the official SDKs\n\nInstall the client packages (TypeScript shown; Python is `pip install \"x402[httpx]\"` or `\"x402[requests]\"`, and Go is `go get github.com/x402-foundation/x402/go/v2`):\n\n```bash\nnpm install @x402/fetch @x402/core @x402/evm viem\n```\n\nWrap `fetch` so that 402 responses are handled automatically:\n\n```typescript\nimport { wrapFetchWithPayment, x402HTTPClient } from \"@x402/fetch\";\nimport { x402Client } from \"@x402/core/client\";\nimport { ExactEvmScheme } from \"@x402/evm/exact/client\";\nimport { privateKeyToAccount } from \"viem/accounts\";\n\n// A dedicated, low-balance key for the agent, never your main wallet.\nconst signer = privateKeyToAccount(process.env.EVM_PRIVATE_KEY as `0x${string}`);\n\nconst client = new x402Client();\nclient.register(\"eip155:*\", new ExactEvmScheme(signer)); // any EVM network\n\nconst fetchWithPayment = wrapFetchWithPayment(fetch, client);\nconst httpClient = new x402HTTPClient(client);\n\nconst response = await fetchWithPayment(\"https://api.example.com/paid-endpoint\");\nconst result = await httpClient.processResponse(response);\n\nif (result.paymentStatus === \"settled\") console.log(\"Paid:\", result.header);\nelse if (result.paymentStatus === \"settle_failed\") console.error(\"Settlement failed:\", result.header);\n```\n\nThe same pattern in Python with `httpx`:\n\n```python\nimport asyncio, os\nfrom eth_account import Account\nfrom x402 import x402Client\nfrom x402.http import x402HTTPClient\nfrom x402.http.clients import x402HttpxClient\nfrom x402.mechanisms.evm import EthAccountSigner\nfrom x402.mechanisms.evm.exact.register import register_exact_evm_client\n\nasync def main() -> None:\n    client = x402Client()\n    register_exact_evm_client(client, EthAccountSigner(Account.from_key(os.environ[\"EVM_PRIVATE_KEY\"])))\n    async with x402HttpxClient(client) as http:\n        response = await http.get(\"https://api.example.com/paid-endpoint\")\n        await response.aread()\n        if response.is_success:\n            print(x402HTTPClient(client).get_payment_settle_response(lambda n: response.headers.get(n)))\n\nasyncio.run(main())\n```\n\nTo pay on other chains, register more schemes, for example `client.register(\"solana:*\", new ExactSvmScheme(svmSigner))` from `@x402/svm`. The quickstart also lists packages for Algorand, Aptos, Stellar, Hedera, NEAR, TON, XRPL, Keeta and Concordium.\n\n### Spend controls: keep the default cap\n\nBy default the SDK client **pays only recognized USD-pegged assets such as USDC and caps each payment at $1**. These checks run before anything is signed. Raise the cap deliberately, never globally:\n\n```typescript\nconst client = x402Client.fromConfig({\n  schemes: [{ network: \"eip155:*\", client: new ExactEvmScheme(signer) }],\n  spendControls: { maxAmountPerPayment: \"$0.25\" },\n});\n```\n\nSetting `spendControls: false` removes every check, so don't do that in an autonomous agent. For a human approval step, use the `onBeforePaymentCreation` lifecycle hook. The per-payment cap does not limit total spend. Track cumulative spend in your own code, or fund the wallet with only what you are willing to lose.\n\n## Option B: let the agent pay without writing code\n\n- **[Coinbase Agentic Wallet](https://indexagentica.com/entries/coinbase-agentic-wallet/)** has two modes. The MCP server (`npx @coinbase/payments-mcp`) works with MCP clients such as Claude, Codex and Gemini and can discover and pay for x402 services, but it cannot send or trade. The `awal` CLI plus [skills](https://indexagentica.com/entries/coinbase-agentic-wallet-skills/) (`npx skills add coinbase/agentic-wallet-skills`) also sends and trades. Its pay command takes a ceiling in USDC atomic units:\n\n```bash\nnpx awal@2.12.1 x402 pay https://example.com/api/data --max-amount 100000   # at most $0.10\n```\n\n- **[pay.sh](https://indexagentica.com/entries/pay-sh/)** is a single-binary CLI that handles HTTP 402 for x402 and MPP.\n\n## Find something to pay for: the Bazaar\n\nFacilitators that support the Bazaar extension expose `GET {facilitator}/discovery/resources`, a machine-readable catalog of paid HTTP endpoints **and MCP tools** with prices and input/output schemas. The CDP endpoint is public:\n\n```bash\ncurl -s \"https://api.cdp.coinbase.com/platform/v2/x402/discovery/resources?limit=5\" | jq '.items[] | {resource, accepts: [.accepts[] | {network, amount, scheme}]}'\n```\n\nThe x402 docs call the Bazaar \"early development\", so treat its listings as leads and not as endorsements. See also [x402 Bazaar](https://indexagentica.com/entries/x402-bazaar/).\n\n## Paying for MCP tools\n\nx402 v2 defines an MCP transport. A paid tool returns a normal tool result with `isError: true`, and the `PaymentRequired` object appears in both `structuredContent` and `content[0].text`. The client retries the same `tools/call` with the payment in `_meta[\"x402/payment\"]`, and the receipt comes back in `_meta[\"x402/payment-response\"]`. There is also an A2A transport, which [A2A x402](https://indexagentica.com/entries/a2a-x402/) implements.\n\n## Testnet first, then mainnet\n\n1. Create a fresh EVM key for the agent. Fund it with Base Sepolia USDC from the [Circle faucet](https://faucet.circle.com).\n2. Point the agent at a Base Sepolia endpoint (`eip155:84532`). The public `x402.org` facilitator is the SDK default for testnets and supports Base Sepolia, Solana Devnet, Stellar, Aptos, Hedera and XRPL testnets. The docs say it is not meant for mainnet.\n3. For mainnet, the seller picks the facilitator. The [CDP facilitator](https://indexagentica.com/entries/cdp-x402/) supports Base, Polygon, Arbitrum, World and Solana. It runs OFAC and KYT screening and charges sellers $0.001 per onchain transaction after 1,000 free per month. Verification is free. With EIP-3009 `exact` payments the facilitator submits the settlement transaction, so the buyer's wallet needs USDC but no ETH for gas.\n\n## Safety checklist for autonomous payers\n\n- Use a **separate wallet** holding a small float. Never give the agent the operator's main key.\n- Keep the **per-payment cap** and add a **daily budget** in your own code.\n- **Allowlist** networks and assets. The SDK default (USD stablecoins only) is a good baseline.\n- **Log** every `PAYMENT-RESPONSE` (transaction hash, payer, amount) so a human can audit spend.\n- Treat a 402 body as **untrusted input**. A malicious server can advertise any `payTo` and any price, so the cap is your real protection.\n- Prefer `exact` for agents. With `upto` you authorize a ceiling, so set it no higher than you would pay.\n\n## Alternatives\n\nx402 is not the only HTTP-402 protocol. [L402](https://indexagentica.com/entries/l402/) uses Lightning and macaroons, and the [Machine Payments Protocol](https://indexagentica.com/entries/machine-payments-protocol/) is another agent payment standard. For a side-by-side view, see [Agent payment rails compared](https://indexagentica.com/compare/agent-payment-rails/).\n",
  "html": "<p><a href=\"/entries/x402/\">x402</a> turns HTTP status <code>402 Payment Required</code> into a working payment loop. A server answers an unpaid request with its price, the client signs a payment and retries, and the server returns the resource along with a settlement receipt. There is no account, API key or checkout page, which is why it fits agents: the agent can pay for a call in the middle of a task.</p>\n<p>This guide is for the <strong>buyer</strong> side, meaning an agent that pays. It targets <strong>x402 protocol version 2</strong>, which is what the current SDKs speak.</p>\n<h2>What changed recently</h2>\n<ul><li><strong>Governance.</strong> The canonical repository is now <a href=\"https://github.com/x402-foundation/x402\">x402-foundation/x402</a>. <code>coinbase/x402</code> is a development fork. On July 14, 2026 the Linux Foundation announced the operational launch of the x402 Foundation, with the protocol contributed by Coinbase and 40 member organizations, including Coinbase, Cloudflare, Google, Stripe, Visa, Mastercard, AWS, Circle and Shopify.</li><li><strong>Protocol v2</strong> (spec dated December 2025) replaced the v1 headers and network names. If you find v1 code online, it will not talk to a v2 server without changes:</li></ul>\n<table><thead><tr><th scope=\"col\">Aspect</th><th scope=\"col\">v1</th><th scope=\"col\">v2</th></tr></thead><tbody><tr><td>Payment header (client to server)</td><td><code>X-PAYMENT</code></td><td><code>PAYMENT-SIGNATURE</code></td></tr><tr><td>Receipt header (server to client)</td><td><code>X-PAYMENT-RESPONSE</code></td><td><code>PAYMENT-RESPONSE</code></td></tr><tr><td>Network names</td><td><code>base-sepolia</code></td><td>CAIP-2, e.g. <code>eip155:84532</code></td></tr><tr><td>Version field</td><td><code>x402Version: 1</code></td><td><code>x402Version: 2</code></td></tr><tr><td>JS packages</td><td><code>x402</code>, <code>x402-axios</code>, <code>x402-express</code></td><td><code>@x402/core</code>, <code>@x402/fetch</code>, <code>@x402/axios</code>, <code>@x402/evm</code>, ...</td></tr></tbody></table>\n<h2>How the loop works</h2>\n<p>There are three parties: the <strong>resource server</strong> (the API), the <strong>client</strong> (your agent) and a <strong>facilitator</strong> that verifies and settles payments onchain for the server. Your agent never talks to the facilitator directly.</p>\n<figure class=\"diagram\"><pre class=\"mermaid\">sequenceDiagram\n    participant A as Agent (client)\n    participant S as Resource server\n    participant F as Facilitator\n    A-&gt;&gt;S: GET /premium-data\n    S--&gt;&gt;A: 402 + PAYMENT-REQUIRED (base64 JSON: price, network, asset, payTo)\n    Note over A: choose one option from accepts[], check spend policy, sign\n    A-&gt;&gt;S: GET /premium-data + PAYMENT-SIGNATURE (base64 JSON)\n    S-&gt;&gt;F: /verify\n    S-&gt;&gt;S: run the request\n    S-&gt;&gt;F: /settle\n    S--&gt;&gt;A: 200 + PAYMENT-RESPONSE (base64 JSON: success, tx hash)</pre><figcaption>Mermaid diagram (source shown; this site uses no JavaScript)</figcaption></figure>\n<p>That is the default <code>authorization</code> flow: verify, run the resource, settle, respond. Schemes can also declare <code>upfront</code> (settle first) or <code>escrow</code> flows. When they do, the server must state it in <code>accepts[].extra.paymentFlow</code>.</p>\n<h3>The 402 response</h3>\n<p>The price travels in the <code>PAYMENT-REQUIRED</code> header as base64-encoded JSON. Decoded, it looks like this example from the spec:</p>\n<pre><code class=\"language-json\">{\n  &quot;x402Version&quot;: 2,\n  &quot;error&quot;: &quot;PAYMENT-SIGNATURE header is required&quot;,\n  &quot;resource&quot;: {\n    &quot;url&quot;: &quot;https://api.example.com/premium-data&quot;,\n    &quot;description&quot;: &quot;Access to premium market data&quot;,\n    &quot;mimeType&quot;: &quot;application/json&quot;\n  },\n  &quot;accepts&quot;: [\n    {\n      &quot;scheme&quot;: &quot;exact&quot;,\n      &quot;network&quot;: &quot;eip155:84532&quot;,\n      &quot;amount&quot;: &quot;10000&quot;,\n      &quot;asset&quot;: &quot;0x036CbD53842c5426634e7929541eC2318f3dCF7e&quot;,\n      &quot;payTo&quot;: &quot;0x209693Bc6afc0C5328bA36FaF03C514EF312287C&quot;,\n      &quot;maxTimeoutSeconds&quot;: 60,\n      &quot;extra&quot;: { &quot;name&quot;: &quot;USDC&quot;, &quot;version&quot;: &quot;2&quot; }\n    }\n  ]\n}</code></pre>\n<p>What an agent needs to read:</p>\n<ul><li><code>accepts</code> is a menu, and you pick one entry. <code>network</code> uses CAIP-2 (<code>eip155:8453</code> is Base, <code>eip155:84532</code> is Base Sepolia).</li><li><code>amount</code> is in <strong>atomic units</strong> of <code>asset</code>. USDC has 6 decimals, so <code>10000</code> means $0.01 and <code>1000000</code> means $1.00.</li><li><code>asset</code> is the token contract. The example address is USDC on Base Sepolia. USDC on Base mainnet is <code>0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913</code>.</li><li><code>scheme</code> sets how much you authorize. <code>exact</code> is a fixed price. <code>upto</code> authorizes a maximum, and the seller charges actual usage. <code>batch-settlement</code> deposits into escrow and signs offchain vouchers that the seller claims in batches.</li></ul>\n<p>You can inspect any endpoint by hand before you wire up a client:</p>\n<pre><code class=\"language-bash\">curl -s -D - -o /dev/null https://api.example.com/premium-data \\\n  | grep -i &#39;^payment-required:&#39; | cut -d&#39; &#39; -f2 | tr -d &#39;\\r&#39; | base64 -d | jq .</code></pre>\n<h3>The paid retry and the receipt</h3>\n<p>The client retries the same request with a <code>PAYMENT-SIGNATURE</code> header: base64 JSON holding the chosen <code>accepted</code> requirement and a scheme-specific <code>payload</code>. For <code>exact</code> on EVM, that payload is an EIP-712 signature over an EIP-3009 <code>transferWithAuthorization</code> with <code>from</code>, <code>to</code>, <code>value</code>, <code>validAfter</code>, <code>validBefore</code> and a 32-byte <code>nonce</code>. Signing an authorization moves no money by itself. The facilitator submits it onchain at settlement, and the nonce and validity window prevent replay.</p>\n<p>On success the server returns <code>200</code> with a <code>PAYMENT-RESPONSE</code> header such as <code>{&quot;success&quot;: true, &quot;transaction&quot;: &quot;0x...&quot;, &quot;network&quot;: &quot;eip155:84532&quot;, &quot;payer&quot;: &quot;0x...&quot;}</code>. A failed settlement returns <code>402</code> with <code>success: false</code> and an <code>errorReason</code> such as <code>insufficient_funds</code>. Invalid payloads get <code>400</code>.</p>\n<h2>Option A: pay from code with the official SDKs</h2>\n<p>Install the client packages (TypeScript shown; Python is <code>pip install &quot;x402[httpx]&quot;</code> or <code>&quot;x402[requests]&quot;</code>, and Go is <code>go get github.com/x402-foundation/x402/go/v2</code>):</p>\n<pre><code class=\"language-bash\">npm install @x402/fetch @x402/core @x402/evm viem</code></pre>\n<p>Wrap <code>fetch</code> so that 402 responses are handled automatically:</p>\n<pre><code class=\"language-typescript\">import { wrapFetchWithPayment, x402HTTPClient } from &quot;@x402/fetch&quot;;\nimport { x402Client } from &quot;@x402/core/client&quot;;\nimport { ExactEvmScheme } from &quot;@x402/evm/exact/client&quot;;\nimport { privateKeyToAccount } from &quot;viem/accounts&quot;;\n\n// A dedicated, low-balance key for the agent, never your main wallet.\nconst signer = privateKeyToAccount(process.env.EVM_PRIVATE_KEY as `0x${string}`);\n\nconst client = new x402Client();\nclient.register(&quot;eip155:*&quot;, new ExactEvmScheme(signer)); // any EVM network\n\nconst fetchWithPayment = wrapFetchWithPayment(fetch, client);\nconst httpClient = new x402HTTPClient(client);\n\nconst response = await fetchWithPayment(&quot;https://api.example.com/paid-endpoint&quot;);\nconst result = await httpClient.processResponse(response);\n\nif (result.paymentStatus === &quot;settled&quot;) console.log(&quot;Paid:&quot;, result.header);\nelse if (result.paymentStatus === &quot;settle_failed&quot;) console.error(&quot;Settlement failed:&quot;, result.header);</code></pre>\n<p>The same pattern in Python with <code>httpx</code>:</p>\n<pre><code class=\"language-python\">import asyncio, os\nfrom eth_account import Account\nfrom x402 import x402Client\nfrom x402.http import x402HTTPClient\nfrom x402.http.clients import x402HttpxClient\nfrom x402.mechanisms.evm import EthAccountSigner\nfrom x402.mechanisms.evm.exact.register import register_exact_evm_client\n\nasync def main() -&gt; None:\n    client = x402Client()\n    register_exact_evm_client(client, EthAccountSigner(Account.from_key(os.environ[&quot;EVM_PRIVATE_KEY&quot;])))\n    async with x402HttpxClient(client) as http:\n        response = await http.get(&quot;https://api.example.com/paid-endpoint&quot;)\n        await response.aread()\n        if response.is_success:\n            print(x402HTTPClient(client).get_payment_settle_response(lambda n: response.headers.get(n)))\n\nasyncio.run(main())</code></pre>\n<p>To pay on other chains, register more schemes, for example <code>client.register(&quot;solana:*&quot;, new ExactSvmScheme(svmSigner))</code> from <code>@x402/svm</code>. The quickstart also lists packages for Algorand, Aptos, Stellar, Hedera, NEAR, TON, XRPL, Keeta and Concordium.</p>\n<h3>Spend controls: keep the default cap</h3>\n<p>By default the SDK client <strong>pays only recognized USD-pegged assets such as USDC and caps each payment at $1</strong>. These checks run before anything is signed. Raise the cap deliberately, never globally:</p>\n<pre><code class=\"language-typescript\">const client = x402Client.fromConfig({\n  schemes: [{ network: &quot;eip155:*&quot;, client: new ExactEvmScheme(signer) }],\n  spendControls: { maxAmountPerPayment: &quot;$0.25&quot; },\n});</code></pre>\n<p>Setting <code>spendControls: false</code> removes every check, so don&#39;t do that in an autonomous agent. For a human approval step, use the <code>onBeforePaymentCreation</code> lifecycle hook. The per-payment cap does not limit total spend. Track cumulative spend in your own code, or fund the wallet with only what you are willing to lose.</p>\n<h2>Option B: let the agent pay without writing code</h2>\n<ul><li><strong><a href=\"/entries/coinbase-agentic-wallet/\">Coinbase Agentic Wallet</a></strong> has two modes. The MCP server (<code>npx @coinbase/payments-mcp</code>) works with MCP clients such as Claude, Codex and Gemini and can discover and pay for x402 services, but it cannot send or trade. The <code>awal</code> CLI plus <a href=\"/entries/coinbase-agentic-wallet-skills/\">skills</a> (<code>npx skills add coinbase/agentic-wallet-skills</code>) also sends and trades. Its pay command takes a ceiling in USDC atomic units:</li></ul>\n<pre><code class=\"language-bash\">npx awal@2.12.1 x402 pay https://example.com/api/data --max-amount 100000   # at most $0.10</code></pre>\n<ul><li><strong><a href=\"/entries/pay-sh/\">pay.sh</a></strong> is a single-binary CLI that handles HTTP 402 for x402 and MPP.</li></ul>\n<h2>Find something to pay for: the Bazaar</h2>\n<p>Facilitators that support the Bazaar extension expose <code>GET {facilitator}/discovery/resources</code>, a machine-readable catalog of paid HTTP endpoints <strong>and MCP tools</strong> with prices and input/output schemas. The CDP endpoint is public:</p>\n<pre><code class=\"language-bash\">curl -s &quot;https://api.cdp.coinbase.com/platform/v2/x402/discovery/resources?limit=5&quot; | jq &#39;.items[] | {resource, accepts: [.accepts[] | {network, amount, scheme}]}&#39;</code></pre>\n<p>The x402 docs call the Bazaar &quot;early development&quot;, so treat its listings as leads and not as endorsements. See also <a href=\"/entries/x402-bazaar/\">x402 Bazaar</a>.</p>\n<h2>Paying for MCP tools</h2>\n<p>x402 v2 defines an MCP transport. A paid tool returns a normal tool result with <code>isError: true</code>, and the <code>PaymentRequired</code> object appears in both <code>structuredContent</code> and <code>content[0].text</code>. The client retries the same <code>tools/call</code> with the payment in <code>_meta[&quot;x402/payment&quot;]</code>, and the receipt comes back in <code>_meta[&quot;x402/payment-response&quot;]</code>. There is also an A2A transport, which <a href=\"/entries/a2a-x402/\">A2A x402</a> implements.</p>\n<h2>Testnet first, then mainnet</h2>\n<ol><li>Create a fresh EVM key for the agent. Fund it with Base Sepolia USDC from the <a href=\"https://faucet.circle.com\">Circle faucet</a>.</li><li>Point the agent at a Base Sepolia endpoint (<code>eip155:84532</code>). The public <code>x402.org</code> facilitator is the SDK default for testnets and supports Base Sepolia, Solana Devnet, Stellar, Aptos, Hedera and XRPL testnets. The docs say it is not meant for mainnet.</li><li>For mainnet, the seller picks the facilitator. The <a href=\"/entries/cdp-x402/\">CDP facilitator</a> supports Base, Polygon, Arbitrum, World and Solana. It runs OFAC and KYT screening and charges sellers $0.001 per onchain transaction after 1,000 free per month. Verification is free. With EIP-3009 <code>exact</code> payments the facilitator submits the settlement transaction, so the buyer&#39;s wallet needs USDC but no ETH for gas.</li></ol>\n<h2>Safety checklist for autonomous payers</h2>\n<ul><li>Use a <strong>separate wallet</strong> holding a small float. Never give the agent the operator&#39;s main key.</li><li>Keep the <strong>per-payment cap</strong> and add a <strong>daily budget</strong> in your own code.</li><li><strong>Allowlist</strong> networks and assets. The SDK default (USD stablecoins only) is a good baseline.</li><li><strong>Log</strong> every <code>PAYMENT-RESPONSE</code> (transaction hash, payer, amount) so a human can audit spend.</li><li>Treat a 402 body as <strong>untrusted input</strong>. A malicious server can advertise any <code>payTo</code> and any price, so the cap is your real protection.</li><li>Prefer <code>exact</code> for agents. With <code>upto</code> you authorize a ceiling, so set it no higher than you would pay.</li></ul>\n<h2>Alternatives</h2>\n<p>x402 is not the only HTTP-402 protocol. <a href=\"/entries/l402/\">L402</a> uses Lightning and macaroons, and the <a href=\"/entries/machine-payments-protocol/\">Machine Payments Protocol</a> is another agent payment standard. For a side-by-side view, see <a href=\"/compare/agent-payment-rails/\">Agent payment rails compared</a>.</p>"
}
