SCALE — Build Lab

Webhook 受信エンドポイント

推奨 API連携

外部サービス(Stripe / GitHub / Slack 等)のイベント受信枠を標準装備。

なぜ必要?

Webhook 無いと「相手のイベント」を取れず、Polling で疲弊する。

どう実装する?

/api/webhooks/<provider> で署名検証 + 冪等性キーで重複処理防止。

コード例
ts
// 署名検証(Stripe例)
import Stripe from 'stripe';
const stripe = new Stripe(process.env.STRIPE_SECRET_KEY!);

export async function POST(req: Request) {
  const sig = req.headers.get('stripe-signature')!;
  const body = await req.text();
  const event = stripe.webhooks.constructEvent(body, sig, process.env.STRIPE_WEBHOOK_SECRET!);
  // 冪等性: event.id を DB に記録、既存ならスキップ
  if (await alreadyProcessed(event.id)) return new Response('OK');
  // 処理...
  return new Response('OK');
}

Webhook 受信エンドポイント

:LiTarget: 何のために?

Webhook 無いと「相手のイベント」を取れず、Polling で疲弊する。

:LiSparkle: どう実装する?

/api/webhooks/ で署名検証 + 冪等性キーで重複処理防止。

:LiCode: コード例

// 署名検証(Stripe例)
import Stripe from 'stripe';
const stripe = new Stripe(process.env.STRIPE_SECRET_KEY!);

export async function POST(req: Request) {
  const sig = req.headers.get('stripe-signature')!;
  const body = await req.text();
  const event = stripe.webhooks.constructEvent(body, sig, process.env.STRIPE_WEBHOOK_SECRET!);
  // 冪等性: event.id を DB に記録、既存ならスキップ
  if (await alreadyProcessed(event.id)) return new Response('OK');
  // 処理...
  return new Response('OK');
}