x402 (official examples)

SkillDB 作者 notorious-d-e-v v1.0.1

Internet-native payments using the HTTP 402 Payment Required standard. Set up as a buyer to pay for API access, or as a seller to monetize your APIs.

源码 ↗

安装 / 下载方式

TotalClaw CLI推荐
totalclaw install skilldb:notorious-d-e-v~x402-enhanced
cURL直接下载,无需登录
curl -fsSL https://skills.taituai.com/api/skills/skilldb%3Anotorious-d-e-v~x402-enhanced/file -o x402-enhanced.md
Git 仓库获取源码
git clone https://github.com/clawdbot/skills/commit/074fa10fc0ed68d10d18fb9b3bf301491eabae32
# x402 Payment Protocol

x402 is an open, internet-native payment standard built around the HTTP `402 Payment Required` status code. It enables programmatic payments between clients and servers without accounts, sessions, or credential management.

**Key Benefits:**
- Zero protocol fees (only blockchain network fees)
- Zero friction (no accounts or KYC required)
- Instant settlement via stablecoins
- Works with AI agents and automated systems

**Documentation:** https://docs.x402.org | **GitHub:** https://github.com/coinbase/x402

---

## How x402 Works

1. Client requests a resource from a server
2. Server responds with `402 Payment Required` + payment instructions
3. Client signs and submits a payment payload
4. Server verifies payment, optionally via a facilitator
5. Server returns the requested resource

---

## Environment Variables

### For Buyers (Clients)
```bash
# EVM wallet private key (Ethereum/Base/Polygon)
EVM_PRIVATE_KEY=0x...

# Solana wallet private key (base58 encoded)
SVM_PRIVATE_KEY=...

# Target server URL
RESOURCE_SERVER_URL=http://localhost:4021
ENDPOINT_PATH=/weather
```

### For Sellers (Servers)
```bash
# Your EVM wallet address to receive payments
EVM_ADDRESS=0x...

# Your Solana wallet address to receive payments
SVM_ADDRESS=...

# Facilitator URL (see list below)
FACILITATOR_URL=https://x402.org/facilitator
```

---

## Network Identifiers (CAIP-2)

| Network | CAIP-2 ID | Description |
|---------|-----------|-------------|
| **Base** | | |
| Base Mainnet | `eip155:8453` | Base L2 mainnet |
| Base Sepolia | `eip155:84532` | Base L2 testnet |
| **Solana** | | |
| Solana Mainnet | `solana:5eykt4UsFv8P8NJdTREpY1vzqKqZKvdp` | Solana mainnet |
| Solana Devnet | `solana:EtWTRABZaYq6iMfeYKouRu166VU2xqa1` | Solana testnet |
| **Polygon** | | |
| Polygon Mainnet | `eip155:137` | Polygon PoS mainnet |
| Polygon Amoy | `eip155:80002` | Polygon testnet |
| **Avalanche** | | |
| Avalanche C-Chain | `eip155:43114` | Avalanche mainnet |
| Avalanche Fuji | `eip155:43113` | Avalanche testnet |
| **Sei** | | |
| Sei Mainnet | `eip155:1329` | Sei EVM mainnet |
| Sei Testnet | `eip155:713715` | Sei EVM testnet |
| **X Layer** | | |
| X Layer Mainnet | `eip155:196` | OKX L2 mainnet |
| X Layer Testnet | `eip155:1952` | OKX L2 testnet |
| **SKALE** | | |
| SKALE Base | `eip155:1187947933` | SKALE mainnet |
| SKALE Base Sepolia | `eip155:324705682` | SKALE testnet |


---

## Facilitators

Facilitators handle payment verification and blockchain settlement. Choose one:

| Name | URL | Notes |
|------|-----|-------|
| x402.org | `https://x402.org/facilitator` | Default, testnet only |
| Coinbase | `https://api.cdp.coinbase.com/platform/v2/x402` | Production |
| PayAI | `https://facilitator.payai.network` | Production |
| Corbits | `https://facilitator.corbits.dev` | Production |
| x402rs | `https://facilitator.x402.rs` | Production |
| Dexter | `https://x402.dexter.cash` | Production |
| Heurist | `https://facilitator.heurist.xyz` | Production |
| Kobaru | `https://gateway.kobaru.io` | Production |
| Mogami | `https://facilitator.mogami.tech` | Production |
| Nevermined | `https://api.live.nevermined.app/api/v1/` | Production |
| Openfacilitator | `https://pay.openfacilitator.io` | Production |
| Solpay | `https://x402.solpay.cash` | Production |
| Primer | `https://x402.primer.systems` | Production |
| xEcho | `https://facilitator.xechoai.xyz` | Production |

---

# Buyer Examples (Client)

## TypeScript with fetch

