x402 支付協議深度剖析:HTTP 原生加密貨幣微支付的開放標準


生成提示詞

請深入分析 Coinbase x402 開放支付協議:
1. Clone x402 源代碼並閱讀規範文檔
2. 分析 HTTP 402 狀態碼的創新使用方式
3. 研究三方架構:Client、Resource Server、Facilitator
4. 解析 EIP-3009 (TransferWithAuthorization) 整合
5. 分析 TypeScript、Go、Python SDK 實現
6. 繪製 Mermaid 流程圖說明支付流程
7. 以繁體中文撰寫工程級深度文章

執行摘要

x402 是 Coinbase 推出的開放標準,實現了 HTTP 原生的加密貨幣微支付。本文將深入剖析其核心技術:

  • HTTP 402 原生整合:使用標準 HTTP 狀態碼實現支付要求
  • 三方架構設計:Client、Resource Server、Facilitator 分離
  • EIP-3009 簽名授權:無需 approve 的一次性授權轉帳
  • 信任最小化:Facilitator 無法重定向資金
  • 多鏈支援:EVM (USDC) 與 Solana (SPL Token)

目錄

  1. 協議設計哲學
  2. 三方架構解析
  3. HTTP 402 支付流程
  4. 核心數據結構
  5. 支付方案:EVM Exact Scheme
  6. 支付方案:Solana Exact Scheme
  7. Facilitator 介面規範
  8. SDK 實現分析
  9. 安全設計與信任模型

1. 協議設計哲學

1.1 五大核心原則

x402 建立在五個核心設計原則之上:

mindmap
  root((x402 設計原則))
    開放標準
      無單一依賴
      可互操作
      社區驅動
    HTTP 原生
      標準狀態碼
      無額外請求
      無縫整合
    鏈與代幣無關
      多鏈支援
      多方案擴展
      靈活配置
    信任最小化
      Facilitator 無法挪用
      簽名即授權
      無需 approve
    易於使用
      抽象複雜性
      SDK 封裝
      開發者友好

1.2 解決的核心問題

傳統網路支付的痛點:

問題傳統方案x402 方案
微支付成本高信用卡 2-3% 手續費區塊鏈低費用
跨境支付慢3-5 工作天秒級確認
需要帳戶註冊複雜 KYC 流程錢包即身份
API 計費複雜月結/預付按請求付費
中心化依賴支付網關控制開放標準

2. 三方架構解析

2.1 角色定義

flowchart TB
    subgraph Client["Client (客戶端)"]
        CWallet[擁有錢包]
        CSign[創建支付簽名]
        CPay[發起支付請求]
    end

    subgraph Server["Resource Server (資源服務器)"]
        SProtect[保護資源]
        SRequire[要求支付]
        SVerify[驗證支付]
        SReturn[返回資源]
    end

    subgraph Facilitator["Facilitator (促進者)"]
        FVerify[驗證簽名]
        FSettle[鏈上結算]
        FGas[支付 Gas 費]
        FMulti[多鏈支援]
    end

    Client -->|1. 請求資源| Server
    Server -->|2. 402 Payment Required| Client
    Client -->|3. 帶支付簽名的請求| Server
    Server -->|4. 驗證請求| Facilitator
    Facilitator -->|5. 結算支付| Blockchain[(區塊鏈)]
    Facilitator -->|6. 結算結果| Server
    Server -->|7. 返回資源| Client

2.2 職責分離

Client(客戶端):

  • 持有加密貨幣錢包
  • 使用私鑰簽署支付授權
  • 發送帶支付簽名的 HTTP 請求

Resource Server(資源服務器):

  • 保護需要付費的資源
  • 返回支付要求(PaymentRequired)
  • 委託 Facilitator 驗證和結算

Facilitator(促進者):

  • 驗證支付簽名有效性
  • 提交區塊鏈交易
  • 支付 Gas 費用
  • 支援多鏈多代幣

2.3 為什麼需要 Facilitator?

