Verify Appstle Subscriptions webhooks
Appstle signs every delivery so you can tell it came from Appstle and wasn't changed in transit. The signature in svix-signature is a base64 HMAC-SHA256 of the svix-id header, the svix-timestamp header and the raw body, keyed with the decoded whsec_ secret of that endpoint. Appstle's docs show a hand-written verifier, and the svix libraries implement the same scheme.
The facts
svix-signature Format: v1,<base64>, space-separated when there are several
{svix-id}.{svix-timestamp}.{raw body} The two headers and the body as received, joined with periods.
Recompute the HMAC over the message id, timestamp and raw body with the base64-decoded secret, then compare with each v1 entry. Appstle Subscriptions webhook secret
Each endpoint has its own signing secret, shown in Appstle's webhook portal. It starts with whsec_. Keep it in an environment variable, not in source code.
- Where: in the Appstle dashboard, open Webhook Integration under More, click Launch webhook portal, and open your endpoint.
- Format: starts with
whsec_. A hand-written verifier removes that prefix and base64-decodes the rest to get the key. - One per endpoint: with several endpoints, use the secret of the endpoint that received the request.
- Rotating: Appstle doesn't document it.
svix-signaturecan hold more than one entry, so check them all.
Source: Appstle Subscriptions docs ↗
Code
// Generated with: appstle-webhooks skill
// https://github.com/hookdeck/webhook-skills
import { pathToFileURL } from 'node:url';
import dotenv from 'dotenv';
import express from 'express';
import { Webhook } from 'svix';
dotenv.config({ quiet: true });
export const app = express();
const PORT = process.env.PORT || 3000;
app.get('/health', (req, res) => {
res.json({ status: 'ok' });
});
// IMPORTANT: express.raw() keeps the exact bytes Appstle (Svix) signed, for any content type
app.post('/webhooks/appstle', express.raw({ type: '*/*' }), (req, res) => {
const secret = process.env.APPSTLE_WEBHOOK_SECRET;
if (!secret || !secret.startsWith('whsec_')) {
console.error('APPSTLE_WEBHOOK_SECRET is missing or not a whsec_ secret');
return res.status(500).json({ error: 'Server configuration error' });
}
const svixId = req.headers['svix-id'];
const svixTimestamp = req.headers['svix-timestamp'];
const svixSignature = req.headers['svix-signature'];
if (!svixId || !svixTimestamp || !svixSignature) {
return res.status(400).json({ error: 'Missing required webhook headers' });
}
try {
// Checks HMAC-SHA256 over `${svix-id}.${svix-timestamp}.${body}` against every
// v1, signature and enforces a fixed 5-minute timestamp window. Appstle's own
// retries carry a new timestamp, but Hookdeck retries and replays keep the original,
// so see references/verification.md for a manual verifier with no window.
new Webhook(secret).verify(req.body, {
'svix-id': svixId,
'svix-timestamp': svixTimestamp,
'svix-signature': svixSignature,
});
} catch (err) {
console.error('Appstle webhook verification failed:', err.message);
const error = /timestamp/i.test(err.message) ? 'Timestamp too old' : 'Invalid signature';
return res.status(400).json({ error });
}
let event;
try {
event = JSON.parse(req.body.toString('utf8'));
} catch {
return res.status(400).json({ error: 'Invalid JSON' });
}
// Envelope: { "type": "subscription.created", "data": { ... } }
const { type, data = {} } = event ?? {};
// svix-id is stable across retries: use it to deduplicate
console.log(`Received Appstle webhook ${svixId}: ${type}`);
switch (type) {
case 'subscription.created':
console.log('Subscription created:', data.id, data.customer?.email);
break;
case 'subscription.updated':
console.log('Subscription updated:', data.id);
break;
case 'subscription.activated':
console.log('Subscription activated:', data.id);
break;
case 'subscription.paused':
console.log('Subscription paused:', data.id);
break;
case 'subscription.cancelled':
console.log('Subscription cancelled:', data.id);
break;
case 'subscription.next-order-date-changed':
console.log('Next order date changed:', data.id, data.nextBillingDate);
break;
case 'subscription.billing-interval-changed':
console.log('Billing interval changed:', data.id, data.billingPolicy);
break;
case 'subscription.billing-success':
console.log('Billing succeeded for contract', data.contractId, 'order', data.orderName);
break;
case 'subscription.billing-failure':
console.log('Billing failed for contract', data.contractId, data.billingAttemptResponseMessage);
break;
case 'subscription.billing-skipped':
console.log('Billing skipped for contract', data.contractId);
break;
case 'subscription.upcoming-order-notification':
console.log('Upcoming order notification for contract', data.contractId);
break;
default:
console.log('Unhandled event type:', type);
}
res.status(200).json({ success: true, type });
});
// Start the server only when run directly (not when imported by tests)
if (import.meta.url === pathToFileURL(process.argv[1]).href) {
app.listen(PORT, () => {
console.log(`Appstle webhook server running on http://localhost:${PORT}/webhooks/appstle`);
});
} // Generated with: appstle-webhooks skill
// https://github.com/hookdeck/webhook-skills
import { NextResponse } from 'next/server';
import { Webhook } from 'svix';
export const dynamic = 'force-dynamic';
export async function POST(request: Request) {
const secret = process.env.APPSTLE_WEBHOOK_SECRET;
if (!secret || !secret.startsWith('whsec_')) {
console.error('APPSTLE_WEBHOOK_SECRET is missing or not a whsec_ secret');
return NextResponse.json({ error: 'Server configuration error' }, { status: 500 });
}
const svixId = request.headers.get('svix-id');
const svixTimestamp = request.headers.get('svix-timestamp');
const svixSignature = request.headers.get('svix-signature');
if (!svixId || !svixTimestamp || !svixSignature) {
return NextResponse.json({ error: 'Missing required webhook headers' }, { status: 400 });
}
// Read the RAW body: verification needs the exact bytes Appstle (Svix) signed
const rawBody = await request.text();
try {
// Checks HMAC-SHA256 over `${svix-id}.${svix-timestamp}.${body}` against every
// v1, signature and enforces a fixed 5-minute timestamp window. Appstle's own
// retries carry a new timestamp, but Hookdeck retries and replays keep the original,
// so see references/verification.md for a manual verifier with no window.
new Webhook(secret).verify(rawBody, {
'svix-id': svixId,
'svix-timestamp': svixTimestamp,
'svix-signature': svixSignature,
});
} catch (err) {
const message = err instanceof Error ? err.message : String(err);
console.error('Appstle webhook verification failed:', message);
const error = /timestamp/i.test(message) ? 'Timestamp too old' : 'Invalid signature';
return NextResponse.json({ error }, { status: 400 });
}
let event: { type?: string; data?: Record<string, any> };
try {
event = JSON.parse(rawBody);
} catch {
return NextResponse.json({ error: 'Invalid JSON' }, { status: 400 });
}
// Envelope: { "type": "subscription.created", "data": { ... } }
const type = event?.type;
const data = event?.data ?? {};
// svix-id is stable across retries: use it to deduplicate
console.log(`Received Appstle webhook ${svixId}: ${type}`);
switch (type) {
case 'subscription.created':
console.log('Subscription created:', data.id, data.customer?.email);
break;
case 'subscription.updated':
console.log('Subscription updated:', data.id);
break;
case 'subscription.activated':
console.log('Subscription activated:', data.id);
break;
case 'subscription.paused':
console.log('Subscription paused:', data.id);
break;
case 'subscription.cancelled':
console.log('Subscription cancelled:', data.id);
break;
case 'subscription.next-order-date-changed':
console.log('Next order date changed:', data.id, data.nextBillingDate);
break;
case 'subscription.billing-interval-changed':
console.log('Billing interval changed:', data.id, data.billingPolicy);
break;
case 'subscription.billing-success':
console.log('Billing succeeded for contract', data.contractId, 'order', data.orderName);
break;
case 'subscription.billing-failure':
console.log('Billing failed for contract', data.contractId, data.billingAttemptResponseMessage);
break;
case 'subscription.billing-skipped':
console.log('Billing skipped for contract', data.contractId);
break;
case 'subscription.upcoming-order-notification':
console.log('Upcoming order notification for contract', data.contractId);
break;
default:
console.log('Unhandled event type:', type);
}
return NextResponse.json({ success: true, type });
} # Generated with: appstle-webhooks skill
# https://github.com/hookdeck/webhook-skills
import json
import os
from typing import Optional
from dotenv import load_dotenv
from fastapi import FastAPI, Header, HTTPException, Request
from svix.webhooks import Webhook, WebhookVerificationError
load_dotenv()
app = FastAPI(title="Appstle Webhook Handler")
@app.get("/health")
async def health_check():
return {"status": "ok"}
@app.post("/webhooks/appstle")
async def appstle_webhook(
request: Request,
svix_id: Optional[str] = Header(None),
svix_timestamp: Optional[str] = Header(None),
svix_signature: Optional[str] = Header(None),
):
secret = os.environ.get("APPSTLE_WEBHOOK_SECRET")
if not secret or not secret.startswith("whsec_"):
print("APPSTLE_WEBHOOK_SECRET is missing or not a whsec_ secret")
raise HTTPException(status_code=500, detail="Server configuration error")
if not (svix_id and svix_timestamp and svix_signature):
raise HTTPException(status_code=400, detail="Missing required webhook headers")
# Verify the RAW body: the exact bytes Appstle (Svix) signed
raw_body = await request.body()
try:
# Checks HMAC-SHA256 over "{svix-id}.{svix-timestamp}.{body}" against every
# v1, signature and enforces a fixed 5-minute timestamp window. Appstle's own
# retries carry a new timestamp, but Hookdeck retries and replays keep the original,
# so see references/verification.md for a manual verifier with no window.
Webhook(secret).verify(
raw_body,
{
"svix-id": svix_id,
"svix-timestamp": svix_timestamp,
"svix-signature": svix_signature,
},
)
except WebhookVerificationError as err:
print(f"Appstle webhook verification failed: {err}")
detail = "Timestamp too old" if "timestamp" in str(err).lower() else "Invalid signature"
raise HTTPException(status_code=400, detail=detail)
try:
event = json.loads(raw_body)
except json.JSONDecodeError:
raise HTTPException(status_code=400, detail="Invalid JSON")
# Envelope: {"type": "subscription.created", "data": {...}}
event_type = event.get("type") if isinstance(event, dict) else None
data = (event.get("data") if isinstance(event, dict) else None) or {}
# svix-id is stable across retries: use it to deduplicate
print(f"Received Appstle webhook {svix_id}: {event_type}")
if event_type == "subscription.created":
print(f"Subscription created: {data.get('id')} {data.get('customer', {}).get('email')}")
elif event_type == "subscription.updated":
print(f"Subscription updated: {data.get('id')}")
elif event_type == "subscription.activated":
print(f"Subscription activated: {data.get('id')}")
elif event_type == "subscription.paused":
print(f"Subscription paused: {data.get('id')}")
elif event_type == "subscription.cancelled":
print(f"Subscription cancelled: {data.get('id')}")
elif event_type == "subscription.next-order-date-changed":
print(f"Next order date changed: {data.get('id')} {data.get('nextBillingDate')}")
elif event_type == "subscription.billing-interval-changed":
print(f"Billing interval changed: {data.get('id')} {data.get('billingPolicy')}")
elif event_type == "subscription.billing-success":
print(f"Billing succeeded for contract {data.get('contractId')} order {data.get('orderName')}")
elif event_type == "subscription.billing-failure":
print(f"Billing failed for contract {data.get('contractId')}: {data.get('billingAttemptResponseMessage')}")
elif event_type == "subscription.billing-skipped":
print(f"Billing skipped for contract {data.get('contractId')}")
elif event_type == "subscription.upcoming-order-notification":
print(f"Upcoming order notification for contract {data.get('contractId')}")
else:
print(f"Unhandled event type: {event_type}")
return {"success": True, "type": event_type}
if __name__ == "__main__":
import uvicorn
uvicorn.run(app, host="0.0.0.0", port=8000) Or install the Appstle Subscriptions webhooks skill:
npx skills add hookdeck/webhook-skills --skill appstle-webhooks
Common failures
Body parsed before verification
Parsing and serialising again can change the bytes, for example 15.0 becomes 15. In Express, use express.raw() on the webhook route and register it before any app-wide express.json().
Wrong endpoint's secret
Each endpoint has its own signing secret in the webhook portal. Use the one for the endpoint that received the request.
Secret not decoded
In a hand-written verifier, the HMAC key is the base64-decoded part of the secret after whsec_, not the string as shown.
Delivery checked late
Appstle tells you to reject a svix-timestamp more than five minutes from your clock. Its own retries carry a new timestamp, but a message that waits in your queue, or is replayed through a relay, keeps the old one, so a hand-written verifier may need to widen that check.
Let Event Gateway verify Appstle Subscriptions signatures.
Event Gateway verifies the signature on each Appstle Subscriptions delivery before it reaches your service, then queues it and retries failures on your schedule.