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

# 웹훅

> 결제, 정책 위반, 에이전트 이벤트에 대한 실시간 알림을 수신합니다.

## 개요

웹훅은 HTTP POST 요청을 통해 애플리케이션에 실시간 이벤트 알림을 전달합니다. 결제, 정책 위반, 에이전트 상태 변경, x402 세션 이벤트에 대응하기 위해 사용합니다.

## 웹훅 설정

### SDK를 통한 설정

```typescript theme={null}
const webhook = await aw.webhooks.create({
  url: "https://your-app.com/webhooks/agentwallex",
  events: [
    "payment.completed",
    "payment.failed",
    "agent.frozen",
    "policy.violated",
  ],
  secret: "whsec_your_signing_secret",
});
```

### API를 통한 설정

```bash theme={null}
curl -X POST https://api.agentwallex.com/api/v1/webhooks \
  -H "X-API-Key: awx_your_api_key" \
  -H "Content-Type: application/json" \
  -d '{
    "url": "https://your-app.com/webhooks/agentwallex",
    "events": ["payment.completed", "payment.failed", "agent.frozen", "policy.violated"],
    "secret": "whsec_your_signing_secret"
  }'
```

## 이벤트 유형

| 이벤트                    | 설명                   |
| ---------------------- | -------------------- |
| `payment.completed`    | 온체인에서 거래가 확인됨        |
| `payment.failed`       | 거래가 실패하거나 되돌려짐       |
| `payment.pending`      | 거래가 제출되었으며 확인 대기 중   |
| `agent.frozen`         | 에이전트 지갑이 동결됨         |
| `agent.unfrozen`       | 에이전트 지갑이 해제됨         |
| `policy.violated`      | 정책 엔진에 의해 거래가 거부됨    |
| `x402.session.expired` | x402 세션 예산 또는 TTL 초과 |
| `approval.requested`   | 사람 승인을 기다리는 고액 거래    |

## 웹훅 페이로드

모든 웹훅 전달에는 다음 구조의 JSON 페이로드가 포함됩니다:

```json theme={null}
{
  "id": "evt_abc123",
  "type": "payment.completed",
  "created_at": "2025-06-15T14:30:00Z",
  "data": {
    "transaction_id": "tx_xyz789",
    "agent_id": "agent_abc123",
    "amount": "50.00",
    "token": "USDC",
    "chain": "eip155:8453",
    "hash": "0xabc...def",
    "status": "confirmed"
  }
}
```

## 서명 검증

모든 웹훅 전달에는 검증을 위한 서명 헤더가 포함됩니다. 웹훅 이벤트를 처리하기 전에 항상 서명을 검증하세요.

### 작동 방식

AgentWallex는 등록 시 제공한 시크릿을 사용하여 각 웹훅 페이로드에 서명합니다. 서명은 `X-AgentWallex-Signature` 헤더로 전송됩니다.

### 검증 예시

<CodeGroup>
  ```typescript TypeScript theme={null}
  import crypto from "crypto";

  function verifyWebhookSignature(
    payload: string,
    signature: string,
    secret: string
  ): boolean {
    const expected = crypto
      .createHmac("sha256", secret)
      .update(payload)
      .digest("hex");
    return crypto.timingSafeEqual(
      Buffer.from(signature),
      Buffer.from(expected)
    );
  }

  // In your webhook handler
  app.post("/webhooks/agentwallex", (req, res) => {
    const signature = req.headers["x-agentwallex-signature"] as string;
    const isValid = verifyWebhookSignature(
      JSON.stringify(req.body),
      signature,
      "whsec_your_signing_secret"
    );

    if (!isValid) {
      return res.status(401).send("Invalid signature");
    }

    // Process the event
    const event = req.body;
    console.log(`Received ${event.type} event`);
    res.status(200).send("OK");
  });
  ```

  ```python Python theme={null}
  import hmac
  import hashlib

  def verify_webhook_signature(payload: bytes, signature: str, secret: str) -> bool:
      expected = hmac.new(
          secret.encode(),
          payload,
          hashlib.sha256
      ).hexdigest()
      return hmac.compare_digest(signature, expected)
  ```
</CodeGroup>

<Warning>
  타이밍 공격을 방지하기 위해 서명을 검증할 때 항상 상수 시간 비교(예: `timingSafeEqual` 또는 `hmac.compare_digest`)를 사용하세요.
</Warning>

## 웹훅 테스트

웹훅 엔드포인트에 테스트 이벤트를 전송합니다:

```bash theme={null}
curl -X POST https://api.agentwallex.com/api/v1/webhooks/whk_abc123/test \
  -H "X-API-Key: awx_your_api_key"
```

## 전달 내역 조회

웹훅의 전달 내역을 확인합니다:

```bash theme={null}
curl -X GET https://api.agentwallex.com/api/v1/webhooks/whk_abc123/deliveries \
  -H "X-API-Key: awx_your_api_key"
```

## 웹훅 관리

```bash theme={null}
# List all webhooks
GET /webhooks

# Get a specific webhook
GET /webhooks/:id

# Update a webhook
PUT /webhooks/:id

# Delete a webhook
DELETE /webhooks/:id
```

## 모범 사례

<Tip>
  5초 이내에 2xx 상태 코드로 웹훅 전달에 응답하세요. 핸들러가 무거운 처리를 수행해야 하는 경우 웹훅을 즉시 승인하고 비동기적으로 처리하세요.
</Tip>

* **항상 서명을 검증하세요** — 이벤트를 처리하기 전에 검증하세요.
* **중복 처리** — 웹훅 전달은 재시도될 수 있습니다. 멱등성을 위해 `id` 필드를 사용하세요.
* **빠르게 200을 반환하세요** — 무거운 처리를 수행하기 전에 수신을 확인하세요.
* **전달 실패 모니터링** — 실패한 전달을 위해 전달 엔드포인트를 확인하세요.
* **특정 이벤트 필터 사용** — 모든 이벤트를 수신하지 말고 필요한 이벤트만 구독하세요.