flowchart LR
    subgraph Without["沒有 Facilitator"]
        C1[Client] -->|需要 Gas| B1[區塊鏈]
        S1[Server] -->|需要 Gas| B1
    end

    subgraph With["有 Facilitator"]
        C2[Client] -->|只需簽名| F[Facilitator]
        S2[Server] -->|只需 API| F
        F -->|支付 Gas| B2[區塊鏈]
    end

優勢:

  1. 客戶端無需持有 ETH/SOL 支付 Gas
  2. 服務器無需管理區塊鏈連接
  3. 統一處理多鏈結算邏輯
  4. 專業的交易提交與重試機制

3. HTTP 402 支付流程

3.1 標準 HTTP 402 狀態碼

HTTP 402 “Payment Required” 最初在 HTTP/1.1 規範中保留,x402 賦予其實際意義:

HTTP/1.1 402 Payment Required
Content-Type: application/json
PAYMENT-REQUIRED: eyJ4NDAyVmVyc2lvbiI6Miw...

{
  "error": "Payment required"
}

3.2 完整支付流程(12 步)

sequenceDiagram
    participant C as Client
    participant S as Resource Server
    participant F as Facilitator
    participant B as Blockchain

    C->>S: 1. GET /resource
    S-->>C: 2. 402 + PAYMENT-REQUIRED header

    Note over C: 3. 選擇支付選項
    Note over C: 4. 創建 PaymentPayload

    C->>S: 5. GET /resource + PAYMENT-SIGNATURE header
    S->>F: 6. POST /verify
    F-->>S: 7. VerifyResponse

    alt 驗證成功
        S->>F: 8. POST /settle
        F->>B: 9. 提交交易
        B-->>F: 10. 交易確認
        F-->>S: 11. SettlementResponse
        S-->>C: 12. 200 OK + PAYMENT-RESPONSE header
    else 驗證失敗
        S-->>C: 402 Payment Required
    end

3.3 HTTP Header 規範

服務器 → 客戶端(402 響應):

HTTP/1.1 402 Payment Required
PAYMENT-REQUIRED: <base64(PaymentRequired JSON)>

客戶端 → 服務器(付費請求):

GET /resource HTTP/1.1
PAYMENT-SIGNATURE: <base64(PaymentPayload JSON)>

服務器 → 客戶端(成功響應):

HTTP/1.1 200 OK
PAYMENT-RESPONSE: <base64(SettlementResponse JSON)>

{resource data}

4. 核心數據結構

4.1 PaymentRequired(支付要求)

服務器返回的支付要求:

interface PaymentRequired {
  x402Version: 2;
  error: "Payment signature required";
  resource: {
    url: string;           // 資源 URL
    description: string;   // 資源描述
    mimeType: string;      // 內容類型
  };
  accepts: PaymentRequirements[];  // 接受的支付方式
  extensions?: Record<string, unknown>;
}

interface PaymentRequirements {
  scheme: string;          // 支付方案 (如 "exact")
  network: string;         // 網絡 (如 "eip155:8453")
  amount: string;          // 原子單位金額
  asset: string;           // 代幣合約地址
  payTo: string;           // 收款地址
  maxTimeoutSeconds: number; // 最大超時
  extra?: {                // 額外參數
    name?: string;         // 代幣名稱
    version?: string;      // 合約版本
  };
}

範例:

{
  "x402Version": 2,
  "error": "Payment signature required",
  "resource": {
    "url": "https://api.example.com/premium-data",
    "description": "Premium market data API",
    "mimeType": "application/json"
  },
  "accepts": [
    {
      "scheme": "exact",
      "network": "eip155:8453",
      "amount": "10000",
      "asset": "0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913",
      "payTo": "0x209693Bc6afc0C5328bA36FaF03C514EF312287C",
      "maxTimeoutSeconds": 60,
      "extra": {
        "name": "USDC",
        "version": "2"
      }
    }
  ]
}

