> ## 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가 가격 세부 정보(금액, 토큰, 체인, payTo 주소)가 포함된 `PAYMENT-REQUIRED` 헤더와 함께 HTTP 402로 응답합니다.
  </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 챌린지를 반환해야 합니다.

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