Verify Shopify webhooks
Shopify signs each HTTPS delivery so you can confirm that it came from Shopify. The X-Shopify-Hmac-SHA256 header holds a base64-encoded HMAC-SHA256 of the raw request body, keyed with your app's client secret. Shopify's React Router template and ShopifyApp library can check it for you, and Google Pub/Sub and Amazon EventBridge deliveries don't need it.
The facts
{raw body} The request body as sent, before any parsing. No timestamp is part of it.
Shopify webhook secret
Shopify signs webhooks with your app's client secret, the same one it uses for OAuth. There's no separate webhook secret. Keep it in an environment variable, not in source code.
- In the Dev Dashboard: open Apps, select your app, click Settings and copy the secret under Credentials.
- Some tools and docs call it the API secret, as in
SHOPIFY_API_SECRET. - Rotation: Shopify keeps signing with your oldest unrevoked client secret until you revoke it, so accept both the old and new secrets during the change. Shopify's verification page says the switch to a new secret can take up to an hour.
- Admin-created custom apps have no Dev Dashboard entry and can't rotate this way.
Source: Shopify docs ↗
Code
require('dotenv').config();
const express = require('express');
const crypto = require('crypto');
const app = express();
/**
* Verify Shopify webhook signature
* @param {Buffer} rawBody - Raw request body
* @param {string} hmacHeader - X-Shopify-Hmac-SHA256 header value
* @param {string} secret - Shopify API secret
* @returns {boolean} - Whether signature is valid
*/
function verifyShopifyWebhook(rawBody, hmacHeader, secret) {
const hash = crypto
.createHmac('sha256', secret)
.update(rawBody, 'utf8')
.digest('base64');
try {
return crypto.timingSafeEqual(
Buffer.from(hash),
Buffer.from(hmacHeader)
);
} catch {
return false;
}
}
// Shopify webhook endpoint - must use raw body for signature verification
app.post('/webhooks/shopify',
express.raw({ type: 'application/json' }),
async (req, res) => {
const hmac = req.headers['x-shopify-hmac-sha256'];
const topic = req.headers['x-shopify-topic'];
const shop = req.headers['x-shopify-shop-domain'];
// Verify webhook signature
if (!hmac || !verifyShopifyWebhook(req.body, hmac, process.env.SHOPIFY_API_SECRET)) {
console.error('Webhook signature verification failed');
return res.status(400).send('Invalid signature');
}
// Parse the payload after verification
const payload = JSON.parse(req.body.toString());
console.log(`Received ${topic} webhook from ${shop}`);
// Handle the event based on topic
switch (topic) {
case 'orders/create':
console.log('New order:', payload.id);
// Your code: Process new order, sync to fulfillment, etc.
break;
case 'orders/updated':
console.log('Order updated:', payload.id);
// Your code: Update order status, sync changes, etc.
break;
case 'orders/paid':
console.log('Order paid:', payload.id);
// Your code: Trigger fulfillment, record payment, etc.
break;
case 'products/create':
console.log('New product:', payload.id);
// Your code: Sync to external catalog, etc.
break;
case 'products/update':
console.log('Product updated:', payload.id);
// Your code: Update external listings, etc.
break;
case 'customers/create':
console.log('New customer:', payload.id);
// Your code: Welcome email, CRM sync, etc.
break;
case 'app/uninstalled':
console.log('App uninstalled from shop:', shop);
// Your code: Cleanup shop data, etc.
break;
// GDPR mandatory webhooks
case 'customers/data_request':
console.log('Customer data request for shop:', shop);
// Your code: Gather and return customer data
break;
case 'customers/redact':
console.log('Customer redact request for shop:', shop);
// Your code: Delete customer data
break;
case 'shop/redact':
console.log('Shop redact request for shop:', shop);
// Your code: Delete all shop data
break;
default:
console.log(`Unhandled topic: ${topic}`);
}
// Return 200 to acknowledge receipt
res.status(200).send('OK');
}
);
// Health check endpoint
app.get('/health', (req, res) => {
res.json({ status: 'ok' });
});
// Export app for testing
module.exports = { app, verifyShopifyWebhook };
// Start server only when run directly (not when imported for testing)
if (require.main === module) {
const PORT = process.env.PORT || 3000;
app.listen(PORT, () => {
console.log(`Server running on http://localhost:${PORT}`);
console.log(`Webhook endpoint: POST http://localhost:${PORT}/webhooks/shopify`);
});
} import { NextRequest, NextResponse } from 'next/server';
import crypto from 'crypto';
/**
* Verify Shopify webhook signature
*/
function verifyShopifyWebhook(rawBody: string, hmacHeader: string, secret: string): boolean {
const hash = crypto
.createHmac('sha256', secret)
.update(rawBody, 'utf8')
.digest('base64');
try {
return crypto.timingSafeEqual(
Buffer.from(hash),
Buffer.from(hmacHeader)
);
} catch {
return false;
}
}
export async function POST(request: NextRequest) {
// Get the raw body for signature verification
const body = await request.text();
const hmac = request.headers.get('x-shopify-hmac-sha256');
const topic = request.headers.get('x-shopify-topic');
const shop = request.headers.get('x-shopify-shop-domain');
// Verify webhook signature
if (!hmac || !verifyShopifyWebhook(body, hmac, process.env.SHOPIFY_API_SECRET!)) {
console.error('Webhook signature verification failed');
return NextResponse.json(
{ error: 'Invalid signature' },
{ status: 400 }
);
}
// Parse the payload after verification
const payload = JSON.parse(body);
console.log(`Received ${topic} webhook from ${shop}`);
// Handle the event based on topic
switch (topic) {
case 'orders/create':
console.log('New order:', payload.id);
// Your code: Process new order, sync to fulfillment, etc.
break;
case 'orders/updated':
console.log('Order updated:', payload.id);
// Your code: Update order status, sync changes, etc.
break;
case 'orders/paid':
console.log('Order paid:', payload.id);
// Your code: Trigger fulfillment, record payment, etc.
break;
case 'products/create':
console.log('New product:', payload.id);
// Your code: Sync to external catalog, etc.
break;
case 'products/update':
console.log('Product updated:', payload.id);
// Your code: Update external listings, etc.
break;
case 'customers/create':
console.log('New customer:', payload.id);
// Your code: Welcome email, CRM sync, etc.
break;
case 'app/uninstalled':
console.log('App uninstalled from shop:', shop);
// Your code: Cleanup shop data, etc.
break;
// GDPR mandatory webhooks
case 'customers/data_request':
console.log('Customer data request for shop:', shop);
// Your code: Gather and return customer data
break;
case 'customers/redact':
console.log('Customer redact request for shop:', shop);
// Your code: Delete customer data
break;
case 'shop/redact':
console.log('Shop redact request for shop:', shop);
// Your code: Delete all shop data
break;
default:
console.log(`Unhandled topic: ${topic}`);
}
// Return 200 to acknowledge receipt
return NextResponse.json({ received: true });
} import os
import hmac
import hashlib
import base64
import json
from dotenv import load_dotenv
from fastapi import FastAPI, Request, HTTPException
load_dotenv()
app = FastAPI()
shopify_secret = os.environ.get("SHOPIFY_API_SECRET")
def verify_shopify_webhook(raw_body: bytes, hmac_header: str, secret: str) -> bool:
"""Verify Shopify webhook signature."""
computed_hmac = base64.b64encode(
hmac.new(
secret.encode('utf-8'),
raw_body,
hashlib.sha256
).digest()
).decode('utf-8')
return hmac.compare_digest(computed_hmac, hmac_header)
@app.post("/webhooks/shopify")
async def shopify_webhook(request: Request):
# Get the raw body for signature verification
raw_body = await request.body()
hmac_header = request.headers.get("x-shopify-hmac-sha256")
topic = request.headers.get("x-shopify-topic")
shop = request.headers.get("x-shopify-shop-domain")
# Verify webhook signature
if not hmac_header or not verify_shopify_webhook(raw_body, hmac_header, shopify_secret):
raise HTTPException(status_code=400, detail="Invalid signature")
# Parse the payload after verification
payload = json.loads(raw_body)
print(f"Received {topic} webhook from {shop}")
# Handle the event based on topic
if topic == "orders/create":
print(f"New order: {payload['id']}")
# Your code: Process new order, sync to fulfillment, etc.
elif topic == "orders/updated":
print(f"Order updated: {payload['id']}")
# Your code: Update order status, sync changes, etc.
elif topic == "orders/paid":
print(f"Order paid: {payload['id']}")
# Your code: Trigger fulfillment, record payment, etc.
elif topic == "products/create":
print(f"New product: {payload['id']}")
# Your code: Sync to external catalog, etc.
elif topic == "products/update":
print(f"Product updated: {payload['id']}")
# Your code: Update external listings, etc.
elif topic == "customers/create":
print(f"New customer: {payload['id']}")
# Your code: Welcome email, CRM sync, etc.
elif topic == "app/uninstalled":
print(f"App uninstalled from shop: {shop}")
# Your code: Cleanup shop data, etc.
# GDPR mandatory webhooks
elif topic == "customers/data_request":
print(f"Customer data request for shop: {shop}")
# Your code: Gather and return customer data
elif topic == "customers/redact":
print(f"Customer redact request for shop: {shop}")
# Your code: Delete customer data
elif topic == "shop/redact":
print(f"Shop redact request for shop: {shop}")
# Your code: Delete all shop data
else:
print(f"Unhandled topic: {topic}")
# Return 200 to acknowledge receipt
return {"received": True}
@app.get("/health")
async def health():
return {"status": "ok"}
if __name__ == "__main__":
import uvicorn
uvicorn.run(app, host="0.0.0.0", port=3000) Or install the Shopify webhooks skill:
npx skills add hookdeck/webhook-skills --skill shopify-webhooks
Common failures
Body parsed before verification
The signature covers the raw request body. Middleware such as express.json() parses it first, so capture the raw body and verify before any body parser runs.
Comparing the wrong encoding
The header is base64, not hex. Compute the digest as base64, or decode both values before comparing them.
Wrong secret
Use your app's client secret, from Settings > Credentials in the Dev Dashboard. Some tools call it the API secret.
Client secret mid-rotation
Shopify signs with your oldest unrevoked secret until you revoke it, so accept both the old and new secrets during a rotation.
Let Event Gateway verify Shopify signatures.
Event Gateway verifies the signature on each Shopify delivery before it reaches your service, then queues it and retries failures on your schedule.