4.2 PaymentPayload(支付載荷)

客戶端創建的支付載荷:

interface PaymentPayload {
  x402Version: 2;
  resource?: ResourceInfo;
  accepted: PaymentRequirements;  // 選擇的支付方式
  payload: Record<string, unknown>; // 方案特定載荷
  extensions?: Record<string, unknown>;
}

4.3 SettlementResponse(結算響應)

Facilitator 返回的結算結果:

interface SettlementResponse {
  success: boolean;
  transaction: string;   // 交易哈希
  network: string;       // 網絡標識
  payer?: string;        // 付款人地址
  errorReason?: string;  // 失敗原因
}

5. 支付方案:EVM Exact Scheme

5.1 EIP-3009 核心概念

EIP-3009 定義了 transferWithAuthorization,允許通過簽名授權轉帳,無需事先 approve:

interface IEIP3009 {
    function transferWithAuthorization(
        address from,
        address to,
        uint256 value,
        uint256 validAfter,
        uint256 validBefore,
        bytes32 nonce,
        uint8 v,
        bytes32 r,
        bytes32 s
    ) external;
}

5.2 EIP-712 簽名結構

const authorizationTypes = {
  TransferWithAuthorization: [
    { name: "from", type: "address" },
    { name: "to", type: "address" },
    { name: "value", type: "uint256" },
    { name: "validAfter", type: "uint256" },
    { name: "validBefore", type: "uint256" },
    { name: "nonce", type: "bytes32" }
  ]
};

const domain = {
  name: "USD Coin",
  version: "2",
  chainId: 8453,
  verifyingContract: "0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913"
};

5.3 Payload 結構

{
  "payload": {
    "signature": "0x2d6a7588d6acca505cbf0d9a4a227e0c...",
    "authorization": {
      "from": "0x857b06519E91e3A54538791bDbb0E22373e36b66",
      "to": "0x209693Bc6afc0C5328bA36FaF03C514EF312287C",
      "value": "10000",
      "validAfter": "1740672089",
      "validBefore": "1740672154",
      "nonce": "0xf3746613c2d920b5fdabc..."
    }
  }
}

5.4 驗證流程

flowchart TB
    Start[接收 PaymentPayload] --> V1{驗證 EIP-712 簽名}
    V1 -->|失敗| Fail[返回 invalid_signature]

    V1 -->|成功| V2{檢查餘額}
    V2 -->|不足| Fail2[返回 insufficient_funds]

    V2 -->|足夠| V3{金額匹配?}
    V3 -->|不匹配| Fail3[返回 amount_mismatch]

    V3 -->|匹配| V4{時間窗口有效?}
    V4 -->|過期| Fail4[返回 expired]

    V4 -->|有效| V5{Nonce 未使用?}
    V5 -->|已使用| Fail5[返回 nonce_used]

    V5 -->|未使用| V6{模擬交易}
    V6 -->|失敗| Fail6[返回 simulation_failed]

    V6 -->|成功| Success[返回 isValid: true]

5.5 結算執行

// Facilitator 調用 USDC 合約
IEIP3009(usdcAddress).transferWithAuthorization(
    authorization.from,
    authorization.to,
    authorization.value,
    authorization.validAfter,
    authorization.validBefore,
    authorization.nonce,
    v, r, s
);

關鍵安全特性:

  • Facilitator 無法修改 to 地址(簽名包含)
  • Facilitator 無法修改金額(簽名包含)
  • 時間窗口防止過期簽名被使用
  • Nonce 防止重放攻擊

6. 支付方案:Solana Exact Scheme

6.1 SPL Token TransferChecked

Solana 使用 TransferChecked 指令進行驗證轉帳:

pub struct TransferChecked {
    pub token_program: AccountInfo,
    pub source: AccountInfo,        // 來源代幣帳戶
    pub destination: AccountInfo,   // 目標代幣帳戶
    pub mint: AccountInfo,          // 代幣 Mint
    pub owner: AccountInfo,         // 代幣擁有者
}

