$npx -y skills add hookdeck/webhook-skills --skill openai-webhooksReceive and verify OpenAI webhooks. Use when setting up OpenAI webhook handlers for fine-tuning jobs, batch completions, or async events like fine_tuning.job.completed, batch.completed, or realtime.call.incoming.
| 1 | # OpenAI Webhooks |
| 2 | |
| 3 | ## When to Use This Skill |
| 4 | |
| 5 | - Setting up OpenAI webhook handlers for async operations |
| 6 | - Debugging signature verification failures |
| 7 | - Handling fine-tuning job completion events |
| 8 | - Processing batch API completion notifications |
| 9 | - Handling realtime API incoming calls |
| 10 | |
| 11 | ## Essential Code (USE THIS) |
| 12 | |
| 13 | ### Express Webhook Handler |
| 14 | |
| 15 | ```javascript |
| 16 | const express = require('express'); |
| 17 | const crypto = require('crypto'); |
| 18 | |
| 19 | const app = express(); |
| 20 | |
| 21 | // Standard Webhooks signature verification for OpenAI |
| 22 | function verifyOpenAISignature(payload, webhookId, webhookTimestamp, webhookSignature, secret) { |
| 23 | if (!webhookSignature || !webhookSignature.includes(',')) { |
| 24 | return false; |
| 25 | } |
| 26 | |
| 27 | // Check timestamp is within 5 minutes to prevent replay attacks |
| 28 | const currentTime = Math.floor(Date.now() / 1000); |
| 29 | const timestampDiff = currentTime - parseInt(webhookTimestamp); |
| 30 | if (timestampDiff > 300 || timestampDiff < -300) { |
| 31 | console.error('Webhook timestamp too old or too far in the future'); |
| 32 | return false; |
| 33 | } |
| 34 | |
| 35 | // Extract version and signature |
| 36 | const [version, signature] = webhookSignature.split(','); |
| 37 | if (version !== 'v1') { |
| 38 | return false; |
| 39 | } |
| 40 | |
| 41 | // Create signed content: webhook_id.webhook_timestamp.payload |
| 42 | const payloadStr = payload instanceof Buffer ? payload.toString('utf8') : payload; |
| 43 | const signedContent = `${webhookId}.${webhookTimestamp}.${payloadStr}`; |
| 44 | |
| 45 | // Decode base64 secret (remove whsec_ prefix if present) |
| 46 | const secretKey = secret.startsWith('whsec_') ? secret.slice(6) : secret; |
| 47 | const secretBytes = Buffer.from(secretKey, 'base64'); |
| 48 | |
| 49 | // Generate expected signature |
| 50 | const expectedSignature = crypto |
| 51 | .createHmac('sha256', secretBytes) |
| 52 | .update(signedContent, 'utf8') |
| 53 | .digest('base64'); |
| 54 | |
| 55 | // Timing-safe comparison |
| 56 | return crypto.timingSafeEqual( |
| 57 | Buffer.from(signature), |
| 58 | Buffer.from(expectedSignature) |
| 59 | ); |
| 60 | } |
| 61 | |
| 62 | // CRITICAL: Use express.raw() for webhook endpoint - OpenAI needs raw body |
| 63 | app.post('/webhooks/openai', |
| 64 | express.raw({ type: 'application/json' }), |
| 65 | async (req, res) => { |
| 66 | const webhookId = req.headers['webhook-id']; |
| 67 | const webhookTimestamp = req.headers['webhook-timestamp']; |
| 68 | const webhookSignature = req.headers['webhook-signature']; |
| 69 | |
| 70 | // Verify signature |
| 71 | if (!verifyOpenAISignature( |
| 72 | req.body, |
| 73 | webhookId, |
| 74 | webhookTimestamp, |
| 75 | webhookSignature, |
| 76 | process.env.OPENAI_WEBHOOK_SECRET |
| 77 | )) { |
| 78 | console.error('Invalid OpenAI webhook signature'); |
| 79 | return res.status(400).send('Invalid signature'); |
| 80 | } |
| 81 | |
| 82 | // Parse the verified payload |
| 83 | const event = JSON.parse(req.body.toString()); |
| 84 | |
| 85 | // Handle the event |
| 86 | switch (event.type) { |
| 87 | case 'fine_tuning.job.succeeded': |
| 88 | console.log('Fine-tuning job succeeded:', event.data.id); |
| 89 | break; |
| 90 | case 'fine_tuning.job.failed': |
| 91 | console.log('Fine-tuning job failed:', event.data.id); |
| 92 | break; |
| 93 | case 'batch.completed': |
| 94 | console.log('Batch completed:', event.data.id); |
| 95 | break; |
| 96 | case 'batch.failed': |
| 97 | console.log('Batch failed:', event.data.id); |
| 98 | break; |
| 99 | case 'batch.cancelled': |
| 100 | console.log('Batch cancelled:', event.data.id); |
| 101 | break; |
| 102 | case 'batch.expired': |
| 103 | console.log('Batch expired:', event.data.id); |
| 104 | break; |
| 105 | case 'realtime.call.incoming': |
| 106 | console.log('Realtime call incoming:', event.data.id); |
| 107 | break; |
| 108 | default: |
| 109 | console.log('Unhandled event:', event.type); |
| 110 | } |
| 111 | |
| 112 | res.json({ received: true }); |
| 113 | } |
| 114 | ); |
| 115 | ``` |
| 116 | |
| 117 | ### Python (FastAPI) Webhook Handler |
| 118 | |
| 119 | ```python |
| 120 | import os |
| 121 | import hmac |
| 122 | import hashlib |
| 123 | import base64 |
| 124 | import time |
| 125 | from fastapi import FastAPI, Request, HTTPException, Header |
| 126 | |
| 127 | app = FastAPI() |
| 128 | |
| 129 | def verify_openai_signature( |
| 130 | payload: bytes, |
| 131 | webhook_id: str, |
| 132 | webhook_timestamp: str, |
| 133 | webhook_signature: str, |
| 134 | secret: str |
| 135 | ) -> bool: |
| 136 | if not webhook_signature or ',' not in webhook_signature: |
| 137 | return False |
| 138 | |
| 139 | # Check timestamp is within 5 minutes |
| 140 | current_time = int(time.time()) |
| 141 | timestamp_diff = current_time - int(webhook_timestamp) |
| 142 | if timestamp_diff > 300 or timestamp_diff < -300: |
| 143 | return False |
| 144 | |
| 145 | # Extract version and signature |
| 146 | version, signature = webhook_signature.split(',', 1) |
| 147 | if version != 'v1': |
| 148 | return False |
| 149 | |
| 150 | # Create signed content |
| 151 | signed_content = f"{webhook_id}.{webhook_timestamp}.{payload.decode('utf-8')}" |
| 152 | |
| 153 | # Decode base64 secret (remove whsec_ prefix if present) |
| 154 | secret_key = secret[6:] if secret.startswith('whsec_') else secret |
| 155 | secret_bytes = base64.b64decode(secret_key) |
| 156 | |
| 157 | # G |