Verify Yousign webhooks
Yousign signs each delivery so you can confirm that it came from Yousign and wasn't changed on the way. X-Yousign-Signature-256 holds sha256= followed by the hex HMAC-SHA256 of the raw request body, keyed with the subscription's secret key. No timestamp is signed, and Yousign's docs show the check in PHP, Node.js, Python and Java rather than offering an SDK for it.
The facts
{raw body} The request body exactly as sent, with no timestamp. x-yousign-issued-at is outside the signature, and the body's event_time stays the same through retries.
Yousign webhook secret
Each webhook subscription has its own secret key, shown when you view the subscription. It isn't your API key. Keep it in an environment variable, not in source code.
- In the app: go to API > Webhooks and view the subscription.
- From the API: a webhook subscription includes
secret_key, which is autogenerated at 32 bytes. The create request also has a 32-charactersecret_keyfield. - One per subscription: a subscription belongs to one environment, so sandbox and production have different subscriptions and different secrets.
- Rotation: Yousign's webhook docs don't describe rotating a secret.
Source: Yousign docs ↗
Code
// Generated with: yousign-webhooks skill
// https://github.com/hookdeck/webhook-skills
require('dotenv').config({ quiet: true });
const express = require('express');
const crypto = require('crypto');
const app = express();
// Yousign signs the raw body: X-Yousign-Signature-256 = "sha256=" + hex(HMAC-SHA256(secret, rawBody))
function verifySignature(rawBody, signatureHeader, secret) {
if (!signatureHeader || !secret) return false;
const expected =
'sha256=' + crypto.createHmac('sha256', secret).update(rawBody).digest('hex');
try {
return crypto.timingSafeEqual(Buffer.from(signatureHeader), Buffer.from(expected));
} catch {
return false; // different lengths
}
}
// express.raw with '*/*' keeps the body as a Buffer for any content type
app.post('/webhooks/yousign', express.raw({ type: '*/*' }), (req, res) => {
const signature = req.get('x-yousign-signature-256');
if (!signature) {
return res.status(400).send('Missing X-Yousign-Signature-256 header');
}
if (!Buffer.isBuffer(req.body) || !verifySignature(req.body, signature, process.env.YOUSIGN_WEBHOOK_SECRET)) {
return res.status(400).send('Invalid signature');
}
let event;
try {
event = JSON.parse(req.body.toString('utf8'));
} catch {
return res.status(400).send('Invalid JSON');
}
// event_id is globally unique: use it to deduplicate retries (x-yousign-retry > 0)
switch (event.event_name) {
case 'signature_request.activated':
console.log('Signature request activated:', event.data?.signature_request?.id);
break;
case 'signature_request.done':
console.log('Signature request done:', event.data?.signature_request?.id);
break;
case 'signature_request.declined':
console.log('Signature request declined:', event.data?.signature_request?.id);
break;
case 'signer.done':
console.log('Signer done:', event.data?.signer?.id);
break;
case 'signer.declined':
console.log('Signer declined:', event.data?.signer?.id);
break;
default:
console.log('Unhandled event:', event.event_name);
}
// Respond 2xx within 1 second; do heavy work asynchronously
res.json({ received: true });
});
if (require.main === module) {
const port = process.env.PORT || 3000;
app.listen(port, () => console.log(`Server running on http://localhost:${port}`));
}
module.exports = app; // Generated with: yousign-webhooks skill
// https://github.com/hookdeck/webhook-skills
import { NextRequest, NextResponse } from 'next/server';
import { verifySignature } from '../../../lib/verify';
export async function POST(request: NextRequest) {
// Raw body is required for signature verification
const rawBody = await request.text();
const signature = request.headers.get('x-yousign-signature-256');
if (!signature) {
return NextResponse.json({ error: 'Missing X-Yousign-Signature-256 header' }, { status: 400 });
}
if (!verifySignature(rawBody, signature, process.env.YOUSIGN_WEBHOOK_SECRET)) {
return NextResponse.json({ error: 'Invalid signature' }, { status: 400 });
}
let event: { event_id?: string; event_name?: string; data?: Record<string, any> };
try {
event = JSON.parse(rawBody);
} catch {
return NextResponse.json({ error: 'Invalid JSON' }, { status: 400 });
}
// event_id is globally unique: use it to deduplicate retries (x-yousign-retry > 0)
switch (event.event_name) {
case 'signature_request.activated':
console.log('Signature request activated:', event.data?.signature_request?.id);
break;
case 'signature_request.done':
console.log('Signature request done:', event.data?.signature_request?.id);
break;
case 'signature_request.declined':
console.log('Signature request declined:', event.data?.signature_request?.id);
break;
case 'signer.done':
console.log('Signer done:', event.data?.signer?.id);
break;
case 'signer.declined':
console.log('Signer declined:', event.data?.signer?.id);
break;
default:
console.log('Unhandled event:', event.event_name);
}
// Respond 2xx within 1 second
return NextResponse.json({ received: true });
} # Generated with: yousign-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, HTTPException, Request
load_dotenv()
app = FastAPI()
def verify_signature(raw_body: bytes, signature_header: str | None, secret: str | None) -> bool:
"""Yousign: X-Yousign-Signature-256 = "sha256=" + hex(HMAC-SHA256(secret, raw_body))."""
if not signature_header or not secret:
return False
expected = "sha256=" + hmac.new(secret.encode("utf-8"), raw_body, hashlib.sha256).hexdigest()
return hmac.compare_digest(signature_header.encode(), expected.encode())
@app.post("/webhooks/yousign")
async def yousign_webhook(request: Request):
# Raw body is required for signature verification
raw_body = await request.body()
signature = request.headers.get("x-yousign-signature-256")
if not signature:
raise HTTPException(status_code=400, detail="Missing X-Yousign-Signature-256 header")
if not verify_signature(raw_body, signature, os.getenv("YOUSIGN_WEBHOOK_SECRET")):
raise HTTPException(status_code=400, detail="Invalid signature")
try:
event = json.loads(raw_body)
except json.JSONDecodeError:
raise HTTPException(status_code=400, detail="Invalid JSON")
# event_id is globally unique: use it to deduplicate retries (x-yousign-retry > 0)
name = event.get("event_name")
data = event.get("data") or {}
if name == "signature_request.activated":
print("Signature request activated:", (data.get("signature_request") or {}).get("id"))
elif name == "signature_request.done":
print("Signature request done:", (data.get("signature_request") or {}).get("id"))
elif name == "signature_request.declined":
print("Signature request declined:", (data.get("signature_request") or {}).get("id"))
elif name == "signer.done":
print("Signer done:", (data.get("signer") or {}).get("id"))
elif name == "signer.declined":
print("Signer declined:", (data.get("signer") or {}).get("id"))
else:
print("Unhandled event:", name)
# Respond 2xx within 1 second
return {"received": True} Or install the Yousign webhooks skill:
npx skills add hookdeck/webhook-skills --skill yousign-webhooks
Common failures
The body was parsed first
The HMAC covers the exact bytes Yousign sent. Yousign warns against hashing a parsed or formatted version, so read the raw body before any JSON middleware.
The sha256= prefix is missing
The header value includes the prefix. Add it to your computed hex digest before comparing, or strip it from the header.
The secret belongs to another subscription
Each subscription has its own secret key, so a sandbox subscription's secret won't verify a production delivery. Your API key won't work either.
Signatures of different lengths throw an error
Yousign's Node.js sample calls timingSafeEqual directly, and that throws when the two values differ in length. Handle that case as a failed check.
Let Event Gateway verify Yousign signatures.
Event Gateway verifies the signature on each Yousign delivery before it reaches your service, then queues it and retries failures on your schedule.