6.2 Payload 結構

{
  "payload": {
    "transaction": "AAAAAAAAAAAAA...AAAAAAAAAAAAA="
  }
}

6.3 嚴格驗證規則

flowchart TB
    Start[接收交易] --> I1{指令順序正確?}
    I1 -->|否| Fail1[拒絕]

    I1 -->|是| I2{Compute Budget}
    I2 --> I3{Set Compute Unit Limit}
    I3 --> I4{Set Compute Unit Price}
    I4 --> I5{SPL TransferChecked}

    I5 --> V1{Fee Payer 不在指令中?}
    V1 -->|否| Fail2[拒絕 - 安全風險]

    V1 -->|是| V2{Compute Price <= 5?}
    V2 -->|否| Fail3[拒絕 - 費用過高]

    V2 -->|是| V3{目標 ATA 正確?}
    V3 -->|否| Fail4[拒絕 - 地址錯誤]

    V3 -->|是| V4{金額匹配?}
    V4 -->|否| Fail5[拒絕 - 金額不符]

    V4 -->|是| Success[驗證通過]

關鍵安全規則:

  1. Fee Payer 地址不能出現在任何指令帳戶中
  2. Fee Payer 不能是轉帳授權人
  3. Fee Payer 不能是資金來源
  4. Compute Unit Price <= 5 lamports

7. Facilitator 介面規範

7.1 三個標準端點

GET /supported - 查詢支援的網絡:

{
  "kinds": [
    {
      "x402Version": 2,
      "scheme": "exact",
      "network": "eip155:8453"
    },
    {
      "x402Version": 2,
      "scheme": "exact",
      "network": "solana:5eykt4UsFv8P8NJdTREpY1vzqKqZKvdp"
    }
  ]
}

POST /verify - 驗證支付(不執行):

// 請求
interface VerifyRequest {
  paymentPayload: PaymentPayload;
  paymentRequirements: PaymentRequirements;
}

// 響應
interface VerifyResponse {
  isValid: boolean;
  payer?: string;
  invalidReason?: string;  // "insufficient_funds" | "invalid_signature" | ...
}

POST /settle - 執行結算:

interface SettleResponse {
  success: boolean;
  transaction?: string;
  network?: string;
  payer?: string;
  errorReason?: string;
}

7.2 支援的網絡(CAIP-2 格式)

網絡CAIP-2 標識
Ethereum Mainneteip155:1
Base Mainneteip155:8453
Base Sepoliaeip155:84532
Optimismeip155:10
Arbitrum Oneeip155:42161
Polygoneip155:137
Solana Mainnetsolana:5eykt4UsFv8P8NJdTREpY1vzqKqZKvdp
Solana Devnetsolana:EtWTRABZaYq6iMfeYKouRu166VU2xqa1

8. SDK 實現分析

8.1 TypeScript SDK 架構

@x402/
├── core/          # 框架無關的核心邏輯
├── evm/           # EVM exact scheme
├── svm/           # Solana exact scheme
├── fetch/         # 原生 fetch 封裝
├── axios/         # Axios 整合
└── express/       # Express 中間件

客戶端使用:

import { x402Client } from '@x402/core';
import { exactEvm } from '@x402/evm';
import { createX402Fetch } from '@x402/fetch';

// 創建客戶端
const client = new x402Client();
client.register('eip155:*', exactEvm.client(signer, provider));

// 封裝 fetch
const x402Fetch = createX402Fetch(client);

// 自動處理 402
const response = await x402Fetch('https://api.example.com/data');

服務器中間件:

import { x402PaymentMiddleware } from '@x402/express';

app.use(x402PaymentMiddleware({
  facilitator: facilitatorClient,
  routes: {
    'GET /api/data': {
      price: '$0.001',
      payTo: '0x...',
      network: 'eip155:8453'
    }
  }
}));

8.2 Go SDK 架構

