Verify WooCommerce webhooks
WooCommerce signs each delivery so you can confirm it came from your store and wasn't changed on the way. The X-WC-Webhook-Signature header holds a base64-encoded HMAC-SHA256 of the raw request body, keyed with that webhook's secret. No timestamp is signed, and the ping WooCommerce sends when you activate a webhook has no signature at all.
The facts
{raw body} The request body as sent, after WooCommerce has JSON-encoded it. No timestamp is part of it.
WooCommerce webhook secret
Each WooCommerce webhook has its own secret. You set it on the webhook, or WooCommerce generates one if you leave it blank. Keep it in an environment variable, not in source code.
- In the admin: WooCommerce > Settings > Advanced > Webhooks, open the webhook and read or set the **Secret** field.
- Through the REST API: pass
secretwhen you create the webhook. WooCommerce's REST docs list it as write-only, so keep your own copy. - Leave it blank and WooCommerce generates a 50-character password that includes special characters.
- Use a long alphanumeric secret of your own. WooCommerce decodes HTML entities in the secret before signing, and the admin form sanitizes what's submitted, so other characters can sign differently from what you stored.
- Rotation: a webhook has one secret and no overlap period. Deliveries use the new secret as soon as you save it, so accept both on your side during the change.
Source: WooCommerce docs ↗
Code
Docs discrepancy · read before the code
WooCommerce's docs say a blank secret defaults to the current API user's consumer secret, and its REST docs say an MD5 hash of the user's ID and username. In WooCommerce 11.2.1, the admin form and the REST API both generate a random 50-character password instead.
WooCommerce docs ↗const express = require('express');
const crypto = require('crypto');
require('dotenv').config();
const app = express();
const PORT = process.env.PORT || 3000;
/**
* Verify WooCommerce webhook signature using HMAC SHA-256
* @param {Buffer} rawBody - Raw request body
* @param {string} signature - X-WC-Webhook-Signature header value
* @param {string} secret - Webhook secret from WooCommerce
* @returns {boolean} - True if signature is valid
*/
function verifyWooCommerceWebhook(rawBody, signature, secret) {
if (!signature || !secret || !rawBody) {
return false;
}
const expectedSignature = crypto
.createHmac('sha256', secret)
.update(rawBody)
.digest('base64');
try {
return crypto.timingSafeEqual(
Buffer.from(signature),
Buffer.from(expectedSignature)
);
} catch (error) {
// Different lengths will cause an error
return false;
}
}
/**
* Handle different WooCommerce event types
* @param {string} topic - Event topic (e.g., "order.created")
* @param {Object} payload - Webhook payload
*/
function handleWooCommerceEvent(topic, payload) {
console.log(`Processing ${topic} event for ID: ${payload.id}`);
switch (topic) {
case 'order.created':
console.log(`New order #${payload.id} for $${payload.total}`);
// Add your order processing logic here
break;
case 'order.updated':
console.log(`Order #${payload.id} updated to status: ${payload.status}`);
// Add your order update logic here
break;
case 'product.created':
console.log(`New product: ${payload.name} (ID: ${payload.id})`);
// Add your product sync logic here
break;
case 'product.updated':
console.log(`Product updated: ${payload.name} (ID: ${payload.id})`);
// Add your product update logic here
break;
case 'customer.created':
console.log(`New customer: ${payload.email} (ID: ${payload.id})`);
// Add your customer onboarding logic here
break;
case 'customer.updated':
console.log(`Customer updated: ${payload.email} (ID: ${payload.id})`);
// Add your customer update logic here
break;
default:
console.log(`Unhandled event type: ${topic}`);
}
}
// CRITICAL: Use raw body parser for signature verification
app.use('/webhooks/woocommerce', express.raw({ type: 'application/json' }));
// WooCommerce webhook endpoint
app.post('/webhooks/woocommerce', (req, res) => {
try {
const signature = req.headers['x-wc-webhook-signature'];
const topic = req.headers['x-wc-webhook-topic'];
const source = req.headers['x-wc-webhook-source'];
const secret = process.env.WOOCOMMERCE_WEBHOOK_SECRET;
console.log(`Received webhook: ${topic} from ${source}`);
// Verify webhook signature
if (!verifyWooCommerceWebhook(req.body, signature, secret)) {
console.log('❌ Invalid webhook signature');
return res.status(400).json({ error: 'Invalid signature' });
}
console.log('✅ Signature verified');
// Parse the JSON payload
const payload = JSON.parse(req.body.toString());
// Handle the event
handleWooCommerceEvent(topic, payload);
// Respond with success
res.status(200).json({ received: true });
} catch (error) {
console.error('Error processing webhook:', error);
res.status(500).json({ error: 'Internal server error' });
}
});
// Health check endpoint
app.get('/health', (req, res) => {
res.status(200).json({ status: 'healthy', timestamp: new Date().toISOString() });
});
// Start server only when run directly (not when imported for testing)
if (require.main === module) {
app.listen(PORT, () => {
console.log(`🚀 WooCommerce webhook server running on port ${PORT}`);
console.log(`📍 Webhook endpoint: http://localhost:${PORT}/webhooks/woocommerce`);
console.log('🔒 Make sure to set WOOCOMMERCE_WEBHOOK_SECRET in your environment');
});
}
module.exports = { app, verifyWooCommerceWebhook }; import crypto from 'crypto';
import { NextRequest } from 'next/server';
/**
* Verify WooCommerce webhook signature using HMAC SHA-256
* @param rawBody - Raw request body as string
* @param signature - X-WC-Webhook-Signature header value
* @param secret - Webhook secret from WooCommerce
* @returns True if signature is valid
*/
function verifyWooCommerceWebhook(rawBody: string, signature: string | null, secret: string | undefined): boolean {
if (!signature || !secret || !rawBody) {
return false;
}
const expectedSignature = crypto
.createHmac('sha256', secret)
.update(rawBody)
.digest('base64');
try {
return crypto.timingSafeEqual(
Buffer.from(signature),
Buffer.from(expectedSignature)
);
} catch (error) {
// Different lengths will cause an error
return false;
}
}
/**
* Handle different WooCommerce event types
* @param topic - Event topic (e.g., "order.created")
* @param payload - Webhook payload
*/
function handleWooCommerceEvent(topic: string, payload: any) {
console.log(`Processing ${topic} event for ID: ${payload.id}`);
switch (topic) {
case 'order.created':
console.log(`New order #${payload.id} for $${payload.total}`);
// Add your order processing logic here
break;
case 'order.updated':
console.log(`Order #${payload.id} updated to status: ${payload.status}`);
// Add your order update logic here
break;
case 'product.created':
console.log(`New product: ${payload.name} (ID: ${payload.id})`);
// Add your product sync logic here
break;
case 'product.updated':
console.log(`Product updated: ${payload.name} (ID: ${payload.id})`);
// Add your product update logic here
break;
case 'customer.created':
console.log(`New customer: ${payload.email} (ID: ${payload.id})`);
// Add your customer onboarding logic here
break;
case 'customer.updated':
console.log(`Customer updated: ${payload.email} (ID: ${payload.id})`);
// Add your customer update logic here
break;
default:
console.log(`Unhandled event type: ${topic}`);
}
}
export async function POST(request: NextRequest) {
try {
const signature = request.headers.get('x-wc-webhook-signature');
const topic = request.headers.get('x-wc-webhook-topic');
const source = request.headers.get('x-wc-webhook-source');
const secret = process.env.WOOCOMMERCE_WEBHOOK_SECRET;
console.log(`Received webhook: ${topic} from ${source}`);
// Get raw body for signature verification
const rawBody = await request.text();
// Verify webhook signature
if (!verifyWooCommerceWebhook(rawBody, signature, secret)) {
console.log('❌ Invalid webhook signature');
return new Response(JSON.stringify({ error: 'Invalid signature' }), {
status: 400,
headers: { 'Content-Type': 'application/json' },
});
}
console.log('✅ Signature verified');
// Parse the JSON payload
const payload = JSON.parse(rawBody);
// Handle the event
if (topic) {
handleWooCommerceEvent(topic, payload);
}
// Respond with success
return new Response(JSON.stringify({ received: true }), {
status: 200,
headers: { 'Content-Type': 'application/json' },
});
} catch (error) {
console.error('Error processing webhook:', error);
return new Response(JSON.stringify({ error: 'Internal server error' }), {
status: 500,
headers: { 'Content-Type': 'application/json' },
});
}
}
// Export the verification function for testing
export { verifyWooCommerceWebhook }; import os
import hmac
import hashlib
import base64
from typing import Any, Dict, Optional
from dotenv import load_dotenv
from fastapi import FastAPI, Request, HTTPException
# Load environment variables
load_dotenv()
app = FastAPI(title="WooCommerce Webhook Handler", version="1.0.0")
def verify_woocommerce_webhook(raw_body: bytes, signature: Optional[str], secret: Optional[str]) -> bool:
"""
Verify WooCommerce webhook signature using HMAC SHA-256
Args:
raw_body: Raw request body as bytes
signature: X-WC-Webhook-Signature header value
secret: Webhook secret from WooCommerce
Returns:
True if signature is valid
"""
if not signature or not secret or not raw_body:
return False
# Generate expected signature
hash_digest = hmac.new(
secret.encode('utf-8'),
raw_body,
hashlib.sha256
).digest()
expected_signature = base64.b64encode(hash_digest).decode('utf-8')
# Use timing-safe comparison to prevent timing attacks
return hmac.compare_digest(signature, expected_signature)
def handle_woocommerce_event(topic: str, payload: Dict[str, Any]) -> None:
"""
Handle different WooCommerce event types
Args:
topic: Event topic (e.g., "order.created")
payload: Webhook payload
"""
print(f"Processing {topic} event for ID: {payload.get('id')}")
if topic == 'order.created':
print(f"New order #{payload.get('id')} for ${payload.get('total')}")
# Add your order processing logic here
elif topic == 'order.updated':
print(f"Order #{payload.get('id')} updated to status: {payload.get('status')}")
# Add your order update logic here
elif topic == 'product.created':
print(f"New product: {payload.get('name')} (ID: {payload.get('id')})")
# Add your product sync logic here
elif topic == 'product.updated':
print(f"Product updated: {payload.get('name')} (ID: {payload.get('id')})")
# Add your product update logic here
elif topic == 'customer.created':
print(f"New customer: {payload.get('email')} (ID: {payload.get('id')})")
# Add your customer onboarding logic here
elif topic == 'customer.updated':
print(f"Customer updated: {payload.get('email')} (ID: {payload.get('id')})")
# Add your customer update logic here
else:
print(f"Unhandled event type: {topic}")
@app.post("/webhooks/woocommerce")
async def handle_webhook(request: Request):
"""
WooCommerce webhook endpoint
"""
try:
# Get headers
signature = request.headers.get('x-wc-webhook-signature')
topic = request.headers.get('x-wc-webhook-topic')
source = request.headers.get('x-wc-webhook-source')
secret = os.getenv('WOOCOMMERCE_WEBHOOK_SECRET')
print(f"Received webhook: {topic} from {source}")
# Get raw body for signature verification
raw_body = await request.body()
# Verify webhook signature
if not verify_woocommerce_webhook(raw_body, signature, secret):
print("❌ Invalid webhook signature")
raise HTTPException(status_code=400, detail="Invalid signature")
print("✅ Signature verified")
# Parse the JSON payload
payload = await request.json()
# Handle the event
if topic:
handle_woocommerce_event(topic, payload)
# Respond with success
return {"received": True}
except HTTPException:
# Re-raise HTTP exceptions (like 400 for invalid signature)
raise
except Exception as e:
print(f"Error processing webhook: {e}")
raise HTTPException(status_code=500, detail="Internal server error")
@app.get("/health")
async def health_check():
"""
Health check endpoint
"""
return {
"status": "healthy",
"timestamp": "2024-01-15T10:30:00Z"
}
if __name__ == "__main__":
import uvicorn
uvicorn.run(app, host="0.0.0.0", port=8000) Or install the WooCommerce webhooks skill:
npx skills add hookdeck/webhook-skills --skill woocommerce-webhooks
Common failures
Body parsed before verification
The signature covers the raw request body. WooCommerce's JSON escapes slashes and non-ASCII characters, so a body you've parsed and re-serialized won't match. Capture the raw bytes and verify before any body parser runs.
Rejecting the ping
The ping's body is webhook_id=<id> and it has no X-WC-Webhook-Signature header, so strict verification fails it and the admin shows an error. Return 200 to a request with no X-WC-Webhook-Topic header, without processing it.
Special characters in the secret
WooCommerce decodes HTML entities in the secret before signing, so & signs as &, and the admin form sanitizes what it saves. Use a long alphanumeric secret.
Comparing the wrong encoding
The header is base64, not hex. Compute the digest as base64, or decode both values before comparing them.
Let Event Gateway verify WooCommerce signatures.
Event Gateway verifies the signature on each WooCommerce delivery before it reaches your service, then queues it and retries failures on your schedule.