Verify YouCanBookMe webhooks
YouCanBookMe webhooks carry no signature, timestamp or signing secret, so there's no SDK to verify them. The check available is a request header you add to each webhook action, with a long random value your endpoint compares in full and in constant time. It shows the sender knows the secret, but it doesn't cover the body or stop a replay.
The facts
YouCanBookMe webhook secret
YouCanBookMe doesn't issue a secret. The booking-page owner chooses a header name and value in the webhook's request headers. Keep it in an environment variable, not in source code.
- Add the header as a key and value pair on the webhook action. Use a long random value.
- The action is complete without it, and the docs tell anyone unsure to leave it blank, so check every action has it.
- Each webhook action has its own header, so a secret isn't shared between triggers or booking pages.
- No rotation process is documented. Change the value on every action and on your endpoint together.
Source: YouCanBookMe docs ↗
Code
// Generated with: youcanbookme-webhooks skill
// https://github.com/hookdeck/webhook-skills
require('dotenv').config({ quiet: true });
const crypto = require('crypto');
const express = require('express');
const app = express();
// Hashing both sides gives equal-length buffers, so timingSafeEqual never throws.
const sha256 = (v) => crypto.createHash('sha256').update(String(v)).digest();
/**
* YouCanBookMe does not sign payloads. You add a secret Request Header (name and value of your
* choosing) to the webhook action; compare the WHOLE header value, case-insensitive name.
* A static credential authenticates the sender, not the body, and gives no replay protection.
*/
function verifyYoucanbookmeRequest(headers, {
headerName = process.env.YOUCANBOOKME_WEBHOOK_HEADER || 'Authorization',
secret = process.env.YOUCANBOOKME_WEBHOOK_SECRET,
} = {}) {
if (!secret) return false; // never accept when unconfigured
const received = headers[headerName.toLowerCase()]; // Node lowercases header names
return Boolean(received) && crypto.timingSafeEqual(sha256(received), sha256(secret));
}
// The body is the owner's template, so `event` is whatever the template names.
function handleEvent(payload) {
const { event } = payload;
switch (event) {
case 'booking_made':
console.log(`Booking made: ${payload.email}`);
// Your code: create the CRM contact or calendar entry
break;
case 'booking_rescheduled':
console.log(`Booking rescheduled: ${payload.email}`);
// Your code: move the matching record
break;
case 'booking_cancelled':
console.log(`Booking cancelled: ${payload.email}`);
// Your code: cancel downstream work
break;
case 'reminder':
console.log(`Reminder: ${payload.email}`);
// Your code: send a nudge
break;
case 'follow_up':
console.log(`Follow-up: ${payload.email}`);
// Your code: trigger a survey or thank-you
break;
case 'no_show':
console.log(`No-show: ${payload.email}`);
// Your code: flag the contact
break;
default:
console.log(`Unhandled event: ${event}`);
}
}
// The method is user-chosen in YouCanBookMe, so accept all of these.
// Read the body raw (any content type) so the request is authenticated before parsing.
function webhookHandler(req, res) {
if (!verifyYoucanbookmeRequest(req.headers)) {
return res.status(401).json({ error: 'Invalid or missing webhook header' });
}
const raw = Buffer.isBuffer(req.body) ? req.body.toString('utf8') : '';
// An empty body (e.g. GET) is valid: acknowledge it.
if (raw.trim() === '') {
return res.status(200).json({ received: true });
}
let payload;
try {
payload = JSON.parse(raw);
} catch {
return res.status(400).json({ error: 'Invalid JSON body' });
}
if (!payload || typeof payload !== 'object' || Array.isArray(payload)) {
return res.status(400).json({ error: 'Expected a JSON object' });
}
try {
handleEvent(payload);
} catch (err) {
console.error('Error handling YouCanBookMe event:', err);
return res.status(500).json({ error: 'Handler error' });
}
res.status(200).json({ received: true });
}
for (const method of ['post', 'put', 'patch', 'delete', 'get']) {
app[method]('/webhooks/youcanbookme', express.raw({ type: '*/*' }), webhookHandler);
}
app.get('/health', (req, res) => {
res.json({ status: 'ok' });
});
module.exports = app;
module.exports.verifyYoucanbookmeRequest = verifyYoucanbookmeRequest;
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: http://localhost:${PORT}/webhooks/youcanbookme`);
});
} // Generated with: youcanbookme-webhooks skill
// https://github.com/hookdeck/webhook-skills
import { NextRequest, NextResponse } from 'next/server';
import { verifyYoucanbookmeRequest } from '../../../lib/verify-youcanbookme';
// The body is the owner's template, so `event` is whatever the template names.
interface YoucanbookmePayload {
event?: string;
email?: string;
[key: string]: unknown;
}
function handleEvent(payload: YoucanbookmePayload): void {
const { event } = payload;
switch (event) {
case 'booking_made':
console.log(`Booking made: ${payload.email}`);
// Your code: create the CRM contact or calendar entry
break;
case 'booking_rescheduled':
console.log(`Booking rescheduled: ${payload.email}`);
// Your code: move the matching record
break;
case 'booking_cancelled':
console.log(`Booking cancelled: ${payload.email}`);
// Your code: cancel downstream work
break;
case 'reminder':
console.log(`Reminder: ${payload.email}`);
// Your code: send a nudge
break;
case 'follow_up':
console.log(`Follow-up: ${payload.email}`);
// Your code: trigger a survey or thank-you
break;
case 'no_show':
console.log(`No-show: ${payload.email}`);
// Your code: flag the contact
break;
default:
console.log(`Unhandled event: ${event}`);
}
}
async function handler(request: NextRequest) {
// Authenticate before reading or parsing the body.
if (!verifyYoucanbookmeRequest(request.headers)) {
return NextResponse.json({ error: 'Invalid or missing webhook header' }, { status: 401 });
}
// Read as text so any content type is accepted; an empty body (e.g. GET) is valid.
const raw = await request.text();
if (raw.trim() === '') {
return NextResponse.json({ received: true });
}
let payload: unknown;
try {
payload = JSON.parse(raw);
} catch {
return NextResponse.json({ error: 'Invalid JSON body' }, { status: 400 });
}
if (!payload || typeof payload !== 'object' || Array.isArray(payload)) {
return NextResponse.json({ error: 'Expected a JSON object' }, { status: 400 });
}
try {
handleEvent(payload as YoucanbookmePayload);
} catch (err) {
console.error('Error handling YouCanBookMe event:', err);
return NextResponse.json({ error: 'Handler error' }, { status: 500 });
}
return NextResponse.json({ received: true });
}
// The method is user-chosen in YouCanBookMe, so accept all of these.
export {
handler as POST,
handler as PUT,
handler as PATCH,
handler as DELETE,
handler as GET,
}; # Generated with: youcanbookme-webhooks skill
# https://github.com/hookdeck/webhook-skills
import hashlib
import hmac
import json
import os
from dotenv import load_dotenv
from fastapi import Depends, FastAPI, HTTPException, Request
load_dotenv()
app = FastAPI()
def safe_equal(a: str, b: str) -> bool:
"""Constant-time comparison on bytes (compare_digest raises TypeError on non-ASCII str)."""
return hmac.compare_digest(
hashlib.sha256(a.encode("utf-8")).digest(),
hashlib.sha256(b.encode("utf-8")).digest(),
)
def verify_youcanbookme_request(headers, secret=None, header_name=None) -> bool:
"""YouCanBookMe does not sign payloads. You add a secret Request Header (name and value of
your choosing) to the webhook action; compare the WHOLE header value. Starlette headers are
case-insensitive. A static credential authenticates the sender, not the body, and gives no
replay protection.
"""
secret = secret if secret is not None else os.environ.get("YOUCANBOOKME_WEBHOOK_SECRET")
header_name = (
header_name or os.environ.get("YOUCANBOOKME_WEBHOOK_HEADER") or "Authorization"
)
if not secret:
return False # never accept when unconfigured
received = headers.get(header_name)
return bool(received) and safe_equal(received, secret)
async def require_youcanbookme_header(request: Request) -> None:
"""FastAPI dependency: reject the request before the body is parsed."""
if not verify_youcanbookme_request(request.headers):
raise HTTPException(status_code=401, detail="Invalid or missing webhook header")
def handle_event(payload: dict) -> None:
# The body is the owner's template, so `event` is whatever the template names.
event = payload.get("event")
email = payload.get("email")
if event == "booking_made":
print(f"Booking made: {email}")
# Your code: create the CRM contact or calendar entry
elif event == "booking_rescheduled":
print(f"Booking rescheduled: {email}")
# Your code: move the matching record
elif event == "booking_cancelled":
print(f"Booking cancelled: {email}")
# Your code: cancel downstream work
elif event == "reminder":
print(f"Reminder: {email}")
# Your code: send a nudge
elif event == "follow_up":
print(f"Follow-up: {email}")
# Your code: trigger a survey or thank-you
elif event == "no_show":
print(f"No-show: {email}")
# Your code: flag the contact
else:
print(f"Unhandled event: {event}")
# The method is user-chosen in YouCanBookMe, so accept all of these.
@app.api_route(
"/webhooks/youcanbookme",
methods=["POST", "PUT", "PATCH", "DELETE", "GET"],
dependencies=[Depends(require_youcanbookme_header)],
)
async def youcanbookme_webhook(request: Request):
# Read the raw body so any content type is accepted; an empty body (e.g. GET) is valid.
raw_body = await request.body()
if not raw_body.strip():
return {"received": True}
try:
payload = json.loads(raw_body)
except (json.JSONDecodeError, UnicodeDecodeError):
raise HTTPException(status_code=400, detail="Invalid JSON body")
if not isinstance(payload, dict):
raise HTTPException(status_code=400, detail="Expected a JSON object")
try:
handle_event(payload)
except Exception as err: # noqa: BLE001
print(f"Error handling YouCanBookMe event: {err}")
raise HTTPException(status_code=500, detail="Handler error")
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=8000) Or install the YouCanBookMe webhooks skill:
npx skills add hookdeck/webhook-skills --skill youcanbookme-webhooks
Common failures
Header missing from one action
Each webhook action has its own headers, and YouCanBookMe saves an action without one. A new trigger or booking page fails until you add the header there too.
Value changed in only some places
When you change the secret, update every webhook action and your endpoint together. An action you missed keeps sending the old value.
Prefix left out of the comparison
Compare the whole header value. If you typed Bearer abc as the value, the value to compare is Bearer abc.
Header name mismatch
You choose the name on the action, so your endpoint has to read the same one. Header names are case-insensitive.
Let Event Gateway check your YouCanBookMe header.
Event Gateway compares the header you name with the exact value you enter on each YouCanBookMe request. A request that doesn't match still gets a 200, but it's recorded as failed verification and creates no event. The rest are queued and retried on your schedule.