// 客戶端
client := x402.Newx402Client().
    Register("eip155:*", evm.NewExactEvmScheme(evmSigner)).
    Register("solana:*", svm.NewExactSvmScheme(svmSigner))

// 資源服務器
server := x402.Newx402ResourceServer(
    x402.WithFacilitatorClient(facilitatorClient),
)

// Facilitator
facilitator := x402.Newx402Facilitator().
    Register([]x402.Network{"eip155:8453"}, evmScheme)

Gin 中間件:

r.Use(ginmw.X402Payment(ginmw.Config{
    Routes: x402http.RoutesConfig{
        "GET /data": {
            Accepts: x402http.PaymentOptions{
                {Scheme: "exact", Price: "$0.001", Network: "eip155:8453"},
            },
        },
    },
    Facilitator: facilitatorClient,
}))

8.3 Python SDK 架構

FastAPI 中間件:

from x402.fastapi.middleware import require_payment

app = FastAPI()
app.middleware("http")(
    require_payment(
        price="$0.01",
        pay_to_address="0x..."
    )
)

HTTP 客戶端:

from x402.clients.httpx import x402HttpxClient
from eth_account import Account

account = Account.from_key("private_key")
async with x402HttpxClient(account=account) as client:
    response = await client.get("https://api.example.com/data")

9. 安全設計與信任模型

9.1 信任最小化

flowchart LR
    subgraph Traditional["傳統支付"]
        T1[用戶] -->|信任| T2[支付網關]
        T2 -->|控制| T3[資金]
    end

    subgraph x402["x402 支付"]
        X1[用戶] -->|簽名| X2[Facilitator]
        X2 -->|只能提交| X3[區塊鏈]

        Note1[簽名包含:收款人、金額]
        Note2[Facilitator 無法修改]
    end

Facilitator 的限制:

  • 無法修改收款地址(簽名包含)
  • 無法修改金額(簽名包含)
  • 無法重複使用(Nonce 保護)
  • 無法延遲過久(時間窗口)

9.2 安全機制總結

機制威脅防護
EIP-712 簽名篡改授權結構化數據簽名
Nonce重放攻擊唯一性檢查
時間窗口過期簽名validBefore 檢查
金額精確匹配過度收費鏈上驗證
Fee Payer 隔離資金挪用指令驗證

9.3 失敗處理

// 驗證失敗原因
type InvalidReason =
  | "insufficient_funds"    // 餘額不足
  | "invalid_signature"     // 簽名無效
  | "amount_mismatch"       // 金額不匹配
  | "expired"               // 簽名過期
  | "nonce_used"            // Nonce 已使用
  | "simulation_failed"     // 模擬失敗
  | "network_mismatch";     // 網絡不匹配

總結

x402 的創新

  1. HTTP 402 復活

    • 30 年前保留的狀態碼終於有實際用途
    • 無縫整合現有 HTTP 基礎設施
  2. 簽名即授權

    • 無需 approve 的一次性轉帳
    • 客戶端無需持有 Gas
  3. 三方分離

    • 關注點分離
    • 專業化分工
    • 降低集成複雜度
  4. 多鏈擴展

    • Scheme-Network 抽象
    • 易於添加新鏈

適用場景

場景優勢
API 計費按請求付費,無月費
內容付費微支付解鎖
AI 服務按 token 計費
數據市場即時交易
跨境支付秒級結算

關鍵文件路徑

規範文檔:
├── specs/x402-specification-v2.md
├── specs/schemes/exact/scheme_exact_evm.md
├── specs/schemes/exact/scheme_exact_svm.md
└── specs/transports-v2/http.md

SDK 實現:
├── typescript/packages/core/
├── go/
└── python/x402/

範例:
├── examples/typescript/
├── examples/go/
└── examples/python/

x402 展示了如何將加密貨幣支付無縫整合到現有 HTTP 基礎設施中,其信任最小化設計和多語言 SDK 支援使其成為 Web3 微支付的有力候選。