Verify Paddle webhooks
Every Paddle Billing webhook carries a Paddle-Signature header, so you can confirm that it came from Paddle and wasn't changed on the way. The header holds a timestamp and an HMAC-SHA256 of that timestamp and the raw body, joined by a colon and keyed with the notification destination's secret key. Paddle's official Node.js, Python, Go and PHP SDKs verify it for you.
These pages cover Paddle Billing, which everyone who signed up after 8 August 2023 has. Paddle Classic is a separate legacy product that verifies webhooks differently, with a `p_signature` body field and a public key.
The facts
{ts}:{raw body} ts from the Paddle-Signature header, a literal colon, then the request body exactly as sent.
5 seconds The default tolerance in Paddle's SDKs. If you verify manually the check is optional.
Paddle webhook secret
Each notification destination has its own secret key. It isn't your API key. Keep it in an environment variable, not in source code.
- In the dashboard: go to Paddle > Events > Notifications, choose Edit destination from the menu beside the destination, and copy the secret key.
- From the API:
GET /notification-settings/{notification_setting_id}returns it asendpoint_secret_key, and so does the response when you create a destination. - One per destination: with several destinations, you need the key for each one you verify.
- Format: the documented example starts with
pdl_ntfset_. - Sandbox and live: they are separate accounts, and notification destinations aren't shared between them, so each has its own keys.
- Rotation: Paddle says it may add secret rotation in the future. When it does, a header can carry more than one
h1.
Source: Paddle docs ↗
Code
require('dotenv').config();
const express = require('express');
const crypto = require('crypto');
const { Paddle } = require('@paddle/paddle-node-sdk');
const app = express();
// Initialize Paddle SDK if API key is available
const paddle = process.env.PADDLE_API_KEY ? new Paddle(process.env.PADDLE_API_KEY) : null;
/**
* Verify Paddle webhook signature
* @param {string} payload - Raw request body as string
* @param {string} signatureHeader - Paddle-Signature header value
* @param {string} secret - Webhook secret key
* @returns {boolean} - Whether signature is valid
*/
function verifyPaddleSignature(payload, signatureHeader, secret) {
if (!signatureHeader) {
return false;
}
try {
// Parse the signature header (format: ts=1234567890;h1=abc123...)
const parts = signatureHeader.split(';');
const timestamp = parts.find(p => p.startsWith('ts='))?.slice(3);
const signatures = parts
.filter(p => p.startsWith('h1='))
.map(p => p.slice(3));
if (!timestamp || signatures.length === 0) {
return false;
}
// Build the signed payload (timestamp:rawBody)
const signedPayload = `${timestamp}:${payload}`;
// Compute the expected signature
const expectedSignature = crypto
.createHmac('sha256', secret)
.update(signedPayload)
.digest('hex');
// Check if any signature matches (handles secret rotation)
return signatures.some(sig => {
try {
return crypto.timingSafeEqual(
Buffer.from(sig),
Buffer.from(expectedSignature)
);
} catch {
return false;
}
});
} catch (err) {
console.error('Error verifying signature:', err);
return false;
}
}
// Paddle webhook endpoint - must use raw body for signature verification
app.post('/webhooks/paddle',
express.raw({ type: 'application/json' }),
async (req, res) => {
const signatureHeader = req.headers['paddle-signature'];
const payload = req.body.toString();
const secret = process.env.PADDLE_WEBHOOK_SECRET;
// Option 1: Verify using Paddle SDK (recommended if you have SDK initialized)
let event;
if (paddle) {
try {
// The SDK handles verification and parsing in one step
// Method signature: paddle.webhooks.unmarshal(requestBody, secretKey, signature)
event = await paddle.webhooks.unmarshal(payload, secret, signatureHeader);
console.log('Webhook verified using Paddle SDK');
} catch (err) {
console.error('SDK webhook verification failed:', err.message);
return res.status(400).send('Invalid signature');
}
} else {
// Option 2: Manual verification (when SDK is not available)
const isValid = verifyPaddleSignature(payload, signatureHeader, secret);
if (!isValid) {
console.error('Manual webhook signature verification failed');
return res.status(400).send('Invalid signature');
}
// Parse the event
try {
event = JSON.parse(payload);
console.log('Webhook verified using manual verification');
} catch (err) {
console.error('Failed to parse webhook payload:', err);
return res.status(400).send('Invalid JSON');
}
}
// Handle the event based on type
switch (event.event_type) {
case 'subscription.created':
const newSub = event.data;
console.log('Subscription created:', newSub.id);
// Your code: Provision access, send welcome email, etc.
break;
case 'subscription.activated':
const activeSub = event.data;
console.log('Subscription activated:', activeSub.id);
// Your code: Grant full access after first payment
break;
case 'subscription.canceled':
const canceledSub = event.data;
console.log('Subscription canceled:', canceledSub.id);
// Your code: Revoke access, send retention email, etc.
break;
case 'subscription.paused':
const pausedSub = event.data;
console.log('Subscription paused:', pausedSub.id);
// Your code: Limit access, send pause confirmation
break;
case 'subscription.resumed':
const resumedSub = event.data;
console.log('Subscription resumed:', resumedSub.id);
// Your code: Restore access, send welcome back email
break;
case 'transaction.completed':
const transaction = event.data;
console.log('Transaction completed:', transaction.id);
// Your code: Fulfill order, send receipt, etc.
break;
case 'transaction.payment_failed':
const failedTx = event.data;
console.log('Transaction payment failed:', failedTx.id);
// Your code: Notify customer, update status, etc.
break;
case 'customer.created':
const newCustomer = event.data;
console.log('Customer created:', newCustomer.id);
// Your code: Create customer record, send welcome email, etc.
break;
case 'customer.updated':
const updatedCustomer = event.data;
console.log('Customer updated:', updatedCustomer.id);
// Your code: Update customer record, sync changes, etc.
break;
default:
console.log(`Unhandled event type: ${event.event_type}`);
}
// Return 200 to acknowledge receipt (respond within 5 seconds)
res.json({ received: true });
}
);
// Health check endpoint
app.get('/health', (req, res) => {
res.json({ status: 'ok' });
});
// Export app for testing
module.exports = { app, verifyPaddleSignature };
// 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/paddle`);
});
} import { NextRequest, NextResponse } from 'next/server';
import crypto from 'crypto';
import { Paddle } from '@paddle/paddle-node-sdk';
// Initialize Paddle SDK if API key is available
const paddle = process.env.PADDLE_API_KEY ? new Paddle(process.env.PADDLE_API_KEY) : null;
/**
* Verify Paddle webhook signature
*/
function verifyPaddleSignature(
payload: string,
signatureHeader: string | null,
secret: string
): boolean {
if (!signatureHeader) {
return false;
}
try {
// Parse the signature header (format: ts=1234567890;h1=abc123...)
const parts = signatureHeader.split(';');
const timestamp = parts.find(p => p.startsWith('ts='))?.slice(3);
const signatures = parts
.filter(p => p.startsWith('h1='))
.map(p => p.slice(3));
if (!timestamp || signatures.length === 0) {
return false;
}
// Build the signed payload (timestamp:rawBody)
const signedPayload = `${timestamp}:${payload}`;
// Compute the expected signature
const expectedSignature = crypto
.createHmac('sha256', secret)
.update(signedPayload)
.digest('hex');
// Check if any signature matches (handles secret rotation)
return signatures.some(sig => {
try {
return crypto.timingSafeEqual(
Buffer.from(sig),
Buffer.from(expectedSignature)
);
} catch {
return false;
}
});
} catch (err) {
console.error('Error verifying signature:', err);
return false;
}
}
export async function POST(request: NextRequest) {
// Get the raw body for signature verification
const body = await request.text();
const signatureHeader = request.headers.get('paddle-signature');
const secret = process.env.PADDLE_WEBHOOK_SECRET!;
// Parse the event
let event: {
event_id: string;
event_type: string;
occurred_at: string;
data: Record<string, unknown>;
};
// Option 1: Verify using Paddle SDK (recommended if you have SDK initialized)
if (paddle && signatureHeader) {
try {
// The SDK handles verification and parsing in one step
// Method signature: paddle.webhooks.unmarshal(requestBody, secretKey, signature)
const sdkEvent = await paddle.webhooks.unmarshal(body, secret, signatureHeader);
event = {
event_id: sdkEvent.eventId,
event_type: sdkEvent.eventType,
occurred_at: sdkEvent.occurredAt,
data: sdkEvent.data as Record<string, unknown>,
};
console.log('Webhook verified using Paddle SDK');
} catch (err) {
console.error('SDK webhook verification failed:', err);
return NextResponse.json(
{ error: 'Invalid signature' },
{ status: 400 }
);
}
} else {
// Option 2: Manual verification (when SDK is not available)
const isValid = verifyPaddleSignature(body, signatureHeader, secret);
if (!isValid) {
console.error('Manual webhook signature verification failed');
return NextResponse.json(
{ error: 'Invalid signature' },
{ status: 400 }
);
}
// Parse the event
try {
event = JSON.parse(body);
console.log('Webhook verified using manual verification');
} catch (err) {
console.error('Failed to parse webhook payload:', err);
return NextResponse.json(
{ error: 'Invalid JSON' },
{ status: 400 }
);
}
}
// Handle the event based on type
switch (event.event_type) {
case 'subscription.created':
console.log('Subscription created:', event.data.id);
// Your code: Provision access, send welcome email, etc.
break;
case 'subscription.activated':
console.log('Subscription activated:', event.data.id);
// Your code: Grant full access after first payment
break;
case 'subscription.canceled':
console.log('Subscription canceled:', event.data.id);
// Your code: Revoke access, send retention email, etc.
break;
case 'subscription.paused':
console.log('Subscription paused:', event.data.id);
// Your code: Limit access, send pause confirmation
break;
case 'subscription.resumed':
console.log('Subscription resumed:', event.data.id);
// Your code: Restore access, send welcome back email
break;
case 'transaction.completed':
console.log('Transaction completed:', event.data.id);
// Your code: Fulfill order, send receipt, etc.
break;
case 'transaction.payment_failed':
console.log('Transaction payment failed:', event.data.id);
// Your code: Notify customer, update status, etc.
break;
case 'customer.created':
console.log('Customer created:', event.data.id);
// Your code: Create customer record, send welcome email, etc.
break;
case 'customer.updated':
console.log('Customer updated:', event.data.id);
// Your code: Update customer record, sync changes, etc.
break;
default:
console.log(`Unhandled event type: ${event.event_type}`);
}
// Return 200 to acknowledge receipt (respond within 5 seconds)
return NextResponse.json({ received: true });
} import os
import hmac
import hashlib
from dotenv import load_dotenv
from fastapi import FastAPI, Request, HTTPException
load_dotenv()
app = FastAPI()
webhook_secret = os.environ.get("PADDLE_WEBHOOK_SECRET")
# Note: paddle-python-sdk's Verifier targets Flask/Django request objects,
# so FastAPI users should verify manually.
def verify_paddle_signature(payload: str, signature_header: str, secret: str) -> bool:
"""
Verify Paddle webhook signature.
Args:
payload: Raw request body as string
signature_header: Paddle-Signature header value
secret: Webhook secret key
Returns:
bool: Whether signature is valid
"""
if not signature_header:
return False
try:
# Parse the signature header (format: ts=1234567890;h1=abc123...)
parts = signature_header.split(";")
timestamp = None
signatures = []
for part in parts:
if part.startswith("ts="):
timestamp = part[3:]
elif part.startswith("h1="):
signatures.append(part[3:])
if not timestamp or not signatures:
return False
# Build the signed payload (timestamp:rawBody)
signed_payload = f"{timestamp}:{payload}"
# Compute the expected signature
expected_signature = hmac.new(
secret.encode(), signed_payload.encode(), hashlib.sha256
).hexdigest()
# Check if any signature matches (handles secret rotation)
return any(hmac.compare_digest(sig, expected_signature) for sig in signatures)
except Exception as e:
print(f"Error verifying signature: {e}")
return False
@app.post("/webhooks/paddle")
async def paddle_webhook(request: Request):
# Get the raw body for signature verification
payload = await request.body()
payload_str = payload.decode()
signature_header = request.headers.get("paddle-signature")
if not signature_header:
raise HTTPException(status_code=400, detail="Missing Paddle-Signature header")
if not verify_paddle_signature(payload_str, signature_header, webhook_secret):
print("Webhook signature verification failed")
raise HTTPException(status_code=400, detail="Invalid signature")
# Parse the event
try:
event = await request.json()
except Exception as e:
print(f"Failed to parse webhook payload: {e}")
raise HTTPException(status_code=400, detail="Invalid JSON")
# Handle the event based on type
event_type = event.get("event_type")
data = event.get("data", {})
if event_type == "subscription.created":
print(f"Subscription created: {data.get('id')}")
# Your code: Provision access, send welcome email, etc.
elif event_type == "subscription.activated":
print(f"Subscription activated: {data.get('id')}")
# Your code: Grant full access after first payment
elif event_type == "subscription.canceled":
print(f"Subscription canceled: {data.get('id')}")
# Your code: Revoke access, send retention email, etc.
elif event_type == "subscription.paused":
print(f"Subscription paused: {data.get('id')}")
# Your code: Limit access, send pause confirmation
elif event_type == "subscription.resumed":
print(f"Subscription resumed: {data.get('id')}")
# Your code: Restore access, send welcome back email
elif event_type == "transaction.completed":
print(f"Transaction completed: {data.get('id')}")
# Your code: Fulfill order, send receipt, etc.
elif event_type == "transaction.payment_failed":
print(f"Transaction payment failed: {data.get('id')}")
# Your code: Notify customer, update status, etc.
elif event_type == "customer.created":
print(f"Customer created: {data.get('id')}")
# Your code: Create customer record, send welcome email, etc.
elif event_type == "customer.updated":
print(f"Customer updated: {data.get('id')}")
# Your code: Update customer record, sync changes, etc.
else:
print(f"Unhandled event type: {event_type}")
# Return 200 to acknowledge receipt (respond within 5 seconds)
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 Paddle webhooks skill:
npx skills add hookdeck/webhook-skills --skill paddle-webhooks
Common failures
Body changed before verification
Parsing the JSON, adding whitespace or reformatting the body changes the signed payload. Verify against the raw request body, before any parsing.
Wrong secret key
Use the secret key of the notification destination that sent the event, not an API key. Each destination has its own, and sandbox and live are separate accounts.
Five-second tolerance
Paddle's SDKs reject a timestamp more than five seconds from the current time by default. Keep server clocks in sync with NTP.
Header parsed too strictly
A Paddle-Signature header contains at least one h1, and more than one while a secret is rotated out. Compare against every h1, not only the first.
Let Event Gateway verify Paddle signatures.
Event Gateway verifies the signature on each Paddle delivery before it reaches your service, then queues it and retries failures on your schedule.