Skip to content

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:

FieldTypeDescription
urlstringYour endpoint URL
headersobject(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-After header, 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 valid Retry-After the 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:

HeaderValue
Content-Typeapplication/json
User-AgentSesamy-Webhooks/1.0 (+https://developers.sesamy.com/guides/webhooks.html). Fixed, and not replaced by a custom User-Agent header.
X-Sesamy-Event-IdId of the event. The same on every retry, so use it to drop duplicates.
X-Sesamy-TimestampUnix time in seconds when this attempt was signed. A retry gets a new timestamp.
X-Sesamy-Signaturev1= 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:

json
{
  "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 ​

FieldTypeDescription
eventTypestringThe type of event that occurred (see Event Types below)
vendorIdstringThe vendor identifier
userIdstringThe user identifier
occured_atstringISO 8601 timestamp of when the event occurred
contractIdstring(Optional) Contract identifier, if applicable
entitlementIdstring(Optional) Entitlement identifier, if applicable
checkoutIdstring(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 TypeDescription
userVendor.1#newA new user-vendor relationship was created
userVendor.1#updateA user-vendor relationship was updated
contract.1#purchasedA contract was purchased
contract.1#updateA contract was updated
contract#cancelRequestA cancellation request was made for a contract
entitlement.1#newA new entitlement was created for a user
entitlement.1#updateAn existing entitlement was updated
checkout.1#confirmA checkout was confirmed

Note: entitlements created as part of a bundle (origin: BUNDLE) do not raise entitlement.1#new or entitlement.1#update events. They are filtered out before reaching any integration.

Setting Up Webhook Endpoints ​

Your webhook endpoint should:

  1. Accept POST requests
  2. Respond quickly (within a few seconds)
  3. Store the event durably, then return a 2xx status code to acknowledge receipt
  4. 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 ​

javascript
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 asynchronously

This 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:

javascript
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:

text
signed_payload = X-Sesamy-Timestamp + "." + raw_body
X-Sesamy-Signature = "v1=" + hex(HMAC_SHA256(signing_secret, signed_payload))

To verify a request:

  1. Read the body as raw bytes or text. Do not parse and re-serialize it, because that changes the bytes that were signed.
  2. Recompute the signature with your signing secret and compare it with X-Sesamy-Signature in constant time.
  3. Reject the request if X-Sesamy-Timestamp is more than five minutes from your clock. This stops someone replaying a captured request.
javascript
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 each

A 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:

javascript
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.

javascript
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:

javascript
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:

javascript
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:

  1. Use a tool like ngrok to expose your local endpoint
  2. Ask your Sesamy account manager to point your test vendor's webhook endpoint at the ngrok URL (see Built-in Webhook Forwarding)
  3. Trigger events in your test environment
  4. Monitor the webhook delivery in your local application
bash
# Start ngrok
ngrok http 3000

# Use the ngrok URL as your webhook endpoint
# https://abc123.ngrok.io/webhooks/sesamy

Allowing 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 ​

Released under the MIT License.