Verify TikTok Shop webhooks
TikTok Shop signs each delivery so you can confirm it came from TikTok Shop and wasn't changed on the way. The Authorization header holds a lowercase hex HMAC-SHA256 of your app key followed by the raw request body, keyed with your app secret, and it has no Bearer prefix. It isn't the signature your app creates when it calls TikTok Shop's APIs.
The facts
authorization Format: `<lowercase hex>`, with no `Bearer` prefix
{app_key}{raw body} Your app key, then the raw request body as sent, with nothing between them.
Recompute the HMAC over your app key plus the raw body, and compare TikTok Shop webhook secret
Verification uses two values from your app: app_secret is the HMAC key, and app_key is the start of the signed content. Keep it in an environment variable, not in source code.
- Use your app's
app_secretas the key and put itsapp_keyin front of the raw body. - This isn't the signature your app creates when it calls TikTok Shop's APIs, so don't reuse that code.
Source: TikTok Shop docs ↗
Code
// Generated with: tiktok-shop-webhooks skill
// https://github.com/hookdeck/webhook-skills
require('dotenv').config();
const express = require('express');
const crypto = require('crypto');
const app = express();
const APP_KEY = process.env.TIKTOK_SHOP_APP_KEY;
const APP_SECRET = process.env.TIKTOK_SHOP_APP_SECRET;
// TikTok Shop does NOT publish a complete numeric `type` -> topic mapping
// ("Do not branch only on the numeric type; use the subscribed event_type
// context" — official webhooks overview). Only `type: 1` appears in the
// official sample payload, for ORDER_STATUS_CHANGE. Fill this map from YOUR
// OWN Partner Center subscriptions — or better, register a distinct callback
// URL per event_type (the Update Shop Webhook API takes one address per
// topic) so the route itself identifies the event.
const SUBSCRIBED_TYPE_TO_EVENT = {
1: 'ORDER_STATUS_CHANGE', // per the official sample payload
};
/**
* Verify a TikTok Shop webhook signature.
*
* TikTok Shop signs: HMAC-SHA256(key = app_secret, message = app_key + rawBody),
* lowercase hex, delivered in the `Authorization` header (no "Bearer" prefix).
* There is no timestamp in the signature (no replay protection).
*/
function verifyTikTokShop(rawBody, authHeader, appKey, appSecret) {
const expected = crypto
.createHmac('sha256', appSecret)
.update(appKey + rawBody)
.digest('hex');
try {
return crypto.timingSafeEqual(
Buffer.from(authHeader || '', 'utf8'),
Buffer.from(expected, 'utf8')
);
} catch {
return false; // length mismatch = invalid
}
}
// Must use the raw body for signature verification — do not JSON.parse first.
app.post(
'/webhooks/tiktok-shop',
express.raw({ type: '*/*' }),
(req, res) => {
const authHeader = req.headers['authorization'];
if (!authHeader) {
return res.status(401).send('Missing Authorization header');
}
// req.body is a Buffer from express.raw(); sign the exact bytes as UTF-8.
const rawBody = req.body.toString('utf8');
if (!verifyTikTokShop(rawBody, authHeader, APP_KEY, APP_SECRET)) {
// TikTok Shop treats 401 as a rejected signature.
return res.status(401).send('Invalid signature');
}
let payload;
try {
payload = JSON.parse(rawBody);
} catch {
return res.status(400).send('Invalid JSON');
}
// Delivery is at-least-once: dedupe on tts_notification_id before processing.
// e.g. if (await seen(payload.tts_notification_id)) return res.status(200).send();
const eventName = SUBSCRIBED_TYPE_TO_EVENT[payload.type] || `UNKNOWN_TYPE_${payload.type}`;
switch (eventName) {
case 'ORDER_STATUS_CHANGE':
console.log('Order status changed:', payload.data?.order_id, payload.data?.order_status);
// Your code: sync order, trigger fulfilment, notify customer, etc.
break;
case 'RECIPIENT_ADDRESS_UPDATE':
console.log('Recipient address updated:', payload.data?.order_id);
// Your code: refresh shipping label / warehouse record.
break;
case 'PACKAGE_UPDATE':
console.log('Package updated:', payload.data?.package_id);
// Your code: re-fetch package details, update tracking.
break;
case 'PRODUCT_STATUS_CHANGE':
console.log('Product status changed:', payload.data?.product_id);
// Your code: sync catalog availability.
break;
case 'SELLER_DEAUTHORIZATION':
console.log('Seller deauthorized shop:', payload.shop_id);
// Your code: disable sync, purge stored access tokens for this shop.
break;
default:
console.log(`Unhandled event (type=${payload.type}): ${eventName}`);
}
// Acknowledge within 3 seconds: 200 with an empty body.
return res.status(200).send();
}
);
// Health check endpoint
app.get('/health', (req, res) => {
res.json({ status: 'ok' });
});
// Export app for testing
module.exports = app;
// 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/tiktok-shop`);
});
} // Generated with: tiktok-shop-webhooks skill
// https://github.com/hookdeck/webhook-skills
import { NextRequest, NextResponse } from 'next/server';
import crypto from 'crypto';
const APP_KEY = process.env.TIKTOK_SHOP_APP_KEY ?? '';
const APP_SECRET = process.env.TIKTOK_SHOP_APP_SECRET ?? '';
// TikTok Shop does NOT publish a complete numeric `type` -> topic mapping
// ("Do not branch only on the numeric type; use the subscribed event_type
// context" — official webhooks overview). Only `type: 1` appears in the
// official sample payload, for ORDER_STATUS_CHANGE. Fill this map from YOUR
// OWN Partner Center subscriptions — or better, register a distinct callback
// URL per event_type (the Update Shop Webhook API takes one address per
// topic) so the route itself identifies the event.
const SUBSCRIBED_TYPE_TO_EVENT: Record<number, string> = {
1: 'ORDER_STATUS_CHANGE', // per the official sample payload
};
/**
* Verify a TikTok Shop webhook signature.
*
* TikTok Shop signs: HMAC-SHA256(key = app_secret, message = app_key + rawBody),
* lowercase hex, delivered in the `Authorization` header (no "Bearer" prefix).
* There is no timestamp in the signature (no replay protection).
*/
export function verifyTikTokShop(
rawBody: string,
authHeader: string | null,
appKey: string,
appSecret: string
): boolean {
const expected = crypto
.createHmac('sha256', appSecret)
.update(appKey + rawBody)
.digest('hex');
try {
return crypto.timingSafeEqual(
Buffer.from(authHeader ?? '', 'utf8'),
Buffer.from(expected, 'utf8')
);
} catch {
return false; // length mismatch = invalid
}
}
export async function POST(request: NextRequest) {
// Read the raw body for signature verification — do not parse first.
const rawBody = await request.text();
const authHeader = request.headers.get('authorization');
if (!authHeader) {
return new NextResponse('Missing Authorization header', { status: 401 });
}
if (!verifyTikTokShop(rawBody, authHeader, APP_KEY, APP_SECRET)) {
// TikTok Shop treats 401 as a rejected signature.
return new NextResponse('Invalid signature', { status: 401 });
}
let payload: { type: number; tts_notification_id?: string; shop_id?: string; data?: Record<string, unknown> };
try {
payload = JSON.parse(rawBody);
} catch {
return new NextResponse('Invalid JSON', { status: 400 });
}
// Delivery is at-least-once: dedupe on tts_notification_id before processing.
const eventName = SUBSCRIBED_TYPE_TO_EVENT[payload.type] ?? `UNKNOWN_TYPE_${payload.type}`;
const data = payload.data ?? {};
switch (eventName) {
case 'ORDER_STATUS_CHANGE':
console.log('Order status changed:', data.order_id, data.order_status);
// Your code: sync order, trigger fulfilment, notify customer, etc.
break;
case 'RECIPIENT_ADDRESS_UPDATE':
console.log('Recipient address updated:', data.order_id);
// Your code: refresh shipping label / warehouse record.
break;
case 'PACKAGE_UPDATE':
console.log('Package updated:', data.package_id);
// Your code: re-fetch package details, update tracking.
break;
case 'PRODUCT_STATUS_CHANGE':
console.log('Product status changed:', data.product_id);
// Your code: sync catalog availability.
break;
case 'SELLER_DEAUTHORIZATION':
console.log('Seller deauthorized shop:', payload.shop_id);
// Your code: disable sync, purge stored access tokens for this shop.
break;
default:
console.log(`Unhandled event (type=${payload.type}): ${eventName}`);
}
// Acknowledge within 3 seconds: 200 with an empty body.
return new NextResponse(null, { status: 200 });
} # Generated with: tiktok-shop-webhooks skill
# https://github.com/hookdeck/webhook-skills
import hashlib
import hmac
import json
import os
from dotenv import load_dotenv
from fastapi import FastAPI, Request, Response
load_dotenv()
app = FastAPI()
APP_KEY = os.environ.get("TIKTOK_SHOP_APP_KEY", "")
APP_SECRET = os.environ.get("TIKTOK_SHOP_APP_SECRET", "")
# TikTok Shop does NOT publish a complete numeric `type` -> topic mapping
# ("Do not branch only on the numeric type; use the subscribed event_type
# context" -- official webhooks overview). Only `type: 1` appears in the
# official sample payload, for ORDER_STATUS_CHANGE. Fill this map from YOUR
# OWN Partner Center subscriptions -- or better, register a distinct callback
# URL per event_type (the Update Shop Webhook API takes one address per
# topic) so the route itself identifies the event.
SUBSCRIBED_TYPE_TO_EVENT = {
1: "ORDER_STATUS_CHANGE", # per the official sample payload
}
def verify_tiktok_shop(
raw_body: bytes, auth_header: str, app_key: str, app_secret: str
) -> bool:
"""Verify a TikTok Shop webhook signature.
TikTok Shop signs: HMAC-SHA256(key=app_secret, message=app_key + raw_body),
lowercase hex, delivered in the ``Authorization`` header (no "Bearer" prefix).
There is no timestamp in the signature (no replay protection).
"""
message = app_key.encode("utf-8") + raw_body # raw bytes, NOT parsed JSON
expected = hmac.new(
app_secret.encode("utf-8"), message, hashlib.sha256
).hexdigest()
return hmac.compare_digest(expected, auth_header or "")
@app.post("/webhooks/tiktok-shop")
async def tiktok_shop_webhook(request: Request):
# Read the raw body for signature verification — do not parse first.
raw_body = await request.body()
auth_header = request.headers.get("authorization")
if not auth_header:
# TikTok Shop treats 401 as a rejected signature.
return Response(status_code=401, content="Missing Authorization header")
if not verify_tiktok_shop(raw_body, auth_header, APP_KEY, APP_SECRET):
return Response(status_code=401, content="Invalid signature")
try:
payload = json.loads(raw_body)
except json.JSONDecodeError:
return Response(status_code=400, content="Invalid JSON")
# Delivery is at-least-once: dedupe on tts_notification_id before processing.
event_name = SUBSCRIBED_TYPE_TO_EVENT.get(payload.get("type"), f"UNKNOWN_TYPE_{payload.get('type')}")
data = payload.get("data") or {}
if event_name == "ORDER_STATUS_CHANGE":
print(f"Order status changed: {data.get('order_id')} {data.get('order_status')}")
# Your code: sync order, trigger fulfilment, notify customer, etc.
elif event_name == "RECIPIENT_ADDRESS_UPDATE":
print(f"Recipient address updated: {data.get('order_id')}")
# Your code: refresh shipping label / warehouse record.
elif event_name == "PACKAGE_UPDATE":
print(f"Package updated: {data.get('package_id')}")
# Your code: re-fetch package details, update tracking.
elif event_name == "PRODUCT_STATUS_CHANGE":
print(f"Product status changed: {data.get('product_id')}")
# Your code: sync catalog availability.
elif event_name == "SELLER_DEAUTHORIZATION":
print(f"Seller deauthorized shop: {payload.get('shop_id')}")
# Your code: disable sync, purge stored access tokens for this shop.
else:
print(f"Unhandled event (type={payload.get('type')}): {event_name}")
# Acknowledge within 3 seconds: 200 with an empty body.
return Response(status_code=200)
@app.get("/health")
async def health():
return {"status": "ok"}
if __name__ == "__main__":
import uvicorn
uvicorn.run(app, host="0.0.0.0", port=8000) Or install the TikTok Shop webhooks skill:
npx skills add hookdeck/webhook-skills --skill tiktok-shop-webhooks
Common failures
Body parsed before verification
TikTok warns that reformatting the body can change whitespace or field order and fail verification. Capture the raw bytes and verify before any body parser runs.
Signing the body alone
The signed content starts with your app key, with nothing between it and the body. Leave it out and every delivery fails.
Treating the header as a bearer token
The whole Authorization value is the digest. Auth middleware that expects Bearer rejects it before your check runs, so exclude the webhook route from that middleware.
Reusing your API request signing
The signature your app creates to call TikTok Shop's APIs is a different scheme. Code written for those calls won't produce this digest.
Let Event Gateway verify TikTok Shop signatures.
Event Gateway verifies the signature on each TikTok Shop delivery before it reaches your service, then queues it and retries failures on your schedule.