> ## Documentation Index
> Fetch the complete documentation index at: https://docs.arouter.ai/llms.txt
> Use this file to discover all available pages before exploring further.

# x402 Agent 支付

> 讓擁有加密錢包的 AI Agent 自動儲值點數並完成驗證 — 無需註冊、無需 Dashboard，完全自主運行。

ARouter 支援 [x402 支付協議](https://x402.org)，這是面向 HTTP 原生支付的開放標準。
擁有加密錢包的 AI Agent 可以完成驗證、支付點數並發起 LLM 請求 —
無需註冊帳戶，也無需登入 Dashboard。

## 三種接入方式

ARouter 為 Agent 提供三種接入方式。API Key 使用者和錢包使用者現在遵循各自獨立的長期路徑：

| 接入方式           | 驗證方法                                 | 使用情境                                         |
| -------------- | ------------------------------------ | -------------------------------------------- |
| **標準 x402 支付** | 僅 `PAYMENT-SIGNATURE` 請求標頭           | 任何 x402 用戶端 — 首次錢包支付註冊帳戶並返回錢包 JWT            |
| **SIWx 驗證**    | `SIGN-IN-WITH-X` 請求標頭                | 證明錢包所有權 → 取得錢包 JWT（無需支付）                     |
| **API Key**    | `Authorization: Bearer lr_live_xxxx` | 現有 API Key 使用者 — 餘額不足時返回 `403`，不自動觸發 x402 儲值 |

<Info>
  標準 x402 模式適用於**任何 x402 相容工具** — `@x402/fetch`、`awal`、MCP 錢包、Chrome 擴充功能。
  無需 ARouter SDK。
</Info>

***

## 運作原理

### 標準 x402（任何 x402 用戶端）

最簡單的接入方式。任何持有 USDC 的錢包都可以立即發起 LLM 請求：

```mermaid theme={null}
sequenceDiagram
    participant Wallet as 任意錢包
    participant Client as x402 用戶端 (@x402/fetch)
    participant GW as ARouter 閘道
    participant Chain as Base / Solana

    Client->>GW: POST /v1/chat/completions（無驗證）
    GW-->>Client: 402 + PAYMENT-REQUIRED
    Client->>Wallet: 簽署 USDC 支付（免 Gas EIP-3009）
    Wallet-->>Client: 已簽署支付
    Client->>GW: 重試 + PAYMENT-SIGNATURE
    GW->>Chain: 驗證並結算
    GW-->>Client: 200 OK + PAYMENT-RESPONSE(jwt)
    Note over Client: 儲存錢包 JWT 以供後續請求使用
```

1. 發送**無 API Key** 的請求 — 閘道返回 **HTTP 402** 及支付選項。
2. x402 用戶端簽署 USDC 支付（透過 EIP-3009 免 Gas 進行）。
3. 攜帶 `PAYMENT-SIGNATURE` 請求標頭重試。
4. 閘道驗證、結算、建立帳戶並返回回應。
5. `PAYMENT-RESPONSE` 請求標頭包含用於後續錢包驗證請求的 `jwt` 擴充欄位。

### SIWx 驗證（錢包登入）

證明錢包所有權以取得錢包 JWT，無需先支付：

```mermaid theme={null}
sequenceDiagram
    participant Wallet as 任意錢包
    participant Client as 用戶端
    participant Auth as POST /v1/x402/auth

    Client->>Wallet: 簽署 CAIP-122 訊息
    Wallet-->>Client: 簽名
    Client->>Auth: SIGN-IN-WITH-X 請求標頭
    Auth-->>Client: {"jwt": "eyJ..."}
    Note over Client: 使用 Bearer JWT 進行錢包請求
```

SIWx 遵循 [CAIP-122 標準](https://chainagnostic.org/CAIPs/caip-122) — 與 QuickNode 及其他支援 x402 的服務採用相同協議。

### API Key 使用者

現有 API Key 使用者繼續使用標準 ARouter API Key 流程：

```mermaid theme={null}
sequenceDiagram
    participant Agent as AI Agent + 錢包
    participant GW as ARouter 閘道
    participant Chain as Base / Solana

    Agent->>GW: POST /v1/chat/completions（Bearer token）
    GW-->>Agent: 403 點數不足
    Note over Agent: 透過 Dashboard / Stripe / 傳統帳單儲值
```

***

## 支援的網路

| 網路                | CAIP-2 識別碼                                | Token |
| ----------------- | ----------------------------------------- | ----- |
| Base 主網           | `eip155:8453`                             | USDC  |
| Base Sepolia（測試網） | `eip155:84532`                            | USDC  |
| Solana 主網         | `solana:5eykt4UsFv8P8NJdTREpY1vzqKqZKvdp` | USDC  |
| Solana Devnet     | `solana:EtWTRABZaYq6iMfeYKouRu166VU2xqa1` | USDC  |

## 錢包相容性

所有錢包均可使用 — **無需匯出私鑰**：

| 錢包                    | 支付 (EIP-3009) | 驗證 (SIWx) | 需要私鑰？       |
| --------------------- | ------------- | --------- | ----------- |
| MetaMask              | ✓             | ✓         | 否           |
| Coinbase Wallet       | ✓             | ✓         | 否           |
| Coinbase Agent Wallet | ✓             | ✓         | 否 (CDP API) |
| Phantom (Solana)      | ✓             | ✓         | 否           |
| 本機私鑰                  | ✓             | ✓         | 是           |

***

## SDK 使用方法

### 標準 x402（無需 ARouter SDK）

直接使用 Coinbase 官方 `@x402/fetch`：

```typescript theme={null}
import { wrapFetchWithPayment } from "@x402/fetch";
import { x402Client } from "@x402/core/client";
import { ExactEvmScheme } 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();
client.register("eip155:*", new ExactEvmScheme(signer));

const paidFetch = wrapFetchWithPayment(fetch, client);

const resp = await paidFetch("https://api.arouter.ai/v1/chat/completions", {
  method: "POST",
  headers: { "Content-Type": "application/json" },
  body: JSON.stringify({
    model: "openai/gpt-5.4",
    messages: [{ role: "user", content: "Hello" }],
  }),
});
```

### SIWx 驗證（取得錢包 JWT）

#### Node.js SDK

```typescript theme={null}
import { ARouter, authenticateWithSIWx } from "@arouter/sdk";
import { privateKeyToAccount } from "viem/accounts";

const account = privateKeyToAccount(process.env.EVM_PRIVATE_KEY as `0x${string}`);

const { jwt } = await authenticateWithSIWx(
  "https://api.arouter.ai",
  { address: account.address, signMessage: (msg) => account.signMessage({ message: msg }) },
);

const client = new ARouter({ baseURL: "https://api.arouter.ai", apiKey: jwt });
```

#### Go SDK

```go theme={null}
import arouter "github.com/arouter-ai/arouter-go"

signer := arouter.NewEvmWalletSigner(privateKey)
result, err := arouter.AuthenticateWithSIWx(ctx, "https://api.arouter.ai", signer, nil)

client := arouter.NewClient("https://api.arouter.ai", result.JWT)
```

### ARouter SDK + 自動支付（推薦高頻使用）

#### Go SDK — EVM (Base)

```go theme={null}
import (
    "github.com/ethereum/go-ethereum/crypto"
    arouter "github.com/arouter-ai/arouter-go"
)

key, _ := crypto.HexToECDSA("your-private-key-hex")

client := arouter.NewClient(
    "https://api.arouter.ai",
    "",  // 無需 API Key
    arouter.WithX402CoinbasePayment(key),
)
```

`WithX402CoinbasePayment` 設定帶 JWT 快取的錢包 x402 支付：

* 首次成功支付在 `PAYMENT-RESPONSE` 中返回錢包 JWT
* 後續請求使用 `Bearer <jwt>`
* `401` 觸發 SIWx 重新驗證
* `402` 觸發 x402 支付

#### Go SDK — Solana

```go theme={null}
solanaKey := ed25519.PrivateKey(yourKeyBytes)
client := arouter.NewClient("https://api.arouter.ai", "",
    arouter.WithX402SolanaPayment(solanaKey),
)
```

#### Node.js SDK — EVM (Base)

```typescript theme={null}
import { ARouter, withX402EvmPayment } from "@arouter/sdk";
import { privateKeyToAccount } from "viem/accounts";

const signer = privateKeyToAccount(process.env.EVM_PRIVATE_KEY as `0x${string}`);
const client = withX402EvmPayment(
  new ARouter({ baseURL: "https://api.arouter.ai", apiKey: "" }),
  signer,
);
```

#### Node.js SDK — 雙鏈（EVM + Solana）

```typescript theme={null}
import { ARouter, withX402Payment } from "@arouter/sdk";

const client = withX402Payment(
  new ARouter({ baseURL: "https://api.arouter.ai", apiKey: "" }),
  {
    evm: { signer: evmAccount },
    solana: { signer: solanaSigner },
  },
);
```

### CLI 工具的 GET 端點

適用於無法傳送 POST 請求體的 x402 CLI 工具（如 `awal`）：

```
GET /v1/x402/chat?model=openai/gpt-5.4&message=Hello&system=Be+brief&max_tokens=100
```

| 參數            | 是否必填 | 說明                       |
| ------------- | ---- | ------------------------ |
| `model`       | 是    | 模型名稱，例如 `openai/gpt-5.4` |
| `message`     | 是    | 使用者訊息文字                  |
| `system`      | 否    | 系統提示詞                    |
| `max_tokens`  | 否    | 最大輸出 Token 數             |
| `temperature` | 否    | 溫度參數                     |
| `stream`      | 否    | 設定為 `true` 以啟用串流輸出       |

***

## 支付請求標頭

| 請求標頭                | 方向        | 說明                                        |
| ------------------- | --------- | ----------------------------------------- |
| `PAYMENT-REQUIRED`  | 伺服端 → 用戶端 | Base64 編碼的支付選項（金額、錢包、網路）。                 |
| `PAYMENT-SIGNATURE` | 用戶端 → 伺服端 | Base64 編碼的已簽署支付載荷。                        |
| `SIGN-IN-WITH-X`    | 用戶端 → 伺服端 | Base64 編碼的 SIWx 驗證憑證。                     |
| `PAYMENT-RESPONSE`  | 伺服端 → 用戶端 | Base64 編碼的結算結果。ARouter 為錢包使用者新增 `jwt` 欄位。 |

## 點數運作原理

* x402 支付以**點數**形式存入租戶餘額 — 與 Stripe 和 Helio 支付共享同一點數池。
* 所有 x402 交易均顯示在**帳單**頁面的交易記錄中，參考類型為 `x402_topup`。
* 餘額儲值後，閘道按每次請求照常扣除點數。
* 錢包使用者按租戶計費，透過錢包 JWT 驗證，並可透過 SIWx 重新驗證，無需暴露原始 API Key。

## 安全性

* **標準 x402 協議**：使用 Coinbase 官方 x402 SDK 進行驗證和結算。
* **Facilitator 驗證**：支付透過 [x402 Facilitator](https://x402.org) 加密驗證後才會授予點數。
* **免 Gas 支付**：EIP-3009（TransferWithAuthorization）— 使用者簽名，Facilitator 提交上鏈。
* **金額上限**：單次支付設有上限，防止意外大額扣費。
* **冪等性**：每個支付載荷具有唯一 nonce — 同一簽名不可重放。
* **SIWx 標準**：驗證遵循 [CAIP-122](https://chainagnostic.org/CAIPs/caip-122)，支援 EIP-4361（EVM）和 SIWS（Solana）訊息格式。
* **稽核軌跡**：所有 x402 儲值與 Stripe/Helio 支付一同記錄在交易記錄中。
* **非託管**：USDC 直接轉入接收錢包。Facilitator 不持有任何資金。
