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

# x402 微支付

> 使用 HTTP 402 协议按 API 调用付费 — 会话预算、自动协商和结算。

## 什么是 x402？

x402 是围绕 HTTP `402 Payment Required` 构建的机器对机器支付协议。它使 AI 代理能够自动支付 API 访问费用，无需人工干预。AgentWallex 实现了带有 EIP-3009 授权载荷的 x402 v2。

## x402 v2 头部

该协议使用三个 HTTP 头部：

| 头部                  | 方向      | 用途            |
| ------------------- | ------- | ------------- |
| `PAYMENT-REQUIRED`  | 服务器到客户端 | 带定价信息的 402 挑战 |
| `PAYMENT-SIGNATURE` | 客户端到服务器 | 签名的支付载荷       |
| `PAYMENT-RESPONSE`  | 服务器到客户端 | 结算确认          |

## 支付流程

```
Client Agent               Paid API               AgentWallex
    |                        |                         |
    |-- GET /resource ------>|                         |
    |<-- 402 + PAYMENT-REQUIRED                        |
    |                        |                         |
    |-- POST /api/v1/x402/pay -----------------------> |
    |                        |     (sign + policy)     |
    |<-- payment_info        |                         |
    |                        |                         |
    |-- GET /resource + PAYMENT-SIGNATURE -----------> |
    |<-- 200 + PAYMENT-RESPONSE                        |
```

<Steps>
  <Step title="代理请求资源">
    代理向付费 API 端点发送标准 HTTP 请求。
  </Step>

  <Step title="服务器返回 402">
    API 响应 HTTP 402 并附带 `PAYMENT-REQUIRED` 头部，其中包含定价详情（金额、代币、链、收款地址）。
  </Step>

  <Step title="代理通过 AgentWallex 支付">
    代理将支付详情发送到 `POST /x402/pay`。AgentWallex 评估策略并签署支付。
  </Step>

  <Step title="代理携带支付凭证重试">
    代理使用附带的 `PAYMENT-SIGNATURE` 头部重试原始请求。
  </Step>

  <Step title="服务器验证并响应">
    API 验证支付签名（通过 AgentWallex facilitator）并返回资源。
  </Step>
</Steps>

## 使用 x402 API

### 检查 URL 是否支持 x402

```bash theme={null}
curl -X POST https://api.agentwallex.com/api/v1/x402/check \
  -H "X-API-Key: awx_your_api_key" \
  -H "Content-Type: application/json" \
  -d '{"url": "https://paid-api.example.com/v1/data"}'
```

### 创建会话预算

会话允许您为重复的 API 调用预授权消费预算：

```bash theme={null}
curl -X POST https://api.agentwallex.com/api/v1/x402/sessions \
  -H "X-API-Key: awx_your_api_key" \
  -H "Content-Type: application/json" \
  -d '{
    "agent_id": "agent_uuid",
    "budget_limit": "100.00",
    "chain": "eip155:84532",
    "ttl_seconds": 3600,
    "allowed_urls": ["https://paid-api.example.com/v1/data"]
  }'
```

### 触发支付协商

```bash theme={null}
curl -X POST https://api.agentwallex.com/api/v1/x402/pay \
  -H "X-API-Key: awx_your_api_key" \
  -H "Content-Type: application/json" \
  -d '{
    "agent_id": "agent_uuid",
    "target_url": "https://paid-api.example.com/v1/data",
    "session_id": "optional_session_uuid",
    "chain": "eip155:84532"
  }'
```

响应包含 `payment_info`，其中包括：

| 字段           | 说明             |
| ------------ | -------------- |
| `ledger_id`  | 内部账本条目 ID      |
| `amount`     | 支付金额           |
| `fee_amount` | 平台扣除的费用        |
| `fee_rate`   | 适用的费率百分比       |
| `token`      | 使用的代币（例如 USDC） |
| `chain`      | 用于结算的链         |
| `status`     | 支付状态           |

## SDK 集成

### 自动 HTTP 拦截器

TypeScript SDK 提供了一个拦截器，可自动处理完整的 x402 流程：

```typescript theme={null}
const fetchWithPayment = aw.x402.httpInterceptor({
  agentId: "agent_abc123",
  chain: "eip155:84532",
});

// This automatically handles 402 challenges
const response = await fetchWithPayment("https://paid-api.example.com/v1/data");
const data = await response.json();
```

### 手动流程

```typescript theme={null}
// 1. Create a session budget
const session = await aw.x402.createSession({
  agentId: "agent_abc123",
  budgetLimit: "100.00",
  chain: "eip155:84532",
  ttlSeconds: 3600,
  allowedUrls: ["https://paid-api.example.com/v1/data"],
});

// 2. Pay for an API call
const result = await aw.x402.pay({
  agentId: "agent_abc123",
  targetUrl: "https://paid-api.example.com/v1/data",
  sessionId: session.id,
  chain: "eip155:84532",
});

// 3. Or pay using the session directly
await aw.x402.sessionPay(session.id, {
  targetUrl: "https://paid-api.example.com/v1/data",
});
```

## 面向服务提供商

如果您公开付费 API，当缺少支付时，您的服务器应返回 x402 v2 挑战。

### 返回 402 和 PAYMENT-REQUIRED

将 JSON 挑战（base64 编码）放入 `PAYMENT-REQUIRED` 头部：

```json theme={null}
{
  "x402Version": 2,
  "resource": "https://your-api.com/v1/data",
  "accepts": [
    {
      "scheme": "exact",
      "network": "eip155:8453",
      "amount": "0.10",
      "asset": "USDC",
      "payTo": "0xYourAddress",
      "maxTimeoutSeconds": 300
    }
  ]
}
```

### 验证和结算

使用 AgentWallex facilitator 端点：

```bash theme={null}
# Verify a payment signature
POST /api/v1/x402/facilitator/verify

# Settle a verified payment
POST /api/v1/x402/facilitator/settle

# Query supported chains
GET /api/v1/x402/facilitator/supported
```

## 运营默认参数

| 参数     | 值                                                    |
| ------ | ---------------------------------------------------- |
| 结算间隔   | 300 秒                                                |
| 结算阈值   | \$10.00                                              |
| 最大结算延迟 | 3,600 秒                                              |
| 支持的链   | `eip155:84532`、`eip155:8453`、`eip155:1`、`eip155:137` |
