jpskill.com
🛠️ 開発・MCP コミュニティ

webhook-processor

支払いプロバイダーやAPIからのWebhookを、署名検証やリトライ処理、エラーキューイングなどの仕組みを使って、安全かつ確実に受信・処理するシステムを構築するSkill。

📜 元の英語説明(参考)

Build and configure webhook processing systems with retry logic, signature verification, and dead letter queues. Use when you need to receive, validate, and reliably process incoming webhooks from payment providers, version control platforms, or third-party APIs. Trigger words: webhook, callback URL, event handler, retry, idempotency, payload processing.

🇯🇵 日本人クリエイター向け解説

一言でいうと

支払いプロバイダーやAPIからのWebhookを、署名検証やリトライ処理、エラーキューイングなどの仕組みを使って、安全かつ確実に受信・処理するシステムを構築するSkill。

※ jpskill.com 編集部が日本のビジネス現場向けに補足した解説です。Skill本体の挙動とは独立した参考情報です。

⚡ おすすめ: コマンド1行でインストール(60秒)

下記のコマンドをコピーしてターミナル(Mac/Linux)または PowerShell(Windows)に貼り付けてください。 ダウンロード → 解凍 → 配置まで全自動。

🍎 Mac / 🐧 Linux
mkdir -p ~/.claude/skills && cd ~/.claude/skills && curl -L -o webhook-processor.zip https://jpskill.com/download/15560.zip && unzip -o webhook-processor.zip && rm webhook-processor.zip
🪟 Windows (PowerShell)
$d = "$env:USERPROFILE\.claude\skills"; ni -Force -ItemType Directory $d | Out-Null; iwr https://jpskill.com/download/15560.zip -OutFile "$d\webhook-processor.zip"; Expand-Archive "$d\webhook-processor.zip" -DestinationPath $d -Force; ri "$d\webhook-processor.zip"

完了後、Claude Code を再起動 → 普通に「動画プロンプト作って」のように話しかけるだけで自動発動します。

💾 手動でダウンロードしたい(コマンドが難しい人向け)
  1. 1. 下の青いボタンを押して webhook-processor.zip をダウンロード
  2. 2. ZIPファイルをダブルクリックで解凍 → webhook-processor フォルダができる
  3. 3. そのフォルダを C:\Users\あなたの名前\.claude\skills\(Win)または ~/.claude/skills/(Mac)へ移動
  4. 4. Claude Code を再起動

⚠️ ダウンロード・利用は自己責任でお願いします。当サイトは内容・動作・安全性について責任を負いません。

🎯 このSkillでできること

下記の説明文を読むと、このSkillがあなたに何をしてくれるかが分かります。Claudeにこの分野の依頼をすると、自動で発動します。

📦 インストール方法 (3ステップ)

  1. 1. 上の「ダウンロード」ボタンを押して .skill ファイルを取得
  2. 2. ファイル名の拡張子を .skill から .zip に変えて展開(macは自動展開可)
  3. 3. 展開してできたフォルダを、ホームフォルダの .claude/skills/ に置く
    • · macOS / Linux: ~/.claude/skills/
    • · Windows: %USERPROFILE%\.claude\skills\

Claude Code を再起動すれば完了。「このSkillを使って…」と話しかけなくても、関連する依頼で自動的に呼び出されます。

詳しい使い方ガイドを見る →
最終更新
2026-05-18
取得日時
2026-05-18
同梱ファイル
1

📖 Skill本文(日本語訳)

※ 原文(英語/中国語)を Gemini で日本語化したものです。Claude 自身は原文を読みます。誤訳がある場合は原文をご確認ください。

Webhookプロセッサ

概要

このスキルは、受信HTTPコールバックを受け入れ、その信頼性を検証し、指数バックオフ再試行とデッドレターキューを使用して確実に処理する、本番環境グレードのwebhook取り込みエンドポイントを構築するのに役立ちます。署名検証、べき等キー、およびグレースフルなエラー処理について説明します。

手順

1. webhookエンドポイントの作成

POSTリクエストを受け入れるHTTPエンドポイントを作成します。処理を行う前に、すぐに200ステータスを返します。webhook送信者は迅速な応答を期待します。

// webhook-receiver.ts
import express from "express";
import crypto from "crypto";
import { Queue } from "bullmq";

const app = express();
app.use(express.raw({ type: "application/json" }));

const webhookQueue = new Queue("webhooks", {
  connection: { host: "localhost", port: 6379 },
});

app.post("/webhooks/:source", async (req, res) => {
  const signature = req.headers["x-signature-256"] as string;
  const idempotencyKey =
    req.headers["x-idempotency-key"] ||
    crypto.createHash("sha256").update(req.body).digest("hex");

  await webhookQueue.add(
    "process",
    {
      source: req.params.source,
      payload: req.body.toString(),
      signature,
      idempotencyKey,
      receivedAt: new Date().toISOString(),
    },
    {
      jobId: String(idempotencyKey),
      attempts: 5,
      backoff: { type: "exponential", delay: 3000 },
    }
  );

  res.status(200).json({ received: true });
});

2. webhook署名の検証

処理を行う前に、必ず署名を検証してください。各プロバイダーは異なるスキームを使用します。

function verifySignature(
  payload: string,
  signature: string,
  secret: string,
  scheme: "hmac-sha256" | "hmac-sha1"
): boolean {
  const algo = scheme === "hmac-sha256" ? "sha256" : "sha1";
  const expected = crypto
    .createHmac(algo, secret)
    .update(payload, "utf8")
    .digest("hex");
  const prefix = scheme === "hmac-sha256" ? "sha256=" : "sha1=";
  return crypto.timingSafeEqual(
    Buffer.from(prefix + expected),
    Buffer.from(signature)
  );
}

3. 再試行ロジックを持つワーカーの実装

キューからジョブを処理します。失敗したジョブは、指数バックオフで再試行されます。すべての再試行が完了したら、デッドレターキューに移動します。

import { Worker } from "bullmq";

const worker = new Worker(
  "webhooks",
  async (job) => {
    const { source, payload, signature } = job.data;
    const secret = getSecretForSource(source);
    if (!verifySignature(payload, signature, secret, "hmac-sha256")) {
      throw new Error("Invalid webhook signature — will not retry");
    }
    const event = JSON.parse(payload);
    await routeEvent(source, event);
  },
  {
    connection: { host: "localhost", port: 6379 },
    limiter: { max: 50, duration: 1000 },
  }
);

worker.on("failed", (job, err) => {
  if (job && job.attemptsMade >= 5) {
    console.error(`Dead letter: job ${job.id} — ${err.message}`);
    // Move to dead letter queue for manual inspection
  }
});

4. べき等性の追跡の追加

重複排除ストアを使用して、二重処理を防ぎます。

import Redis from "ioredis";
const redis = new Redis();

async function isProcessed(key: string): Promise<boolean> {
  const result = await redis.set(key, "1", "EX", 86400, "NX");
  return result === null; // null means key already existed
}

例1:決済プロバイダーのwebhook

プロンプト: 「決済イベントを受信するwebhookエンドポイントをセットアップします。HMAC-SHA256署名を検証し、失敗した処理を指数バックオフで最大5回まで再試行し、デッドレターイベントをログに記録する必要があります。」

エージェントの出力:

  • プロバイダーの署名シークレットを使用して署名検証を行う src/webhooks/payment-handler.ts を作成します
  • BullMQ再試行設定(5回の試行、3秒/9秒/27秒/81秒/243秒のバックオフ)で src/workers/payment-worker.ts を作成します
  • 失敗したイベントを dead_letters データベーステーブルに格納する src/utils/dead-letter.ts を作成します
  • 無効な署名をシミュレートし、拒否を検証する統合テストを追加します

例2:バージョン管理プラットフォームのwebhook

プロンプト: 「CIビルドをトリガーするリポジトリプッシュイベント用のwebhookハンドラーを構築します。重複配信が重複ビルドを開始しないように、べき等性を含めます。」

エージェントの出力:

  • イベントタイプを検証し、コミットSHAを抽出する src/webhooks/repo-handler.ts を作成します
  • コミットSHAをべき等性キーとして使用します。同じコミットが2つのビルドをトリガーすることはありません
  • 新しいコミットに対してのみビルドジョブをキューに入れる src/workers/build-trigger.ts を作成します
  • 24時間のTTLを持つRedisベースの重複排除チェックを追加します

ガイドライン

  • 常にすぐに200を返す — 非同期的に処理します。Webhook送信者は5〜30秒後にタイムアウトし、再試行して重複が発生します。
  • タイミング攻撃を防ぐために、署名比較にはcrypto.timingSafeEqualを使用します。
  • べき等性キーのTTLを少なくとも24時間に設定します。ほとんどのプロバイダーは最大72時間再試行します。
  • デッドレターキューを監視します。しきい値を超えて増加した場合は、アラートを設定します。
  • 処理を行う前に生のペイロードをログに記録します。これは、不正な形式のイベントをデバッグするのに非常に役立ちます。
  • webhookストーム中にダウンストリームサービスが過負荷にならないように、ワーカーのレート制限を行います。
  • スキーマの変更を適切に処理します。webhookペイロードは進化します。オプションのチェーンを使用し、必須フィールドを明示的に検証します。
📜 原文 SKILL.md(Claudeが読む英語/中国語)を展開

Webhook Processor

Overview

This skill helps you build production-grade webhook ingestion endpoints that accept incoming HTTP callbacks, verify their authenticity, and process them reliably with exponential backoff retries and dead letter queues. It covers signature validation, idempotency keys, and graceful failure handling.

