Handling Webhooks
Learn how to receive and process webhook events from Sesamy.
Overview
Sesamy sends webhook notifications to your configured endpoints when specific events occur. Webhooks are designed to be lightweight, containing only essential identifiers. Your application should use these identifiers to fetch the full details from the Sesamy API.
Built-in Webhook Forwarding
If you want Sesamy to forward events to your endpoint without building a custom consumer, you can use the built-in webhook integration. Provide the following to your Sesamy account manager:
| Field | Type | Description |
|---|---|---|
url | string | Your endpoint URL |
headers | object | (Optional) Custom HTTP headers for authentication (e.g., Authorization: Bearer token) |
The built-in integration forwards six of the eight standard event types (all except entitlement.1#new and entitlement.1#update).
Retry behaviour: HTTP 5xx responses, HTTP 429, and network-level errors (connection refused, timeout, DNS failure, connection reset) are retried. HTTP 4xx responses other than 429 are treated as permanent failures and the event is not redelivered -- a 404 or 401 means the endpoint is misconfigured, and retrying will not fix it.
A retryable failure is delivered up to 5 times in total, waiting 1 minute, 5 minutes, 30 minutes and 2 hours between attempts. After the fifth failure the event moves to a dead-letter queue and is logged for investigation. A nightly job redelivers dead-lettered events once more; after that they are not delivered again.
A 429 (or 503) is retried on that same schedule and counts toward the 5 attempts. If the response has a
Retry-Afterheader, in seconds or as an HTTP date, Sesamy waits at least that long, capped at 2 hours, and never less than the scheduled wait. Without a validRetry-Afterthe schedule applies.Because a failure can be redelivered, your endpoint may see the same event more than once. Return a 2xx as soon as you have accepted the payload, process asynchronously, and make that processing idempotent (see Handle Idempotency).
See Integration Concepts for full retry details.
Headers Sesamy sends
Every request from the built-in integration carries these headers:
| Header | Value |
|---|---|
Content-Type | application/json |
User-Agent | Sesamy-Webhooks/1.0 (+https://developers.sesamy.com/guides/webhooks.html). Fixed, and not replaced by a custom User-Agent header. |
X-Sesamy-Event-Id | Id of the event. The same on every retry, so use it to drop duplicates. |
X-Sesamy-Timestamp | Unix time in seconds when this attempt was signed. A retry gets a new timestamp. |
X-Sesamy-Signature | v1= followed by the hex HMAC-SHA256 signature. See Verify the signature. |
Your own headers are sent as well. Sesamy sets User-Agent, X-Sesamy-Event-Id, X-Sesamy-Timestamp and X-Sesamy-Signature itself, so a custom header with one of those names (in any letter case) is replaced.
Integrations created before signing was added have no signing secret and are sent without X-Sesamy-Timestamp and X-Sesamy-Signature. They get a secret the next time the integration is saved.
The rest of this page covers how to build your own webhook consumer for more advanced use cases.
Webhook Request Format
Webhooks are sent as HTTP POST requests with the following structure:
{
"eventType": "userVendor.1#new",
"vendorId": "vendor_123",
"userId": "user_456",
"contractId": "contract_789",
"entitlementId": "entitlement_012",
"checkoutId": "checkout_345",
"occured_at": "2025-11-10T12:00:00Z"
}Payload Fields
| Field | Type | Description |
|---|---|---|
eventType | string | The type of event that occurred (see Event Types below) |
vendorId | string | The vendor identifier |
userId | string | The user identifier |
occured_at | string | ISO 8601 timestamp of when the event occurred |
contractId | string | (Optional) Contract identifier, if applicable |
entitlementId | string | (Optional) Entitlement identifier, if applicable |
checkoutId | string | (Optional) Checkout identifier, if applicable |
Event Types
The following webhook events are available. For a comprehensive reference of events, tags, and retry behaviour used by built-in integrations, see Integration Concepts.
| Event Type | Description |
|---|---|
userVendor.1#new | A new user-vendor relationship was created |
userVendor.1#update | A user-vendor relationship was updated |
contract.1#purchased | A contract was purchased |
contract.1#update | A contract was updated |
contract#cancelRequest | A cancellation request was made for a contract |
entitlement.1#new | A new entitlement was created for a user |
entitlement.1#update | An existing entitlement was updated |
checkout.1#confirm | A checkout was confirmed |
Note: entitlements created as part of a bundle (
origin: BUNDLE) do not raiseentitlement.1#neworentitlement.1#updateevents. They are filtered out before reaching any integration.
Setting Up Webhook Endpoints
Your webhook endpoint should:
- Accept POST requests
- Respond quickly (within a few seconds)
- Store the event durably, then return a 2xx status code to acknowledge receipt
- Process the stored event asynchronously
Sesamy stops delivering an event after the first 2xx, so acknowledge only once the event is kept. A 5xx is retried.
Example Endpoint
app.post('/webhooks/sesamy', async (req, res) => {
try {
// Store the event (a queue or a database row) before acknowledging it
await enqueueWebhook(req.get('X-Sesamy-Event-Id'), req.body);
} catch {
return res.sendStatus(503); // retried by Sesamy
}
res.status(200).send('OK');
});
// A worker reads the stored events and processes them asynchronouslyThis example skips signature verification to stay short. Verify the signature before you store the event.
Fetching Full Event Data
Webhooks contain minimal data to reduce payload size. Use the provided identifiers to fetch complete information from the Sesamy API:
async function fetchEventData({ eventType, vendorId, userId, contractId, checkoutId }) {
switch (eventType) {
case 'contract.1#purchased':
case 'contract.1#update':
// Fetch contract details
const contract = await sesamyClient.getContract(contractId);
// Process contract data
break;
case 'userVendor.1#new':
case 'userVendor.1#update':
// Fetch user-vendor relationship
const userVendor = await sesamyClient.getUserVendor(vendorId, userId);
// Process user data
break;
case 'checkout.1#confirm':
// Fetch checkout details
const checkout = await sesamyClient.getCheckout(checkoutId);
// Process checkout data
break;
}
}To follow up on a reader who started a checkout and did not finish it, see Listing Checkouts.
Best Practices
1. Validate Webhook Authenticity
Verify the signature
When the built-in integration is created, Sesamy generates a signing secret that starts with whsec_. It is shown once, in the response that creates the integration, and later reads only show its last four characters. Store it like a password.
Each request is signed over the timestamp, a dot, and the raw request body:
signed_payload = X-Sesamy-Timestamp + "." + raw_body
X-Sesamy-Signature = "v1=" + hex(HMAC_SHA256(signing_secret, signed_payload))To verify a request:
- Read the body as raw bytes or text. Do not parse and re-serialize it, because that changes the bytes that were signed.
- Recompute the signature with your signing secret and compare it with
X-Sesamy-Signaturein constant time. - Reject the request if
X-Sesamy-Timestampis more than five minutes from your clock. This stops someone replaying a captured request.
import crypto from 'node:crypto';
import express from 'express';
const app = express();
app.post(
'/webhooks/sesamy',
express.raw({ type: 'application/json' }), // keep the body as a Buffer
async (req, res) => {
const timestamp = req.get('X-Sesamy-Timestamp') ?? '';
const signature = req.get('X-Sesamy-Signature') ?? '';
const age = Math.abs(Date.now() / 1000 - Number(timestamp));
if (!/^\d+$/.test(timestamp) || age > 300) {
return res.status(400).send('Stale or missing timestamp');
}
const expected =
'v1=' +
crypto
.createHmac('sha256', process.env.SESAMY_SIGNING_SECRET)
.update(`${timestamp}.`)
.update(req.body)
.digest('hex');
const a = Buffer.from(expected);
const b = Buffer.from(signature);
if (a.length !== b.length || !crypto.timingSafeEqual(a, b)) {
return res.status(401).send('Invalid signature');
}
const event = JSON.parse(req.body.toString('utf8'));
try {
// Store the event durably (a queue or a database row) before acknowledging it.
// The event id is identical on every retry, so it is the idempotency key.
await enqueueWebhook(req.get('X-Sesamy-Event-Id'), event);
} catch {
// A 5xx is retried; a 2xx would end delivery for an event you did not keep
return res.sendStatus(503);
}
res.sendStatus(200);
}
);
// A worker reads the stored events and calls processWebhook(eventId, event) for eachA 4xx other than 429 is not retried, so return one only for requests that really are invalid. Acknowledge with a 2xx only once the event is safely stored: Sesamy stops delivering an event after the first 2xx.
Shared secret header
You can also keep sending your own secret in headers. Sesamy sends them verbatim on every request:
app.post('/webhooks/sesamy', (req, res) => {
if (req.get('Authorization') !== `Bearer ${process.env.SESAMY_WEBHOOK_SECRET}`) {
return res.status(401).send('Unauthorized');
}
// ...
});Your endpoint url must use https://. These headers are sent on every delivery, so an http:// endpoint would put your shared secret on the wire in clear text.
Treat the payload as untrusted regardless: it carries only identifiers, so read the authoritative record back from the Sesamy API by ID before acting on it.
2. Handle Idempotency
Webhooks may be delivered more than once. Ensure your processing logic is idempotent by tracking processed event IDs. Use the X-Sesamy-Event-Id header as the key: it is the same on every retry of an event, while the payload carries no event id of its own.
const processedEvents = new Set();
async function processWebhook(eventId, payload) {
if (processedEvents.has(eventId)) {
return; // Already processed
}
// Process the webhook
// ...
processedEvents.add(eventId);
}In production, keep the ids in a shared store such as Redis or a database table instead of an in-memory set, so a restart or a second instance does not forget them.
3. Implement Retry Logic
If fetching data from the Sesamy API fails, implement exponential backoff retry logic:
async function fetchWithRetry(apiCall, maxRetries = 3) {
for (let i = 0; i < maxRetries; i++) {
try {
return await apiCall();
} catch (error) {
if (i === maxRetries - 1) throw error;
await new Promise((resolve) => setTimeout(resolve, Math.pow(2, i) * 1000));
}
}
}4. Log All Webhooks
Keep a log of all received webhooks for debugging and auditing:
app.post('/webhooks/sesamy', async (req, res) => {
// Log the webhook
logger.info('Webhook received', {
eventType: req.body.eventType,
timestamp: req.body.occured_at,
payload: req.body,
});
res.status(200).send('OK');
processWebhook(req.get('X-Sesamy-Event-Id'), req.body);
});Testing Webhooks Locally
To test webhooks during development:
- Use a tool like ngrok to expose your local endpoint
- Ask your Sesamy account manager to point your test vendor's webhook endpoint at the ngrok URL (see Built-in Webhook Forwarding)
- Trigger events in your test environment
- Monitor the webhook delivery in your local application
# Start ngrok
ngrok http 3000
# Use the ngrok URL as your webhook endpoint
# https://abc123.ngrok.io/webhooks/sesamyAllowing Sesamy Through Cloudflare
If your endpoint is behind Cloudflare and webhooks fail with 403 responses, a bot or WAF rule is probably blocking the request. Add a custom rule that skips those checks for Sesamy's requests on your webhook path:
Expression
text(http.request.uri.path eq "/webhooks/sesamy" and starts_with(http.user_agent, "Sesamy-Webhooks/") and any(http.request.headers["x-sesamy-signature"][*] contains "v1="))Action: Skip, and select the rules to skip, such as the managed rules and Super Bot Fight Mode.
The expression requires X-Sesamy-Signature, which integrations created before signing was added do not send. Such an integration only matches the rule after it has been saved once, which gives it a signing secret (see Headers Sesamy sends). Save it before you rely on the rule, or drop the x-sesamy-signature condition for it and accept that the User-Agent alone then decides.
Place the rule above the rules it needs to skip. Cloudflare's free Bot Fight Mode cannot be skipped by a custom rule; on that plan, check whether the block comes from it.
Both the User-Agent and the header can be sent by anyone, so the skip only gets Sesamy's requests past Cloudflare. Your endpoint must still verify the signature as described above.
Troubleshooting
Webhooks Not Received
- Verify your endpoint is publicly accessible
- Check that your server responds with a 2xx status code
- Ensure your firewall allows incoming connections
- Review webhook logs in the Sesamy dashboard (if available)
Duplicate Webhooks
- Implement idempotency checks using event identifiers
- Store processed event IDs to prevent reprocessing
Missing Data
- Always fetch complete data from the API using the provided identifiers
- Don't rely solely on webhook payload for critical data
Next Steps
- Integration Concepts -- shared concepts for built-in integrations
- API Reference -- API endpoints for fetching event data
- Authentication -- securing API requests
- Subscriptions Guide -- managing subscription contracts