[{"data":1,"prerenderedAt":-1},["ShallowReactive",2],{"skill:01M6EZPHX8K6G19F1PWW439WKT":3,"skill-same:01M6EZPHX8K6G19F1PWW439WKT":93},{"skillNo":4,"name":5,"nameZh":6,"description":7,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":16,"categories":17,"keywords":18,"publishedAt":39,"linkOnly":40,"markdownContent":41,"markdownBody":42,"frontMatter":43,"refName":53,"commitSha":54,"skillDirectory":55,"forksCount":56,"repositoryHtmlUrl":57,"repositoryHomepageUrl":6,"ownerHtmlUrl":58,"ownerBlogUrl":6,"ownerDescription":59,"updatedAt":60,"install":61,"resources":74},"01M6EZPHX8K6G19F1PWW439WKT","webhook-integration-patterns",null,"Designs reliable webhook systems with proper delivery guarantees, retry logic, signature verification, and idempotent processing for event-driven integrations.","luokai0\u002Fai-agent-skills-by-luo-kai","luokai0","https:\u002F\u002Favatars.githubusercontent.com\u002Fu\u002F266954973?v=4","01M6E16VNT42JB8B3X3254QWJ7","luo kai","01M6E16VTFVP6S5XJF1V1MPV90",14,"MIT","https:\u002F\u002Fgithub.com\u002Fluokai0\u002Fai-agent-skills-by-luo-kai\u002Fblob\u002Fmain\u002Fai-agent-skills\u002F21-external-registries\u002F18-organvm-skills\u002Fintegrations\u002Fwebhook-integration-patterns\u002FSKILL.md",[],[19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38],"webhook","webhook integration patterns","webhook integration","patterns","integration","webhooks","build","user","delivery","logic","systems","verification","iii","processing","integrations","event-driven","event","about","with","retry","2026-11-10 10:12:30",false,"---\nname: webhook-integration-patterns\ndescription: Designs reliable webhook systems with proper delivery guarantees, retry logic, signature verification, and idempotent processing for event-driven integrations.\nlicense: MIT\ngovernance_phases: [build]\norgan_affinity: [organ-iii, organ-iv, organ-vii]\ntriggers: [user-asks-about-webhooks, user-asks-about-event-driven, context:integration]\n---\n\n# Webhook Integration Patterns\n\nThis skill provides guidance for designing and implementing robust webhook systems—both as providers (sending webhooks) and consumers (receiving webhooks).\n\n## Core Competencies\n\n- **Delivery Guarantees**: At-least-once, exactly-once semantics\n- **Security**: Signature verification, secret rotation\n- **Reliability**: Retry strategies, dead letter handling\n- **Scalability**: Queue-based processing, rate limiting\n\n## Webhook Fundamentals\n\n### What Webhooks Solve\n\n```\nPolling (inefficient):           Webhooks (efficient):\n┌────────┐     ┌────────┐       ┌────────┐     ┌────────┐\n│ Client │     │ Server │       │ Client │     │ Server │\n└───┬────┘     └───┬────┘       └───┬────┘     └───┬────┘\n    │ Any news?    │                │              │\n    │─────────────▶│                │              │\n    │    No        │                │   Event!     │\n    │◀─────────────│                │◀─────────────│\n    │ Any news?    │                │  POST \u002Fhook  │\n    │─────────────▶│                │◀─────────────│\n    │    No        │                │   200 OK     │\n    │◀─────────────│                │─────────────▶│\n    │ Any news?    │\n    │─────────────▶│       Push-based notification\n    │    YES!      │       instead of polling\n    │◀─────────────│\n```\n\n### Webhook Anatomy\n\n```http\nPOST \u002Fwebhooks\u002Fpayment HTTP\u002F1.1\nHost: your-app.com\nContent-Type: application\u002Fjson\nX-Webhook-Signature: sha256=abc123...\nX-Webhook-ID: evt_12345\nX-Webhook-Timestamp: 1706616000\n\n{\n  \"id\": \"evt_12345\",\n  \"type\": \"payment.completed\",\n  \"created_at\": \"2024-01-30T12:00:00Z\",\n  \"data\": {\n    \"payment_id\": \"pay_abc\",\n    \"amount\": 1000,\n    \"currency\": \"USD\"\n  }\n}\n```\n\nKey headers:\n- **Signature**: Cryptographic proof of authenticity\n- **ID**: Unique event identifier for deduplication\n- **Timestamp**: When the event occurred\n\n## Webhook Provider Design\n\n### Event Schema Design\n\n```python\nclass WebhookEvent:\n    \"\"\"Standard webhook event structure\"\"\"\n\n    def __init__(self, event_type, data, idempotency_key=None):\n        self.id = self._generate_id()\n        self.type = event_type\n        self.created_at = datetime.utcnow().isoformat()\n        self.api_version = \"2024-01-30\"\n        self.data = data\n        self.idempotency_key = idempotency_key or self.id\n\n    def to_payload(self):\n        return {\n            \"id\": self.id,\n            \"type\": self.type,\n            \"created_at\": self.created_at,\n            \"api_version\": self.api_version,\n            \"data\": self.data\n        }\n\n# Event types follow resource.action pattern\nEVENT_TYPES = [\n    \"payment.created\",\n    \"payment.completed\",\n    \"payment.failed\",\n    \"subscription.created\",\n    \"subscription.updated\",\n    \"subscription.cancelled\",\n    \"customer.created\",\n    \"customer.deleted\"\n]\n```\n\n### Signature Generation\n\n```python\nimport hmac\nimport hashlib\nimport time\n\nclass WebhookSigner:\n    \"\"\"Sign webhook payloads for verification\"\"\"\n\n    def __init__(self, secret):  # allow-secret\n        self.secret = secret.encode()  # allow-secret\n\n    def sign(self, payload, timestamp=None):\n        \"\"\"Generate HMAC signature\"\"\"\n        timestamp = timestamp or int(time.time())\n        payload_str = json.dumps(payload, separators=(',', ':'))\n\n        # Include timestamp to prevent replay attacks\n        signed_payload = f\"{timestamp}.{payload_str}\"\n\n        signature = hmac.new(\n            self.secret,\n            signed_payload.encode(),\n            hashlib.sha256\n        ).hexdigest()\n\n        return {\n            'signature': f\"sha256={signature}\",\n            'timestamp': timestamp\n        }\n\n    def create_headers(self, payload):\n        \"\"\"Generate all webhook headers\"\"\"\n        sign_data = self.sign(payload)\n        return {\n            'Content-Type': 'application\u002Fjson',\n            'X-Webhook-Signature': sign_data['signature'],\n            'X-Webhook-Timestamp': str(sign_data['timestamp']),\n            'X-Webhook-ID': payload['id']\n        }\n```\n\n### Delivery System\n\n```python\nimport asyncio\nfrom datetime import datetime, timedelta\n\nclass WebhookDeliverySystem:\n    \"\"\"Reliable webhook delivery with retries\"\"\"\n\n    RETRY_SCHEDULE = [\n        timedelta(seconds=10),\n        timedelta(minutes=1),\n        timedelta(minutes=5),\n        timedelta(minutes=30),\n        timedelta(hours=1),\n        timedelta(hours=6),\n        timedelta(hours=24)\n    ]\n\n    def __init__(self, signer, http_client):\n        self.signer = signer\n        self.http = http_client\n        self.delivery_log = []\n\n    async def deliver(self, endpoint, event, attempt=0):\n        \"\"\"Attempt webhook delivery\"\"\"\n        payload = event.to_payload()\n        headers = self.signer.create_headers(payload)\n\n        try:\n            response = await self.http.post(\n                endpoint.url,\n                json=payload,\n                headers=headers,\n                timeout=30\n            )\n\n            self._log_attempt(endpoint, event, attempt, response)\n\n            if response.status_code in (200, 201, 202, 204):\n                return {'status': 'delivered', 'attempts': attempt + 1}\n\n            # Non-success status - schedule retry\n            return await self._schedule_retry(endpoint, event, attempt)\n\n        except Exception as e:\n            self._log_attempt(endpoint, event, attempt, error=e)\n            return await self._schedule_retry(endpoint, event, attempt)\n\n    async def _schedule_retry(self, endpoint, event, attempt):\n        \"\"\"Schedule next retry or give up\"\"\"\n        if attempt >= len(self.RETRY_SCHEDULE):\n            self._move_to_dead_letter(endpoint, event)\n            return {'status': 'failed', 'attempts': attempt + 1}\n\n        delay = self.RETRY_SCHEDULE[attempt]\n        # In production: use job queue with delayed execution\n        await asyncio.sleep(delay.total_seconds())\n        return await self.deliver(endpoint, event, attempt + 1)\n\n    def _move_to_dead_letter(self, endpoint, event):\n        \"\"\"Store failed webhook for manual review\"\"\"\n        # Store in dead letter queue\u002Ftable\n        pass\n```\n\n### Endpoint Management\n\n```python\nclass WebhookEndpoint:\n    \"\"\"Subscriber endpoint configuration\"\"\"\n\n    def __init__(self, url, events, secret=None):  # allow-secret\n        self.id = generate_id()\n        self.url = url\n        self.events = events  # List of subscribed event types\n        self.secret = secret or generate_secret()  # allow-secret\n        self.status = 'active'\n        self.created_at = datetime.utcnow()\n\n        # Health tracking\n        self.consecutive_failures = 0\n        self.last_success = None\n        self.last_failure = None\n\n    def should_receive(self, event_type):\n        \"\"\"Check if endpoint subscribes to this event\"\"\"\n        if '*' in self.events:\n            return True\n        return event_type in self.events\n\n    def record_success(self):\n        self.consecutive_failures = 0\n        self.last_success = datetime.utcnow()\n        if self.status == 'disabled':\n            self.status = 'active'\n\n    def record_failure(self):\n        self.consecutive_failures += 1\n        self.last_failure = datetime.utcnow()\n\n        # Auto-disable after too many failures\n        if self.consecutive_failures >= 10:\n            self.status = 'disabled'\n```\n\n## Webhook Consumer Design\n\n### Signature Verification\n\n```python\nclass WebhookVerifier:\n    \"\"\"Verify incoming webhook signatures\"\"\"\n\n    TIMESTAMP_TOLERANCE = 300  # 5 minutes\n\n    def __init__(self, secret):  # allow-secret\n        self.secret = secret.encode()  # allow-secret\n\n    def verify(self, payload, signature, timestamp):\n        \"\"\"Verify webhook authenticity\"\"\"\n        # Check timestamp freshness\n        current_time = int(time.time())\n        if abs(current_time - int(timestamp)) > self.TIMESTAMP_TOLERANCE:\n            raise WebhookVerificationError(\"Timestamp too old\")\n\n        # Compute expected signature\n        signed_payload = f\"{timestamp}.{payload}\"\n        expected = hmac.new(\n            self.secret,\n            signed_payload.encode(),\n            hashlib.sha256\n        ).hexdigest()\n\n        expected_sig = f\"sha256={expected}\"\n\n        # Constant-time comparison to prevent timing attacks\n        if not hmac.compare_digest(signature, expected_sig):\n            raise WebhookVerificationError(\"Invalid signature\")\n\n        return True\n\n\n# Flask endpoint example\n@app.route('\u002Fwebhooks\u002Fprovider', methods=['POST'])\ndef handle_webhook():\n    verifier = WebhookVerifier(WEBHOOK_SECRET)\n\n    try:\n        verifier.verify(\n            request.data.decode(),\n            request.headers.get('X-Webhook-Signature'),\n            request.headers.get('X-Webhook-Timestamp')\n        )\n    except WebhookVerificationError:\n        return 'Invalid signature', 401\n\n    event = request.json\n    process_webhook(event)\n\n    return 'OK', 200\n```\n\n### Idempotent Processing\n\n```python\nclass IdempotentWebhookProcessor:\n    \"\"\"Process webhooks exactly once\"\"\"\n\n    def __init__(self, storage):\n        self.storage = storage  # Redis, database, etc.\n        self.lock_ttl = 300  # 5 minute lock\n\n    async def process(self, event):\n        \"\"\"Process webhook idempotently\"\"\"\n        event_id = event['id']\n\n        # Check if already processed\n        if await self.storage.exists(f\"webhook:processed:{event_id}\"):\n            return {'status': 'duplicate', 'event_id': event_id}\n\n        # Acquire lock to prevent concurrent processing\n        lock_key = f\"webhook:lock:{event_id}\"\n        if not await self.storage.set_nx(lock_key, \"1\", ex=self.lock_ttl):\n            return {'status': 'processing', 'event_id': event_id}\n\n        try:\n            # Process the event\n            result = await self._handle_event(event)\n\n            # Mark as processed (with long TTL for deduplication)\n            await self.storage.set(\n                f\"webhook:processed:{event_id}\",\n                json.dumps(result),\n                ex=86400 * 7  # Keep for 7 days\n            )\n\n            return {'status': 'processed', 'event_id': event_id}\n\n        finally:\n            await self.storage.delete(lock_key)\n\n    async def _handle_event(self, event):\n        \"\"\"Route event to appropriate handler\"\"\"\n        handlers = {\n            'payment.completed': self._handle_payment_completed,\n            'subscription.cancelled': self._handle_subscription_cancelled,\n            # ... more handlers\n        }\n        handler = handlers.get(event['type'])\n        if handler:\n            return await handler(event['data'])\n        return {'skipped': True, 'reason': 'unknown_event_type'}\n```\n\n### Queue-Based Processing\n\n```python\nclass QueuedWebhookHandler:\n    \"\"\"Decouple receipt from processing\"\"\"\n\n    def __init__(self, queue):\n        self.queue = queue  # Redis, SQS, RabbitMQ, etc.\n\n    async def receive(self, event):\n        \"\"\"Acknowledge receipt quickly, process async\"\"\"\n        # Validate immediately\n        self._validate_event_structure(event)\n\n        # Queue for processing\n        await self.queue.enqueue(\n            'webhook_processing',\n            event,\n            deduplication_id=event['id']\n        )\n\n        # Return 200 immediately (don't make sender wait)\n        return {'status': 'accepted'}\n\n    async def process_queue(self):\n        \"\"\"Worker that processes queued webhooks\"\"\"\n        while True:\n            event = await self.queue.dequeue('webhook_processing')\n            if event:\n                try:\n                    await self._process_event(event)\n                    await self.queue.ack(event)\n                except Exception as e:\n                    await self.queue.nack(event, requeue=True)\n                    logging.error(f\"Webhook processing failed: {e}\")\n```\n\n## Security Patterns\n\n### Secret Rotation\n\n```python\nclass SecretRotation:\n    \"\"\"Support rolling secret updates\"\"\"\n\n    def __init__(self):\n        self.current_secret = None\n        self.previous_secret = None\n        self.rotation_timestamp = None\n\n    def rotate(self, new_secret):\n        \"\"\"Rotate to new secret while supporting old\"\"\"\n        self.previous_secret = self.current_secret\n        self.current_secret = new_secret\n        self.rotation_timestamp = datetime.utcnow()\n\n    def get_verification_secrets(self):\n        \"\"\"Return secrets to try for verification\"\"\"\n        secrets = [self.current_secret]\n\n        # Accept previous secret for grace period\n        if self.previous_secret and self.rotation_timestamp:\n            grace_period = timedelta(hours=24)\n            if datetime.utcnow() - self.rotation_timestamp \u003C grace_period:\n                secrets.append(self.previous_secret)\n\n        return secrets\n```\n\n### IP Allowlisting\n\n```python\nALLOWED_IPS = {\n    'stripe': ['3.18.12.63', '3.130.192.231', ...],\n    'github': ['192.30.252.0\u002F22', '185.199.108.0\u002F22', ...],\n    'twilio': ['54.172.60.0\u002F23', '54.244.51.0\u002F24', ...]\n}\n\ndef verify_source_ip(request, provider):\n    \"\"\"Verify webhook comes from expected IP\"\"\"\n    client_ip = request.remote_addr\n\n    allowed = ALLOWED_IPS.get(provider, [])\n    for allowed_range in allowed:\n        if ip_in_range(client_ip, allowed_range):\n            return True\n\n    return False\n```\n\n## Error Handling\n\n### Response Codes\n\n| Code | Meaning | Provider Action |\n|------|---------|-----------------|\n| 200-204 | Success | Mark delivered |\n| 400 | Bad request | Don't retry (your bug) |\n| 401\u002F403 | Auth failed | Disable endpoint |\n| 404 | Not found | Disable endpoint |\n| 429 | Rate limited | Retry with backoff |\n| 500+ | Server error | Retry |\n| Timeout | No response | Retry |\n\n### Dead Letter Queue\n\n```python\nclass DeadLetterQueue:\n    \"\"\"Store and manage failed webhooks\"\"\"\n\n    async def add(self, endpoint, event, failure_reason, attempts):\n        \"\"\"Add failed webhook to DLQ\"\"\"\n        await self.storage.add({\n            'id': generate_id(),\n            'endpoint_id': endpoint.id,\n            'endpoint_url': endpoint.url,\n            'event': event.to_payload(),\n            'failure_reason': str(failure_reason),\n            'attempts': attempts,\n            'added_at': datetime.utcnow().isoformat()\n        })\n\n    async def retry(self, dlq_item_id):\n        \"\"\"Manually retry a DLQ item\"\"\"\n        item = await self.storage.get(dlq_item_id)\n        endpoint = await self.get_endpoint(item['endpoint_id'])\n        event = WebhookEvent.from_payload(item['event'])\n\n        result = await self.delivery_system.deliver(endpoint, event)\n\n        if result['status'] == 'delivered':\n            await self.storage.remove(dlq_item_id)\n\n        return result\n\n    async def purge_old(self, days=30):\n        \"\"\"Clean up old DLQ items\"\"\"\n        cutoff = datetime.utcnow() - timedelta(days=days)\n        await self.storage.delete_before(cutoff)\n```\n\n## Best Practices\n\n### For Providers\n\n1. **Include event ID** for consumer deduplication\n2. **Sign payloads** with HMAC-SHA256 minimum\n3. **Include timestamps** to prevent replay\n4. **Retry with exponential backoff** (5 attempts minimum)\n5. **Provide webhook logs** in your dashboard\n6. **Support event filtering** by type\n7. **Version your payloads** for backward compatibility\n\n### For Consumers\n\n1. **Verify signatures** before processing\n2. **Respond quickly** (\u003C 5 seconds)\n3. **Process asynchronously** via queue\n4. **Implement idempotency** using event ID\n5. **Log everything** for debugging\n6. **Monitor for failures** proactively\n\n## References\n\n- `references\u002Fwebhook-security.md` - Detailed security implementation\n- `references\u002Fprovider-examples.md` - Stripe, GitHub, Twilio patterns\n- `references\u002Ftesting-webhooks.md` - Local development and testing\n","# Webhook Integration Patterns\n\nThis skill provides guidance for designing and implementing robust webhook systems—both as providers (sending webhooks) and consumers (receiving webhooks).\n\n## Core Competencies\n\n- **Delivery Guarantees**: At-least-once, exactly-once semantics\n- **Security**: Signature verification, secret rotation\n- **Reliability**: Retry strategies, dead letter handling\n- **Scalability**: Queue-based processing, rate limiting\n\n## Webhook Fundamentals\n\n### What Webhooks Solve\n\n```\nPolling (inefficient):           Webhooks (efficient):\n┌────────┐     ┌────────┐       ┌────────┐     ┌────────┐\n│ Client │     │ Server │       │ Client │     │ Server │\n└───┬────┘     └───┬────┘       └───┬────┘     └───┬────┘\n    │ Any news?    │                │              │\n    │─────────────▶│                │              │\n    │    No        │                │   Event!     │\n    │◀─────────────│                │◀─────────────│\n    │ Any news?    │                │  POST \u002Fhook  │\n    │─────────────▶│                │◀─────────────│\n    │    No        │                │   200 OK     │\n    │◀─────────────│                │─────────────▶│\n    │ Any news?    │\n    │─────────────▶│       Push-based notification\n    │    YES!      │       instead of polling\n    │◀─────────────│\n```\n\n### Webhook Anatomy\n\n```http\nPOST \u002Fwebhooks\u002Fpayment HTTP\u002F1.1\nHost: your-app.com\nContent-Type: application\u002Fjson\nX-Webhook-Signature: sha256=abc123...\nX-Webhook-ID: evt_12345\nX-Webhook-Timestamp: 1706616000\n\n{\n  \"id\": \"evt_12345\",\n  \"type\": \"payment.completed\",\n  \"created_at\": \"2024-01-30T12:00:00Z\",\n  \"data\": {\n    \"payment_id\": \"pay_abc\",\n    \"amount\": 1000,\n    \"currency\": \"USD\"\n  }\n}\n```\n\nKey headers:\n- **Signature**: Cryptographic proof of authenticity\n- **ID**: Unique event identifier for deduplication\n- **Timestamp**: When the event occurred\n\n## Webhook Provider Design\n\n### Event Schema Design\n\n```python\nclass WebhookEvent:\n    \"\"\"Standard webhook event structure\"\"\"\n\n    def __init__(self, event_type, data, idempotency_key=None):\n        self.id = self._generate_id()\n        self.type = event_type\n        self.created_at = datetime.utcnow().isoformat()\n        self.api_version = \"2024-01-30\"\n        self.data = data\n        self.idempotency_key = idempotency_key or self.id\n\n    def to_payload(self):\n        return {\n            \"id\": self.id,\n            \"type\": self.type,\n            \"created_at\": self.created_at,\n            \"api_version\": self.api_version,\n            \"data\": self.data\n        }\n\n# Event types follow resource.action pattern\nEVENT_TYPES = [\n    \"payment.created\",\n    \"payment.completed\",\n    \"payment.failed\",\n    \"subscription.created\",\n    \"subscription.updated\",\n    \"subscription.cancelled\",\n    \"customer.created\",\n    \"customer.deleted\"\n]\n```\n\n### Signature Generation\n\n```python\nimport hmac\nimport hashlib\nimport time\n\nclass WebhookSigner:\n    \"\"\"Sign webhook payloads for verification\"\"\"\n\n    def __init__(self, secret):  # allow-secret\n        self.secret = secret.encode()  # allow-secret\n\n    def sign(self, payload, timestamp=None):\n        \"\"\"Generate HMAC signature\"\"\"\n        timestamp = timestamp or int(time.time())\n        payload_str = json.dumps(payload, separators=(',', ':'))\n\n        # Include timestamp to prevent replay attacks\n        signed_payload = f\"{timestamp}.{payload_str}\"\n\n        signature = hmac.new(\n            self.secret,\n            signed_payload.encode(),\n            hashlib.sha256\n        ).hexdigest()\n\n        return {\n            'signature': f\"sha256={signature}\",\n            'timestamp': timestamp\n        }\n\n    def create_headers(self, payload):\n        \"\"\"Generate all webhook headers\"\"\"\n        sign_data = self.sign(payload)\n        return {\n            'Content-Type': 'application\u002Fjson',\n            'X-Webhook-Signature': sign_data['signature'],\n            'X-Webhook-Timestamp': str(sign_data['timestamp']),\n            'X-Webhook-ID': payload['id']\n        }\n```\n\n### Delivery System\n\n```python\nimport asyncio\nfrom datetime import datetime, timedelta\n\nclass WebhookDeliverySystem:\n    \"\"\"Reliable webhook delivery with retries\"\"\"\n\n    RETRY_SCHEDULE = [\n        timedelta(seconds=10),\n        timedelta(minutes=1),\n        timedelta(minutes=5),\n        timedelta(minutes=30),\n        timedelta(hours=1),\n        timedelta(hours=6),\n        timedelta(hours=24)\n    ]\n\n    def __init__(self, signer, http_client):\n        self.signer = signer\n        self.http = http_client\n        self.delivery_log = []\n\n    async def deliver(self, endpoint, event, attempt=0):\n        \"\"\"Attempt webhook delivery\"\"\"\n        payload = event.to_payload()\n        headers = self.signer.create_headers(payload)\n\n        try:\n            response = await self.http.post(\n                endpoint.url,\n                json=payload,\n                headers=headers,\n                timeout=30\n            )\n\n            self._log_attempt(endpoint, event, attempt, response)\n\n            if response.status_code in (200, 201, 202, 204):\n                return {'status': 'delivered', 'attempts': attempt + 1}\n\n            # Non-success status - schedule retry\n            return await self._schedule_retry(endpoint, event, attempt)\n\n        except Exception as e:\n            self._log_attempt(endpoint, event, attempt, error=e)\n            return await self._schedule_retry(endpoint, event, attempt)\n\n    async def _schedule_retry(self, endpoint, event, attempt):\n        \"\"\"Schedule next retry or give up\"\"\"\n        if attempt >= len(self.RETRY_SCHEDULE):\n            self._move_to_dead_letter(endpoint, event)\n            return {'status': 'failed', 'attempts': attempt + 1}\n\n        delay = self.RETRY_SCHEDULE[attempt]\n        # In production: use job queue with delayed execution\n        await asyncio.sleep(delay.total_seconds())\n        return await self.deliver(endpoint, event, attempt + 1)\n\n    def _move_to_dead_letter(self, endpoint, event):\n        \"\"\"Store failed webhook for manual review\"\"\"\n        # Store in dead letter queue\u002Ftable\n        pass\n```\n\n### Endpoint Management\n\n```python\nclass WebhookEndpoint:\n    \"\"\"Subscriber endpoint configuration\"\"\"\n\n    def __init__(self, url, events, secret=None):  # allow-secret\n        self.id = generate_id()\n        self.url = url\n        self.events = events  # List of subscribed event types\n        self.secret = secret or generate_secret()  # allow-secret\n        self.status = 'active'\n        self.created_at = datetime.utcnow()\n\n        # Health tracking\n        self.consecutive_failures = 0\n        self.last_success = None\n        self.last_failure = None\n\n    def should_receive(self, event_type):\n        \"\"\"Check if endpoint subscribes to this event\"\"\"\n        if '*' in self.events:\n            return True\n        return event_type in self.events\n\n    def record_success(self):\n        self.consecutive_failures = 0\n        self.last_success = datetime.utcnow()\n        if self.status == 'disabled':\n            self.status = 'active'\n\n    def record_failure(self):\n        self.consecutive_failures += 1\n        self.last_failure = datetime.utcnow()\n\n        # Auto-disable after too many failures\n        if self.consecutive_failures >= 10:\n            self.status = 'disabled'\n```\n\n## Webhook Consumer Design\n\n### Signature Verification\n\n```python\nclass WebhookVerifier:\n    \"\"\"Verify incoming webhook signatures\"\"\"\n\n    TIMESTAMP_TOLERANCE = 300  # 5 minutes\n\n    def __init__(self, secret):  # allow-secret\n        self.secret = secret.encode()  # allow-secret\n\n    def verify(self, payload, signature, timestamp):\n        \"\"\"Verify webhook authenticity\"\"\"\n        # Check timestamp freshness\n        current_time = int(time.time())\n        if abs(current_time - int(timestamp)) > self.TIMESTAMP_TOLERANCE:\n            raise WebhookVerificationError(\"Timestamp too old\")\n\n        # Compute expected signature\n        signed_payload = f\"{timestamp}.{payload}\"\n        expected = hmac.new(\n            self.secret,\n            signed_payload.encode(),\n            hashlib.sha256\n        ).hexdigest()\n\n        expected_sig = f\"sha256={expected}\"\n\n        # Constant-time comparison to prevent timing attacks\n        if not hmac.compare_digest(signature, expected_sig):\n            raise WebhookVerificationError(\"Invalid signature\")\n\n        return True\n\n\n# Flask endpoint example\n@app.route('\u002Fwebhooks\u002Fprovider', methods=['POST'])\ndef handle_webhook():\n    verifier = WebhookVerifier(WEBHOOK_SECRET)\n\n    try:\n        verifier.verify(\n            request.data.decode(),\n            request.headers.get('X-Webhook-Signature'),\n            request.headers.get('X-Webhook-Timestamp')\n        )\n    except WebhookVerificationError:\n        return 'Invalid signature', 401\n\n    event = request.json\n    process_webhook(event)\n\n    return 'OK', 200\n```\n\n### Idempotent Processing\n\n```python\nclass IdempotentWebhookProcessor:\n    \"\"\"Process webhooks exactly once\"\"\"\n\n    def __init__(self, storage):\n        self.storage = storage  # Redis, database, etc.\n        self.lock_ttl = 300  # 5 minute lock\n\n    async def process(self, event):\n        \"\"\"Process webhook idempotently\"\"\"\n        event_id = event['id']\n\n        # Check if already processed\n        if await self.storage.exists(f\"webhook:processed:{event_id}\"):\n            return {'status': 'duplicate', 'event_id': event_id}\n\n        # Acquire lock to prevent concurrent processing\n        lock_key = f\"webhook:lock:{event_id}\"\n        if not await self.storage.set_nx(lock_key, \"1\", ex=self.lock_ttl):\n            return {'status': 'processing', 'event_id': event_id}\n\n        try:\n            # Process the event\n            result = await self._handle_event(event)\n\n            # Mark as processed (with long TTL for deduplication)\n            await self.storage.set(\n                f\"webhook:processed:{event_id}\",\n                json.dumps(result),\n                ex=86400 * 7  # Keep for 7 days\n            )\n\n            return {'status': 'processed', 'event_id': event_id}\n\n        finally:\n            await self.storage.delete(lock_key)\n\n    async def _handle_event(self, event):\n        \"\"\"Route event to appropriate handler\"\"\"\n        handlers = {\n            'payment.completed': self._handle_payment_completed,\n            'subscription.cancelled': self._handle_subscription_cancelled,\n            # ... more handlers\n        }\n        handler = handlers.get(event['type'])\n        if handler:\n            return await handler(event['data'])\n        return {'skipped': True, 'reason': 'unknown_event_type'}\n```\n\n### Queue-Based Processing\n\n```python\nclass QueuedWebhookHandler:\n    \"\"\"Decouple receipt from processing\"\"\"\n\n    def __init__(self, queue):\n        self.queue = queue  # Redis, SQS, RabbitMQ, etc.\n\n    async def receive(self, event):\n        \"\"\"Acknowledge receipt quickly, process async\"\"\"\n        # Validate immediately\n        self._validate_event_structure(event)\n\n        # Queue for processing\n        await self.queue.enqueue(\n            'webhook_processing',\n            event,\n            deduplication_id=event['id']\n        )\n\n        # Return 200 immediately (don't make sender wait)\n        return {'status': 'accepted'}\n\n    async def process_queue(self):\n        \"\"\"Worker that processes queued webhooks\"\"\"\n        while True:\n            event = await self.queue.dequeue('webhook_processing')\n            if event:\n                try:\n                    await self._process_event(event)\n                    await self.queue.ack(event)\n                except Exception as e:\n                    await self.queue.nack(event, requeue=True)\n                    logging.error(f\"Webhook processing failed: {e}\")\n```\n\n## Security Patterns\n\n### Secret Rotation\n\n```python\nclass SecretRotation:\n    \"\"\"Support rolling secret updates\"\"\"\n\n    def __init__(self):\n        self.current_secret = None\n        self.previous_secret = None\n        self.rotation_timestamp = None\n\n    def rotate(self, new_secret):\n        \"\"\"Rotate to new secret while supporting old\"\"\"\n        self.previous_secret = self.current_secret\n        self.current_secret = new_secret\n        self.rotation_timestamp = datetime.utcnow()\n\n    def get_verification_secrets(self):\n        \"\"\"Return secrets to try for verification\"\"\"\n        secrets = [self.current_secret]\n\n        # Accept previous secret for grace period\n        if self.previous_secret and self.rotation_timestamp:\n            grace_period = timedelta(hours=24)\n            if datetime.utcnow() - self.rotation_timestamp \u003C grace_period:\n                secrets.append(self.previous_secret)\n\n        return secrets\n```\n\n### IP Allowlisting\n\n```python\nALLOWED_IPS = {\n    'stripe': ['3.18.12.63', '3.130.192.231', ...],\n    'github': ['192.30.252.0\u002F22', '185.199.108.0\u002F22', ...],\n    'twilio': ['54.172.60.0\u002F23', '54.244.51.0\u002F24', ...]\n}\n\ndef verify_source_ip(request, provider):\n    \"\"\"Verify webhook comes from expected IP\"\"\"\n    client_ip = request.remote_addr\n\n    allowed = ALLOWED_IPS.get(provider, [])\n    for allowed_range in allowed:\n        if ip_in_range(client_ip, allowed_range):\n            return True\n\n    return False\n```\n\n## Error Handling\n\n### Response Codes\n\n| Code | Meaning | Provider Action |\n|------|---------|-----------------|\n| 200-204 | Success | Mark delivered |\n| 400 | Bad request | Don't retry (your bug) |\n| 401\u002F403 | Auth failed | Disable endpoint |\n| 404 | Not found | Disable endpoint |\n| 429 | Rate limited | Retry with backoff |\n| 500+ | Server error | Retry |\n| Timeout | No response | Retry |\n\n### Dead Letter Queue\n\n```python\nclass DeadLetterQueue:\n    \"\"\"Store and manage failed webhooks\"\"\"\n\n    async def add(self, endpoint, event, failure_reason, attempts):\n        \"\"\"Add failed webhook to DLQ\"\"\"\n        await self.storage.add({\n            'id': generate_id(),\n            'endpoint_id': endpoint.id,\n            'endpoint_url': endpoint.url,\n            'event': event.to_payload(),\n            'failure_reason': str(failure_reason),\n            'attempts': attempts,\n            'added_at': datetime.utcnow().isoformat()\n        })\n\n    async def retry(self, dlq_item_id):\n        \"\"\"Manually retry a DLQ item\"\"\"\n        item = await self.storage.get(dlq_item_id)\n        endpoint = await self.get_endpoint(item['endpoint_id'])\n        event = WebhookEvent.from_payload(item['event'])\n\n        result = await self.delivery_system.deliver(endpoint, event)\n\n        if result['status'] == 'delivered':\n            await self.storage.remove(dlq_item_id)\n\n        return result\n\n    async def purge_old(self, days=30):\n        \"\"\"Clean up old DLQ items\"\"\"\n        cutoff = datetime.utcnow() - timedelta(days=days)\n        await self.storage.delete_before(cutoff)\n```\n\n## Best Practices\n\n### For Providers\n\n1. **Include event ID** for consumer deduplication\n2. **Sign payloads** with HMAC-SHA256 minimum\n3. **Include timestamps** to prevent replay\n4. **Retry with exponential backoff** (5 attempts minimum)\n5. **Provide webhook logs** in your dashboard\n6. **Support event filtering** by type\n7. **Version your payloads** for backward compatibility\n\n### For Consumers\n\n1. **Verify signatures** before processing\n2. **Respond quickly** (\u003C 5 seconds)\n3. **Process asynchronously** via queue\n4. **Implement idempotency** using event ID\n5. **Log everything** for debugging\n6. **Monitor for failures** proactively\n\n## References\n\n- `references\u002Fwebhook-security.md` - Detailed security implementation\n- `references\u002Fprovider-examples.md` - Stripe, GitHub, Twilio patterns\n- `references\u002Ftesting-webhooks.md` - Local development and testing\n",{"name":5,"license":15,"triggers":44,"description":7,"organ_affinity":48,"governance_phases":52},[45,46,47],"user-asks-about-webhooks","user-asks-about-event-driven","context:integration",[49,50,51],"organ-iii","organ-iv","organ-vii",[25],"main","4d2fb89cdfb75f3f6fd3c6c5ec9ad90ea129eb3c","ai-agent-skills\u002F21-external-registries\u002F18-organvm-skills\u002Fintegrations\u002Fwebhook-integration-patterns",2,"https:\u002F\u002Fgithub.com\u002Fluokai0\u002Fai-agent-skills-by-luo-kai","https:\u002F\u002Fgithub.com\u002Fluokai0","a solo builder.","2026-05-06 04:29:04",{"source":8,"skillName":5,"commands":62,"prompt":72,"zipAvailable":73},[63,66,69],{"tool":64,"command":65},"npx","npx skills add luokai0\u002Fai-agent-skills-by-luo-kai --skill webhook-integration-patterns",{"tool":67,"command":68},"bunx","bunx skills add luokai0\u002Fai-agent-skills-by-luo-kai --skill webhook-integration-patterns",{"tool":70,"command":71},"pnpm","pnpm dlx skills add luokai0\u002Fai-agent-skills-by-luo-kai --skill webhook-integration-patterns","安装技能，技能地址：https:\u002F\u002Fgithub.com\u002Fluokai0\u002Fai-agent-skills-by-luo-kai\u002Fblob\u002Fmain\u002Fai-agent-skills\u002F21-external-registries\u002F18-organvm-skills\u002Fintegrations\u002Fwebhook-integration-patterns\u002FSKILL.md",true,[75,81,85,89],{"path":76,"resourceType":77,"resourceTypeDesc":78,"sizeBytes":79,"sourceHtmlUrl":80},"references\u002Fprovider-examples.md","REFERENCE","参考文档",7126,"https:\u002F\u002Fgithub.com\u002Fluokai0\u002Fai-agent-skills-by-luo-kai\u002Fblob\u002Fmain\u002Fai-agent-skills\u002F21-external-registries\u002F18-organvm-skills\u002Fintegrations\u002Fwebhook-integration-patterns\u002Freferences\u002Fprovider-examples.md",{"path":82,"resourceType":77,"resourceTypeDesc":78,"sizeBytes":83,"sourceHtmlUrl":84},"references\u002Ftesting-webhooks.md",7325,"https:\u002F\u002Fgithub.com\u002Fluokai0\u002Fai-agent-skills-by-luo-kai\u002Fblob\u002Fmain\u002Fai-agent-skills\u002F21-external-registries\u002F18-organvm-skills\u002Fintegrations\u002Fwebhook-integration-patterns\u002Freferences\u002Ftesting-webhooks.md",{"path":86,"resourceType":77,"resourceTypeDesc":78,"sizeBytes":87,"sourceHtmlUrl":88},"references\u002Fwebhook-security.md",7295,"https:\u002F\u002Fgithub.com\u002Fluokai0\u002Fai-agent-skills-by-luo-kai\u002Fblob\u002Fmain\u002Fai-agent-skills\u002F21-external-registries\u002F18-organvm-skills\u002Fintegrations\u002Fwebhook-integration-patterns\u002Freferences\u002Fwebhook-security.md",{"path":90,"resourceType":77,"resourceTypeDesc":78,"sizeBytes":91,"sourceHtmlUrl":92},"references\u002Fworkflow-integration.md",6013,"https:\u002F\u002Fgithub.com\u002Fluokai0\u002Fai-agent-skills-by-luo-kai\u002Fblob\u002Fmain\u002Fai-agent-skills\u002F21-external-registries\u002F18-organvm-skills\u002Fintegrations\u002Fwebhook-integration-patterns\u002Freferences\u002Fworkflow-integration.md",[94,121,138,162,188,213],{"skillNo":95,"name":96,"nameZh":6,"description":97,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":98,"categories":99,"keywords":100,"publishedAt":39},"01M6F2SKTE208174C7S7JJCZC7","write-contracts","Generates secure Aptos Move V2 smart contracts with Object model, Digital Asset integration, security patterns, and storage type guidance. Includes comprehensive storage decision framework for optimal data structure selection. Triggers on: 'write contract', 'create NFT collection', 'build marketplace', 'implement minting', 'generate Move module', 'create token contract', 'build DAO', 'implement staking'. Ask storage questions when: 'store', 'track', 'registry', 'mapping', 'list', 'collection'.","https:\u002F\u002Fgithub.com\u002Fluokai0\u002Fai-agent-skills-by-luo-kai\u002Fblob\u002Fmain\u002Fai-agent-skills\u002F22-clawhub-skills\u002Fwrite-contracts\u002FSKILL.md",[],[101,102,103,104,105,106,107,108,109,110,111,112,113,114,115,116,117,118,119,120],"write","contracts","write contracts","storage","secure","create","generate","collection","model","decision","ask","smart-contracts","selection","objects","structure","nft","token","aptos","critical","move",{"skillNo":122,"name":123,"nameZh":6,"description":124,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":125,"categories":126,"keywords":127,"publishedAt":39},"01M6F2RFXJ6T9MKW0A7N7GM45B","web-search","通用网络搜索技能，支持多引擎搜索（百度、必应、DuckDuckGo），无需API密钥即可获取实时信息","https:\u002F\u002Fgithub.com\u002Fluokai0\u002Fai-agent-skills-by-luo-kai\u002Fblob\u002Fmain\u002Fai-agent-skills\u002F22-clawhub-skills\u002Fweb-search-ex-skill\u002FSKILL.md",[],[128,129,130,131,132,133,134,135,136,137],"web","search","web search","搜索","baidu","bing","duckduckgo","百度","多引擎","internet",{"skillNo":139,"name":140,"nameZh":6,"description":141,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":142,"categories":143,"keywords":144,"publishedAt":39},"01M6F2K968G1FZEZFPW2E6B222","solo-build","Execute implementation plan tasks with TDD workflow, auto-commit, and phase gates. Use when user says \"build it\", \"start building\", \"execute plan\", \"implement tasks\", \"ship it\", or references a track ID. Do NOT use for planning (use \u002Fplan) or scaffolding (use \u002Fscaffold).","https:\u002F\u002Fgithub.com\u002Fluokai0\u002Fai-agent-skills-by-luo-kai\u002Fblob\u002Fmain\u002Fai-agent-skills\u002F22-clawhub-skills\u002Fsolo-build\u002FSKILL.md",[],[25,145,146,147,148,149,150,151,129,152,153,154,101,155,156,157,158,159,160,161],"solo","solo build","MCP","workflow","commit","tasks","code","Bash","plan","read","auto","references","context7","query","scaffolding","ship it","project",{"skillNo":163,"name":164,"nameZh":6,"description":165,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":166,"categories":167,"keywords":168,"publishedAt":39},"01M6F2GKN39SGHSPWYB3662YC8","react-email","Use when building HTML email templates with React components, adding a visual email editor to an application using the React Email visual editor, rendering emails to HTML, or sending emails with Resend. Covers welcome emails, password resets, notifications, order confirmations, newsletters, transactional emails, and the embeddable email editor component.","https:\u002F\u002Fgithub.com\u002Fluokai0\u002Fai-agent-skills-by-luo-kai\u002Fblob\u002Fmain\u002Fai-agent-skills\u002F22-clawhub-skills\u002Freact-email-skills\u002FSKILL.md",[],[169,170,171,172,173,174,175,176,177,178,179,180,181,182,183,184,185,186,187,37],"react","email","react email","github","editor","components","react components","component","welcome","https","notifications","password","node","use","html","resend","visual","emails","rendering",{"skillNo":189,"name":190,"nameZh":6,"description":191,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":192,"categories":193,"keywords":194,"publishedAt":39},"01M6F2FBVGVDFSG8SSFJGXA40C","APITester Agent-Driven API Testing","Test API endpoints and document responses. Define tests in plain English, run them, get formatted results. Agent-driven Postman alternative.","https:\u002F\u002Fgithub.com\u002Fluokai0\u002Fai-agent-skills-by-luo-kai\u002Fblob\u002Fmain\u002Fai-agent-skills\u002F22-clawhub-skills\u002Fopenclaw-api-tester\u002FSKILL.md",[],[195,196,197,198,199,200,201,202,203,204,205,206,207,208,209,210,211,212],"testing","api","api testing","driven","APITester Agent Driven API Testing","test","run","postman","results","plain english","tester","endpoints","document","get","define","tests","english","api-tester",{"skillNo":214,"name":215,"nameZh":6,"description":216,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":217,"categories":218,"keywords":219,"publishedAt":39},"01M6F273Y3NGAPVJZ608BC0G9G","hubspot-implementation-plan","Generate a phased implementation plan from a HubSpot audit report. Creates prioritized, sequenced cleanup processes with effort estimates, dependencies, and automation feasibility. Use after running \u002Fhubspot-audit.","https:\u002F\u002Fgithub.com\u002Fluokai0\u002Fai-agent-skills-by-luo-kai\u002Fblob\u002Fmain\u002Fai-agent-skills\u002F22-clawhub-skills\u002Fhubspot-implementation-plan\u002FSKILL.md",[],[153,220,221,222,223,224,225,107,226,227,228,229,230,182,231,232,37,233],"implementation","hubspot","hubspot implementation plan","automation","feasibility","cleanup","planning","report","audit","audit report","phased implementation","dependencies","processes","hubspot audit"]