Install dependencies:
```bash
npm install @x402/fetch @x402/evm @x402/svm viem @solana/kit @scure/base dotenv
```

Code:
```typescript
import { config } from "dotenv";
import { x402Client, wrapFetchWithPayment, x402HTTPClient } from "@x402/fetch";
import { registerExactEvmScheme } from "@x402/evm/exact/client";
import { registerExactSvmScheme } from "@x402/svm/exact/client";
import { privateKeyToAccount } from "viem/accounts";
import { createKeyPairSignerFromBytes } from "@solana/kit";
import { base58 } from "@scure/base";

config();

const evmPrivateKey = process.env.EVM_PRIVATE_KEY as `0x${string}`;
const svmPrivateKey = process.env.SVM_PRIVATE_KEY as string;
const url = `${process.env.RESOURCE_SERVER_URL}${process.env.ENDPOINT_PATH}`;

async function main(): Promise<void> {
  const evmSigner = privateKeyToAccount(evmPrivateKey);
  const svmSigner = await createKeyPairSignerFromBytes(base58.decode(svmPrivateKey));

  const client = new x402Client();
  registerExactEvmScheme(client, { signer: evmSigner });
  registerExactSvmScheme(client, { signer: svmSigner });

  const fetchWithPayment = wrapFetchWithPayment(fetch, client);

  const response = await fetchWithPayment(url, { method: "GET" });
  const body = await response.json();
  console.log("Response:", body);

  if (response.ok) {
    const paymentResponse = new x402HTTPClient(client).getPaymentSettleResponse(
      name => response.headers.get(name)
    );
    console.log("Payment:", JSON.stringify(paymentResponse, null, 2));
  }
}

main().catch(console.error);
```

## TypeScript with axios

Install dependencies:
```bash
npm install @x402/axios @x402/evm @x402/svm axios viem @solana/kit @scure/base dotenv
```

Code:
```typescript
import { config } from "dotenv";
import { x402Client, wrapAxiosWithPayment, x402HTTPClient } from "@x402/axios";
import { registerExactEvmScheme } from "@x402/evm/exact/client";
import { registerExactSvmScheme } from "@x402/svm/exact/client";
import { privateKeyToAccount } from "viem/accounts";
import { createKeyPairSignerFromBytes } from "@solana/kit";
import { base58 } from "@scure/base";
import axios from "axios";

config();

const evmPrivateKey = process.env.EVM_PRIVATE_KEY as `0x${string}`;
const svmPrivateKey = process.env.SVM_PRIVATE_KEY as string;
const url = `${process.env.RESOURCE_SERVER_URL}${process.env.ENDPOINT_PATH}`;

async function main(): Promise<void> {
  const evmSigner = privateKeyToAccount(evmPrivateKey);
  const svmSigner = await createKeyPairSignerFromBytes(base58.decode(svmPrivateKey));

  const client = new x402Client();
  registerExactEvmScheme(client, { signer: evmSigner });
  registerExactSvmScheme(client, { signer: svmSigner });

  const api = wrapAxiosWithPayment(axios.create(), client);

  const response = await api.get(url);
  console.log("Response:", response.data);

  if (response.status < 400) {
    const paymentResponse = new x402HTTPClient(client).getPaymentSettleResponse(
      name => response.headers[name.toLowerCase()]
    );
    console.log("Payment:", paymentResponse);
  }
}

main().catch(console.error);
```

## Python with httpx (async)

Install dependencies:
```bash
pip install "x402[httpx,evm,svm]" python-dotenv
```

Code:
```python
import asyncio
import os
from dotenv import load_dotenv
from eth_account import Account

from x402 import x402Client
from x402.http import x402HTTPClient
from x402.http.clients import x402HttpxClient
from x402.mechanisms.evm import EthAccountSigner
from x402.mechanisms.evm.exact.register import register_exact_evm_client
from x402.mechanisms.svm import KeypairSigner
from x402.mechanisms.svm.exact.register import register_exact_svm_client

load_dotenv()

async def main() -> None:
    evm_private_key = os.getenv("EVM_PRIVATE_KEY")
    svm_private_key = os.getenv("SVM_PRIVATE_KEY")
    base_url = os.getenv("RESOURCE_SERVER_URL")
    endpoint_path = os.getenv("ENDPOINT_PATH")

    client = x402Client()

    if evm_private_key:
        account = Account.from_key(evm_private_key)
        register_exact_evm_client(client, EthAccountSigner(account))

    if svm_private_key:
        svm_signer = KeypairSigner.from_base58(svm_private_key)
        register_exact_svm_client(client, svm_signer)

    http_client = x402HTTPClient(client)
    url = f"{base_url}{endpoint_path}"

    async with x402HttpxClient(client) as http:
        response = await http.get(url)
        await response.aread()
        print(f"Response: {response.text}")

        if response.is_success:
            try: