> For the complete documentation index, see [llms.txt](https://docs.tiun.io/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://docs.tiun.io/guides/webhooks/receive-webhooks.md).

# Receive webhooks

Webhooks let your backend react when something changes in tiun — a user gets or loses access to a product, a new user signs up, or a user withdraws consent — without the user being in your app. tiun sends a `POST` request to a URL you choose, and your server takes it from there: provision access in your own database, send a welcome email, or delete a user's data.

You don't need webhooks to gate content. The SDK's `userChange` event and the server-side checks already tell you what a user can access **right now**. Webhooks are for keeping **your own systems** in sync in the background.

***

## How it works

1. You add an **endpoint** in the dashboard — an `https://` URL on your server — and pick the events it should receive.
2. When one of those events happens, tiun sends your endpoint a small JSON message with the event type and the **IDs** involved.
3. Your server replies with a `2xx` status, then fetches the current state from the tiun API and acts on it.

{% hint style="warning" %}
**Webhooks carry IDs, not data, and they aren't signed.** Anyone who knows your endpoint URL can send it a request that looks like a tiun event. Never grant access or change data based on the webhook body alone — always confirm the current state with an authenticated server-to-server call before you act.
{% endhint %}

The event types and their payloads are listed in [Webhook events](https://docs.tiun.io/reference/webhooks/events.md). Retries, timeouts, and delivery statuses are in [Webhook delivery](https://docs.tiun.io/reference/webhooks/delivery.md).

***

## 1. Add an endpoint

In the [dashboard](https://my.tiun.business/), add an endpoint under **API & Webhook → Webhooks**: the URL tiun should send events to, for example `https://example.com/webhooks/tiun`, and the events it should receive. The URL must use `https://`.

You can add more than one endpoint — for example one per service — and each gets only the events you picked for it. You can change an endpoint's URL or events later, or pause it to stop deliveries for a while without removing it. Events that happen while an endpoint is paused aren't delivered to it, even after you turn it back on.

{% hint style="info" %}
Sandbox and live each have **their own endpoints**, like the rest of the dashboard. Add a sandbox endpoint while you build, and add the live one separately when you go live.
{% endhint %}

***

## 2. Set up an API key

Your handler confirms each event with a server-to-server call, which needs an API key. If you don't have one yet, create one in the dashboard under **API & Webhook → API Keys**. Store it in your backend environment variables — never in frontend code.

Use the API key and base URL from the **same environment** as the endpoint:

| Environment | URL                             |
| ----------- | ------------------------------- |
| Live        | `https://api.tiun.live`         |
| Sandbox     | `https://api-sandbox.tiun.live` |

***

## 3. Handle the request

Every event has the same envelope: an `id`, a `type`, a `version`, an `occurred_at` timestamp, and a `payload` with the IDs involved.

```json
{
  "id": "b0c22a9741be458fa36e742d3d3bb0e8",
  "type": "product_access.add",
  "version": 1,
  "occurred_at": "2026-10-30T14:45:50.6090416+00:00",
  "payload": {
    "user_id": "user-sample-0001",
    "product_id": "product-sample-0001",
    "reference": null
  }
}
```

Your handler should:

1. **Reply `2xx` quickly.** tiun waits up to 15 seconds for a response; anything else — a timeout, a `4xx`, or a `5xx` — counts as a failure and is retried. Acknowledge first, then do the slow work.
2. **Skip duplicates.** The same event can arrive more than once, for example after a retry or a manual resend. Store each `id` you've handled and ignore repeats.
3. **Confirm with the API.** Fetch the user's current state with the [UserInfo API](https://docs.tiun.io/guides/authentication/get-user-info.md) — or, for a repeatable product, [the purchase's access by reference ID](https://docs.tiun.io/guides/one-time-purchases/verify-server-side.md) — and act on that, not on the webhook body.

Because you always read the current state, you don't have to worry about events arriving out of order: whatever the API returns is the truth at that moment.

***

## Full example

An Express handler that acknowledges the event, skips duplicates, and syncs the user from the UserInfo API:

```javascript
import express from 'express';

const BASE_URL = process.env.TIUN_API_BASE || 'https://api-sandbox.tiun.live';
const API_KEY = process.env.TIUN_API_KEY;

const app = express();

app.post('/webhooks/tiun', express.json(), (req, res) => {
  const event = req.body;

  // 1. Acknowledge right away so tiun doesn't retry
  res.sendStatus(200);

  // 2. Do the real work after responding
  handleEvent(event).catch((error) => {
    console.error('tiun webhook failed', event?.id, error);
  });
});

async function handleEvent(event) {
  if (!event?.id || !event?.payload?.user_id) return;

  // Skip events you've already handled (use your database in production)
  if (await alreadyHandled(event.id)) return;

  switch (event.type) {
    case 'user.create':
      await syncUser(event.payload.user_id);
      break;

    case 'product_access.add':
    case 'product_access.remove':
      if (event.payload.reference) {
        // Repeatable product: check that one purchase
        await syncPurchase(event.payload);
      } else {
        await syncUser(event.payload.user_id);
      }
      break;

    case 'user.revoke_consent':
      await deleteUserData(event.payload.user_id);
      break;
  }

  await markHandled(event.id);
}

// Read the current state from tiun — never trust the webhook body alone
async function syncUser(userId) {
  const response = await fetch(`${BASE_URL}/live_api/s2s/v1/users/${userId}/info`, {
    headers: { 'X-TIUN-API-KEY': API_KEY },
  });

  if (response.status === 404) return; // not a tiun user in this environment
  if (!response.ok) throw new Error(`UserInfo API returned ${response.status}`);

  const user = await response.json();
  await saveUserAccess(user.userId, user.email, user.productAccess);
}

// For repeatable products, check access for the purchase's reference ID
async function syncPurchase({ user_id, product_id, reference }) {
  const url = new URL(`/live_api/s2s/v1/users/${user_id}/product_access/${product_id}`, BASE_URL);
  url.searchParams.set('referenceId', reference);

  const response = await fetch(url, { headers: { 'X-TIUN-API-KEY': API_KEY } });

  if (response.status === 404) return;
  if (!response.ok) throw new Error(`Product access API returned ${response.status}`);

  const { hasAccess, access } = await response.json();
  await savePurchase(user_id, product_id, reference, hasAccess, access?.expiresAt);
}
```

`alreadyHandled`, `markHandled`, `saveUserAccess`, `savePurchase`, and `deleteUserData` stand in for your own storage. If `syncUser` throws after you've already replied, tiun won't retry — log the error and recover from your side, for example by re-syncing the user later.

{% hint style="info" %}
For `user.revoke_consent`, the example acts on the `user_id` directly. Deleting data is hard to undo, so keep your endpoint URL private and only delete users you actually know — a `user_id` that isn't in your database means there's nothing to remove.
{% endhint %}

***

## 4. Send a test event

Send a test event to your endpoint from the dashboard. You pick the event type, and the dashboard shows the request tiun sent and your server's response, so you can check your handler without making a real purchase.

Test events carry **sample IDs** such as `user-sample-0001` that don't exist in tiun. Your handler should treat a `404` from the UserInfo API as "nothing to do", as in the example above.

***

## 5. Monitor deliveries

The endpoint page shows every delivery with its status, HTTP response, and response time, plus delivery rate and failures over the last 24 hours, 7 days, or month. Open a delivery to see each attempt and the event body.

If your server was down and a delivery failed after all retries, fix the problem and resend that delivery from the dashboard — it sends the real event again with the same `id`.

***

## Go live

Webhook endpoints, API keys, and user IDs are all environment-specific. When you go live:

1. Add a **live** endpoint in the dashboard with the events you need.
2. Switch your handler to the live base URL (`https://api.tiun.live`) and a **live** API key.
3. Send a test event to the live endpoint to confirm it responds.

See [setting up your environment](https://docs.tiun.io/guides/getting-started/set-up-environment.md) for the full sandbox / live workflow.


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## Querying This Documentation
If you need additional information that is not directly available in this page, you can query the documentation by asking a question.

Perform an HTTP GET request on the following URL with the `ask` and `goal` query parameters:

```
GET https://docs.tiun.io/guides/webhooks/receive-webhooks.md?ask=<question>&goal=<user_goal>
```

`ask` is the immediate question: it should be specific, self-contained, and written in natural language.
`goal` is what the user is ultimately trying to achieve, the reason they need the answer. Sharing it helps GitBook give you a better, more relevant answer. A goal is most helpful when it describes the outcome the user wants rather than restating the question. For example, with `ask=how do I create an API token`, a goal like `automate deployments from our CI pipeline` lets GitBook tailor the answer to that use case.

The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
