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

# Webhook

> 支払い、ポリシー違反、エージェントイベントのリアルタイム通知を受信します。

## 概要

Webhookは、HTTP POSTリクエストを通じてアプリケーションにリアルタイムイベント通知を配信します。支払い、ポリシー違反、エージェントステータスの変更、x402セッションイベントに対応するために使用します。

## Webhookの設定

### 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`   | 高額トランザクションが人間の承認を待っています      |

## Webhookペイロード

すべてのWebhook配信には、この構造の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"
  }
}
```

## 署名検証

すべてのWebhook配信には検証用の署名ヘッダーが含まれます。Webhookイベントを処理する前に必ず署名を検証してください。

### 仕組み

AgentWallexは、登録時に提供されたシークレットを使用して各Webhookペイロードに署名します。署名は`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>

## Webhookのテスト

Webhookエンドポイントにテストイベントを送信します：

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

## 配信履歴の表示

Webhookの配信履歴を確認します：

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

## Webhookの管理

```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>
  Webhook配信には5秒以内に2xxステータスコードで応答してください。ハンドラーで重い処理が必要な場合は、Webhookを即座に確認してから非同期で処理してください。
</Tip>

* **常に署名を検証する** — イベントを処理する前に必ず検証してください。
* **重複を処理する** — Webhook配信はリトライされる場合があります。冪等性のために`id`フィールドを使用してください。
* **200を素早く返す** — 重い処理を行う前に受信を確認してください。
* **配信失敗を監視する** — 配信エンドポイントで失敗した配信を確認してください。
* **特定のイベントフィルターを使用する** — すべてのイベントを受信するのではなく、必要なイベントのみを購読してください。