Instructions

1. Scaffold the webhook endpoint

Create an HTTP endpoint that accepts POST requests. Immediately return a 200 status before processing — webhook senders expect fast acknowledgment.

// webhook-receiver.ts
import express from "express";
import crypto from "crypto";
import { Queue } from "bullmq";

const app = express();
app.use(express.raw({ type: "application/json" }));

const webhookQueue = new Queue("webhooks", {
  connection: { host: "localhost", port: 6379 },
});

app.post("/webhooks/:source", async (req, res) => {
  const signature = req.headers["x-signature-256"] as string;
  const idempotencyKey =
    req.headers["x-idempotency-key"] ||
    crypto.createHash("sha256").update(req.body).digest("hex");

  await webhookQueue.add(
    "process",
    {
      source: req.params.source,
      payload: req.body.toString(),
      signature,
      idempotencyKey,
      receivedAt: new Date().toISOString(),
    },
    {
      jobId: String(idempotencyKey),
      attempts: 5,
      backoff: { type: "exponential", delay: 3000 },
    }
  );

  res.status(200).json({ received: true });
});

2. Verify webhook signatures

Always validate the signature before processing. Each provider uses different schemes:

function verifySignature(
  payload: string,
  signature: string,
  secret: string,
  scheme: "hmac-sha256" | "hmac-sha1"
): boolean {
  const algo = scheme === "hmac-sha256" ? "sha256" : "sha1";
  const expected = crypto
    .createHmac(algo, secret)
    .update(payload, "utf8")
    .digest("hex");
  const prefix = scheme === "hmac-sha256" ? "sha256=" : "sha1=";
  return crypto.timingSafeEqual(
    Buffer.from(prefix + expected),
    Buffer.from(signature)
  );
}

3. Implement the worker with retry logic

Process jobs from the queue. Failed jobs retry with exponential backoff. After all retries exhaust, move to a dead letter queue.

import { Worker } from "bullmq";

const worker = new Worker(
  "webhooks",
  async (job) => {
    const { source, payload, signature } = job.data;
    const secret = getSecretForSource(source);
    if (!verifySignature(payload, signature, secret, "hmac-sha256")) {
      throw new Error("Invalid webhook signature — will not retry");
    }
    const event = JSON.parse(payload);
    await routeEvent(source, event);
  },
  {
    connection: { host: "localhost", port: 6379 },
    limiter: { max: 50, duration: 1000 },
  }
);

worker.on("failed", (job, err) => {
  if (job && job.attemptsMade >= 5) {
    console.error(`Dead letter: job ${job.id} — ${err.message}`);
    // Move to dead letter queue for manual inspection
  }
});

4. Add idempotency tracking

Prevent double-processing with a deduplication store:

import Redis from "ioredis";
const redis = new Redis();

async function isProcessed(key: string): Promise<boolean> {
  const result = await redis.set(key, "1", "EX", 86400, "NX");
  return result === null; // null means key already existed
}

Examples

Example 1: Payment provider webhook

Prompt: "Set up a webhook endpoint to receive payment events. It should verify HMAC-SHA256 signatures, retry failed processing up to 5 times with exponential backoff, and log dead letter events."

Agent output:

  • Creates src/webhooks/payment-handler.ts with signature verification using the provider's signing secret
  • Creates src/workers/payment-worker.ts with BullMQ retry config (5 attempts, 3s/9s/27s/81s/243s backoff)
  • Creates src/utils/dead-letter.ts that stores failed events in a dead_letters database table
  • Adds integration test that simulates an invalid signature and verifies rejection

Example 2: Version control platform webhook

Prompt: "Build a webhook handler for repository push events that triggers CI builds. Include idempotency so duplicate deliveries don't start duplicate builds."

Agent output:

  • Creates src/webhooks/repo-handler.ts that validates the event type and extracts commit SHA
  • Uses the commit SHA as the idempotency key — same commit never triggers two builds
  • Creates src/workers/build-trigger.ts that enqueues build jobs only for new commits
  • Adds a Redis-backed deduplication check with 24-hour TTL

Guidelines

  • Always return 200 immediately — process asynchronously. Webhook senders timeout after 5-30 seconds and will retry, causing duplicates.
  • Use crypto.timingSafeEqual for signature comparison to prevent timing attacks.
  • Set idempotency key TTL to at least 24 hours — most providers retry for up to 72 hours.
  • Monitor your dead letter queue — set up alerts when it grows beyond a threshold.
  • Log the raw payload before processing — invaluable for debugging malformed events.
  • Rate limit your worker to avoid overwhelming downstream services during webhook storms.
  • Handle schema changes gracefully — webhook payloads evolve. Use optional chaining and validate required fields explicitly.