> 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/sdk/web-sdk/core-methods.md).

# Core Methods

## Authentication

| Method                            | Description                                           |
| --------------------------------- | ----------------------------------------------------- |
| `tiun.login()`                    | Open the login overlay.                               |
| `tiun.logout()`                   | Clear the user session.                               |
| `tiun.getUser()`                  | Get the current user state.                           |
| `tiun.getUserVerificationToken()` | Get a signed token for server-side user verification. |

`getUserVerificationToken()` resolves to a token valid for 5 minutes, or `null` when there's none — the user isn't signed in, or the request failed (`tiun.isAuthenticated` tells you which). Fetch a fresh token for each request to your backend. Parallel calls each get their own token from `@tiun/sdk` 0.12.0; before that, all but the last resolved `null`. See [verify authentication server-side](https://docs.tiun.io/guides/authentication/verify-server-side.md).

***

## Checkout

| Method                                      | Description                                                    |
| ------------------------------------------- | -------------------------------------------------------------- |
| `tiun.checkout({ productId, referenceId })` | Open the checkout flow for a subscription or one-time product. |

| Option        | Type     | Description                                                                                                                                                                                                                                                                                                                                                         |
| ------------- | -------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `productId`   | `string` | The product to buy, from your dashboard.                                                                                                                                                                                                                                                                                                                            |
| `referenceId` | `string` | Your own identifier for this purchase, such as an article or order ID. **Required for repeatable products** — without it, checkout shows a configuration error. Omit it for every other product; passing it there is a configuration error too. 1–200 characters: letters, digits, hyphens, underscores, or dots, and no spaces. Needs `@tiun/sdk` 0.11.0 or later. |

```javascript
tiun.checkout({ productId: 'p-live-pro' });

// Repeatable product: tie this purchase to your own reference
tiun.checkout({ productId: 'p-live-article', referenceId: 'article-1042' });
```

See [repeatable one-time purchases](https://docs.tiun.io/guides/one-time-purchases/repeatable-one-time-purchases.md) for how reference IDs work.

***

## Products

Read your product catalog and check what the current user has access to. Needs `@tiun/sdk` 0.12.0 or later.

| Method                                                | Returns                       | Description                                                                                                               |
| ----------------------------------------------------- | ----------------------------- | ------------------------------------------------------------------------------------------------------------------------- |
| `tiun.listProducts()`                                 | `Promise<Product[]>`          | List the products available on your snippet.                                                                              |
| `tiun.getProduct(productId)`                          | `Promise<ProductDetail>`      | Get a product's details and localized pricing.                                                                            |
| `tiun.listProductAccess()`                            | `Promise<ProductAccess[]>`    | List the current user's active product access.                                                                            |
| `tiun.checkProductAccess(productId, { referenceId })` | `Promise<ProductAccessCheck>` | Check whether the current user has access to a product. Pass `referenceId` to check one purchase of a repeatable product. |

```javascript
const products = await tiun.listProducts();
// [{ productId: 'p-live-pro', name: 'Pro', type: 'Subscription' }]

const { name, pricingLine } = await tiun.getProduct('p-live-pro');
// pricingLine is localized, e.g. "CHF 240 /year"

const access = await tiun.listProductAccess();
// [
//   { productId: 'p-live-pro', referenceId: null, type: 'Subscription', activatedAt: '2026-10-01T09:12:00Z', expiresAt: null },
//   { productId: 'p-live-article', referenceId: 'article-1042', type: 'OneTime', activatedAt: '2026-11-02T10:00:00Z', expiresAt: null },
// ]

const { hasAccess } = await tiun.checkProductAccess('p-live-pro');

// Repeatable product: check one purchase,
// using the referenceId you passed to checkout()
const { hasAccess: ownsArticle } = await tiun.checkProductAccess('p-live-article', {
  referenceId: 'article-1042',
});
```

**Being logged out is not an error.** `listProductAccess()` resolves to `[]` and `checkProductAccess()` to `{ hasAccess: false, access: null }` — the same answer as a logged-in user without access. An unknown product ID makes `getProduct()` reject with `http_404`, while `checkProductAccess()` resolves to `{ hasAccess: false, access: null }`.

You can call these methods straight after `init()`: calls made before the snippet is ready wait for it. Parallel calls are fine — each gets its own answer.

**Showing many items at once**, like a list of articles? Call `listProductAccess()` once and look up each item in the result, rather than calling `checkProductAccess()` per item.

`user.productAccess` is still there, stays in sync through `userChange`, and is all you need for subscriptions and regular one-time products. Use these methods for repeatable products, or when you need when a purchase started (`activatedAt`) or ends (`expiresAt`). Re-check on every [`userChange`](https://docs.tiun.io/sdk/web-sdk/events.md#userchange): it fires with `event: 'checkout'` whenever access changes, including a repeatable product bought with a new reference ID.

{% hint style="info" %}
**Checking on your server instead.** These methods work without a backend. If your backend serves the content, check access there with the server-to-server APIs. See [verify authentication server-side](https://docs.tiun.io/guides/authentication/verify-server-side.md).
{% endhint %}

### Types

All types are exported from `@tiun/sdk`.

| Type                   | Properties                                                                                                                                                                  |
| ---------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `Product`              | `productId: string`, `name: string`, `type: 'Subscription' \| 'OneTime'`                                                                                                    |
| `ProductDetail`        | Everything in `Product`, plus `pricingLine: string` (localized, e.g. `"CHF 240 /year"`) and `explanationLine?: string \| null`                                              |
| `ProductAccess`        | `productId: string`, `referenceId?: string \| null` (set for repeatable products), `type: 'Subscription' \| 'OneTime'`, `activatedAt: string`, `expiresAt?: string \| null` |
| `ProductAccessCheck`   | `hasAccess: boolean`, `access?: ProductAccess \| null` (`null` when there's no access)                                                                                      |
| `ProductAccessOptions` | `referenceId?: string`                                                                                                                                                      |

Dates are ISO 8601 strings. `expiresAt` is `null` while a subscription is active and renewing; once it's cancelled, it's set to the end of the paid period.

### Errors

When a request fails, the Promise rejects with a `TiunError` — `{ code, message, details? }`. Errors only come through the Promise: they don't fire the [`error` event](https://docs.tiun.io/sdk/web-sdk/events.md#error), so wrap calls in `try` / `catch`.

| `code`             | When                                                                                                                                          |
| ------------------ | --------------------------------------------------------------------------------------------------------------------------------------------- |
| `http_<status>`    | The backend answered with an error, e.g. `http_404` for an unknown product in `getProduct()`. `details` holds the backend's problem response. |
| `network_error`    | The request didn't reach the backend.                                                                                                         |
| `timeout`          | No answer within 10 seconds.                                                                                                                  |
| `invalid_argument` | `productId` is empty.                                                                                                                         |
| `destroyed`        | `tiun.destroy()` was called while the call was waiting.                                                                                       |
| `ssr`              | Called on the server during server-side rendering. Call it in the browser only.                                                               |
| `unknown_error`    | Anything else that went wrong.                                                                                                                |

```javascript
try {
  const product = await tiun.getProduct(productId);
  renderPrice(product.pricingLine);
} catch (error) {
  console.error('tiun error:', error.code, error.message);
}
```

***

## Time-based

| Method         | Description                                      |
| -------------- | ------------------------------------------------ |
| `tiun.start()` | Open the connect overlay for time-based billing. |

***

## Content & Access

| Method                     | Description                         |
| -------------------------- | ----------------------------------- |
| `tiun.setContent(options)` | Update the current content context. |

***

## Lifecycle

| Method                           | Description                                                                                                                                                                                                                                          |
| -------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `tiun.init(config)`              | Initialize the SDK. Call once at startup.                                                                                                                                                                                                            |
| `tiun.setAppearance(appearance)` | Switch the snippet color theme to `'light'`, `'dark'`, or `'auto'` without a reload. The value is case-insensitive. Safe to call before `init()` or before the snippet is ready.                                                                     |
| `tiun.destroy()`                 | Destroy the SDK instance and clean up all listeners. The snippet stays loaded, and from `@tiun/sdk` 0.12.0 a later `init()` works again — see [Lifecycle and `destroy()`](https://docs.tiun.io/sdk/web-sdk/initialization.md#lifecycle-and-destroy). |
| `tiun.waitForReady()`            | Returns a Promise that resolves when the snippet is ready. From 0.12.0 it also resolves when called before `init()`, once the snippet is ready.                                                                                                      |
| `tiun.on(event, callback)`       | Subscribe to an event. Returns an unsubscribe function.                                                                                                                                                                                              |
| `tiun.once(event, callback)`     | Subscribe to an event once.                                                                                                                                                                                                                          |


---

# 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/sdk/web-sdk/core-methods.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.
