Webhook

CheckoutOSからのリアルタイムのイベント通知

最終更新日:2025-01-16

Webhookを使うと、CheckoutOSでイベントが発生した際にリアルタイムの通知を受け取れます。APIを定期的に問い合わせる代わりに、イベントの発生時にWebhookがサーバーへデータを送信します。

利用できるイベント

Webhookイベント

  • upsell.accepted — 顧客がアップセルのオファーを承諾
  • upsell.declined — 顧客がアップセルのオファーを辞退
  • bundle.purchased — バンドルを購入
  • experiment.concluded — A/Bテストが統計的有意性に到達
  • order.edited — 顧客が注文を変更
  • order.cancelled — 顧客が注文をキャンセル
  • subscription.created — 定期購入のアップセルが転換

Webhookの作成

1

Webhookを開く

CheckoutOS → Settings → Webhooksに進みます。
2

エンドポイントを追加する

"Add Webhook Endpoint"をクリックします。
3

URLを入力する

イベントを受信するHTTPS URLを入力します。
4

イベントを選ぶ

購読するイベントを選択します。
5

保存する

保存して署名シークレットを控えます。
APIからWebhookを作成
curl -X POST "https://api.chargezen.com/v1/webhooks" \
  -H "Authorization: Bearer YOUR_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "url": "https://yourserver.com/webhooks/checkoutos",
    "events": ["upsell.accepted", "bundle.purchased"],
    "enabled": true
  }'

# Response
{
  "id": "wh_123",
  "url": "https://yourserver.com/webhooks/checkoutos",
  "events": ["upsell.accepted", "bundle.purchased"],
  "signing_secret": "whsec_abc123...",
  "enabled": true
}

Webhookのペイロード

upsell.accepted

アップセル承諾イベント
{
  "id": "evt_123456",
  "type": "upsell.accepted",
  "created_at": "2025-01-16T14:30:00Z",
  "data": {
    "upsell_id": "upsell_abc",
    "upsell_name": "Premium Add-On",
    "order_id": "order_789",
    "shopify_order_id": "5678901234",
    "customer_id": "cust_456",
    "product": {
      "id": "prod_xyz",
      "title": "Premium Widget",
      "variant_id": "var_123",
      "price": 29.99
    },
    "discount": {
      "type": "percentage",
      "value": 15,
      "amount": 4.50
    },
    "final_price": 25.49
  }
}

bundle.purchased

バンドル購入イベント
{
  "id": "evt_234567",
  "type": "bundle.purchased",
  "created_at": "2025-01-16T15:00:00Z",
  "data": {
    "bundle_id": "bundle_def",
    "bundle_name": "Skincare Starter Kit",
    "bundle_type": "fixed",
    "order_id": "order_890",
    "products": [
      { "id": "prod_a", "title": "Cleanser", "quantity": 1 },
      { "id": "prod_b", "title": "Toner", "quantity": 1 },
      { "id": "prod_c", "title": "Moisturizer", "quantity": 1 }
    ],
    "original_price": 89.97,
    "bundle_price": 71.98,
    "savings": 17.99
  }
}

order.edited

注文変更イベント
{
  "id": "evt_345678",
  "type": "order.edited",
  "created_at": "2025-01-16T15:30:00Z",
  "data": {
    "order_id": "order_901",
    "shopify_order_id": "6789012345",
    "edit_type": "add_items",
    "changes": {
      "items_added": [
        { "product_id": "prod_new", "quantity": 1, "price": 19.99 }
      ],
      "items_removed": [],
      "quantity_changes": []
    },
    "amount_changed": 19.99,
    "new_total": 109.98
  }
}

Webhookの検証

すべてのWebhookには、検証用の署名ヘッダーが含まれます。

Node.jsでの検証
const crypto = require('crypto');

function verifyWebhook(payload, signature, secret) {
  const expectedSignature = crypto
    .createHmac('sha256', secret)
    .update(payload, 'utf8')
    .digest('hex');

  return crypto.timingSafeEqual(
    Buffer.from(signature),
    Buffer.from(`sha256=${expectedSignature}`)
  );
}

// Express middleware
app.post('/webhooks/checkoutos', express.raw({ type: 'application/json' }), (req, res) => {
  const signature = req.headers['x-checkoutos-signature'];

  if (!verifyWebhook(req.body, signature, process.env.WEBHOOK_SECRET)) {
    return res.status(401).send('Invalid signature');
  }

  const event = JSON.parse(req.body);
  // Handle event...

  res.status(200).send('OK');
});
Pythonでの検証
import hmac
import hashlib

def verify_webhook(payload: bytes, signature: str, secret: str) -> bool:
    expected = hmac.new(
        secret.encode('utf-8'),
        payload,
        hashlib.sha256
    ).hexdigest()

    return hmac.compare_digest(
        f'sha256={expected}',
        signature
    )

# Flask example
@app.route('/webhooks/checkoutos', methods=['POST'])
def handle_webhook():
    signature = request.headers.get('X-CheckoutOS-Signature')

    if not verify_webhook(request.data, signature, WEBHOOK_SECRET):
        return 'Invalid signature', 401

    event = request.get_json()
    # Handle event...

    return 'OK', 200
必ず検証する

処理する前に、必ずWebhookの署名を検証してください。これにより、攻撃者が偽のイベントをエンドポイントに送信することを防ぎます。

再試行ポリシー

Webhookの配信に失敗した場合は、待機時間を指数関数的に延ばして再試行します。

再試行スケジュール
{
  "retry_policy": {
    "max_attempts": 5,
    "schedule": [
      { "attempt": 1, "delay": "immediately" },
      { "attempt": 2, "delay": "5 minutes" },
      { "attempt": 3, "delay": "30 minutes" },
      { "attempt": 4, "delay": "2 hours" },
      { "attempt": 5, "delay": "24 hours" }
    ],
    "success_codes": [200, 201, 202, 204],
    "timeout": "30 seconds"
  }
}

Webhookのテスト

本番で使用する前に、Webhookエンドポイントをテストしてください。

テストイベントを送信
curl -X POST "https://api.chargezen.com/v1/webhooks/wh_123/test" \
  -H "Authorization: Bearer YOUR_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "event_type": "upsell.accepted"
  }'

Webhookログ

ダッシュボードまたはAPIでWebhookの配信履歴を確認します。

Webhookログの取得
curl -X GET "https://api.chargezen.com/v1/webhooks/wh_123/logs" \
  -H "Authorization: Bearer YOUR_API_KEY"

# Response
{
  "data": [
    {
      "id": "log_123",
      "event_id": "evt_456",
      "event_type": "upsell.accepted",
      "status": "delivered",
      "response_code": 200,
      "duration_ms": 245,
      "created_at": "2025-01-16T14:30:00Z"
    }
  ]
}

効果的な使い方

Webhookのヒント
  • すぐに応答する — 30秒以内に200を返してください
  • 非同期で処理する — バックグラウンド処理用にイベントをキューに入れてください
  • 重複に対応する — イベントは複数回配信される場合があります
  • 署名を検証する — 処理前に必ず検証してください
  • 失敗を監視する — 配信失敗のアラートを設定してください

関連トピック

このページは役に立ちましたか?

さらにサポートが必要ですか? サポートに問い合わせる