> ## 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ヘッダー

プロトコルは3つの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ファシリテーター経由で）検証し、リソースを返します。
  </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チャレンジを返す必要があります。

### PAYMENT-REQUIREDを含む402を返す

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ファシリテーターエンドポイントを使用します：

```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` |
