> ## 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 不持有任何资金。
