tiun-sdk
Use when integrating or debugging tiun — the web SDK (@tiun/sdk) or the React Native SDK (@tiun/react-native-sdk) — for authentication, subscription billing, one-time purchases (including repeatable purchases and limited access), webhooks, and time-based paywalls. Triggers on imports of `@tiun/sdk` or `@tiun/react-native-sdk`, calls like `tiun.init`, `tiun.checkout`, `tiun.login`, `tiun.start`, `tiun.listProducts`, `tiun.getProduct`, `tiun.listProductAccess`, `tiun.checkProductAccess`, `TiunProvider`, `useTiun`, `useTiunEvent`, or questions about tiun products, product catalogs, pricing, entitlements, access checks, one-time purchases, lifetime access, referenceId, repeat purchases, limited access, webhooks, fixed fees, time-based sessions, checkout return deep links, or server-side verification.
How do I install this agent skill?
npx skills add https://mcp.tiun.business --skill tiun-sdkIs this agent skill safe to install?
No partner audit is available yet. Read the source before installing.
What does this agent skill do?
tiun SDK skill
Use this skill whenever the user is integrating, extending, or debugging code that uses @tiun/sdk or @tiun/react-native-sdk. Authoritative upstream docs: https://docs.tiun.io/llms-full.txt.
What tiun is
A commercial backend platform providing authentication, payments, and entitlements through a single JS SDK. The tiun singleton supports three flows; you pick based on the integrator's intent (see "Step 0 — Discovery before code"):
- Subscriptions — persistent user accounts (OTP login), recurring billing, per-product entitlements in
user.productAccess[]. Entry point:tiun.checkout({ productId }). See references/subscriptions.md. - One-time purchases — same accounts and same entry point as subscriptions, charged as a single fixed fee: no interval, no trial, no renewal, no cancellation. Access is permanent by default. Limited access gives the purchase an end date; Repeat purchases lets the same customer buy again, once per
referenceId. Entry point:tiun.checkout({ productId }), plusreferenceIdwhen the product is repeatable. See references/one-time.md. - Time-based — per-session anonymous access (no account required), metered by time spent on paid content. Entry point:
tiun.start()+paywallShow/paywallHideevents. See references/time-based.md.
Install: npm install @tiun/sdk. Init: tiun.init({ snippetId, language: 'en' }) once, on app start, ideally in the app root (idempotent).
Products and access at runtime (@tiun/sdk 0.12.0+, @tiun/react-native-sdk 0.5.0+ on useTiun()): tiun.listProducts(), tiun.getProduct(productId) (localized pricing), tiun.listProductAccess(), and tiun.checkProductAccess(productId, { referenceId }). They work without a backend, including for repeatable products. See references/api-reference.md.
tiun runs live and sandbox as two independent parallel environments. The SDK's sandbox flag selects which one — see references/installation.md.
React Native is a separate SDK. @tiun/react-native-sdk uses <TiunProvider> + useTiun() / useTiunEvent(), selects the environment with host (no sandbox flag), needs a returnUrl deep link, and covers subscriptions and one-time purchases only. Everything about it is in references/react-native.md. The tiun.* code, Minimal working example, and per-framework wiring below are web-only — never generate them in a React Native app.
Step 0 — Discovery before code
Platform first. Check the project before asking anything: a react-native dependency in package.json (or ios/ + android/ folders) means React Native → follow references/react-native.md alongside this discovery; otherwise it's the web SDK. In React Native, time-based is not available — if the user asks for it, say so in 0b.
Before writing any integration code, establish four things. Ask only for items the user has not already stated. If their prompt is fully specified ("wire up subscription with product p-test-pro in sandbox to gate /watch/*"), skip discovery.
Use a structured question primitive (e.g. AskQuestion) if your client supports one; otherwise ask inline in chat.
0a. Detect the MCP and offer to install if missing. See references/mcp.md for per-client install instructions and detection. Three states:
- MCP present and authed → use it to enumerate providers/products in 0c.
- MCP present, not authed → prompt auth once; if declined, proceed in manual mode.
- MCP absent → offer to install (single-sentence value proposition: "fetch your snippetId and productIds directly so we avoid copy-paste errors"). If declined, proceed in manual mode.
0b. Establish integration mode. Subscription, one-time purchase, time-based, or a combination? See references/discovery.md for cues that map user language to each mode. Do not infer mode from the account's inventory. A provider with only one product type today may be planning another tomorrow.
0c. Gather identifiers. Questions depend on mode and MCP availability. The MCP returns one row per environment for the same providerId — a sandbox row and a live row are the same provider.
- Subscription, MCP present → list providers, ask user to pick the environment row; list products, ask user to pick one or multiple tiers.
- Subscription, no MCP → ask for
snippetId; ask one product or multiple tiers; for each, askproductIdand label; confirm sandbox or live (thep-test-.../p-live-...prefix is a strong hint). - One-time, MCP present → list providers, ask user to pick the environment row; list products, ask user to pick the product(s) to unlock. Do not ask about tiers — one-time products are not tiered.
pricingType: 'OneTime'does not say whether Repeat purchases or Limited access is on. ReadoneTime.isRepeatableandoneTime.expiryfromget_products. For a repeatable product, ask which ID in the app is thereferenceId. - One-time, no MCP → ask for
snippetId; for each product, askproductIdand label; ask whether Repeat purchases or Limited access is on; for a repeatable product, ask which ID in the app is thereferenceId; confirm sandbox or live (prefix is a strong hint). - Time-based, MCP present → list providers, ask user to pick the environment row.
- Time-based, no MCP → ask for
snippetId; confirm sandbox or live.
When the MCP is present, ground questions in inventory ("you have a sandbox time-based product p-test-xxx — wire that up, or set up subscription products first?") rather than asking blind.
0d. Identify what to gate. Without this step the agent is generating boilerplate with no target. Ask:
- Which routes/components/features require access?
- What should signed-out users see, and how does the app's journey start? (offering or pricing page / account-first app where users sign in before meeting an upgrade / full-screen paywall / teaser + subscribe). Keep the journey the app is built for.
- What should authenticated-but-no-access users see? (typically the same UX with "upgrade" copy)
- Is there a free preview? (If yes, this is often a cue the user actually wants time-based, not subscription — feed back into 0b.)
- For multi-tier: which routes/features map to which tier?
When to do what
| Task | Route to |
|---|---|
| Discovery, scoping, MCP detection, mode selection | references/discovery.md |
| MCP installation per client, detection, auth | references/mcp.md |
| What tiun is, supported platforms, product model, hosted-UI boundaries | references/overview.md |
| Install / init / config / per-host env injection | references/installation.md |
| Method or property lookup | references/api-reference.md |
| Event names and payloads | references/events.md |
| Subscription gating (accounts + recurring billing), choosing checkout vs login | references/subscriptions.md |
| One-time purchase gating (fixed fee; permanent by default, optional limited access or repeat purchases) | references/one-time.md |
| Time-based paywall (per-session, anonymous, metered) | references/time-based.md |
| Trusted backend authorization | references/server-verification.md |
| Webhooks (unsigned ID events; confirm with the S2S API) | references/webhooks.md |
| Framework wiring (any stack) + lifecycle matrix | references/frameworks.md |
| "Overlay not appearing", SSR errors, sandbox mismatch, broken overlay injections | references/troubleshooting.md |
React Native: install, return deep link, TiunProvider, hooks, host, device testing | references/react-native.md |
Load-bearing rules
tiun.init({ snippetId, language })runs on the client, early in startup. In Next.js/Nuxt, wrap in a client-only component/plugin. Never call it on the server.initis idempotent — calling it again merges config rather than re-initializing, so noisInitializedguard is needed.snippetIdis not a secret. It identifies the environment. UseNEXT_PUBLIC_*/publicruntime config.userChangeis the source of truth for checkout-based gating (subscriptions and one-time purchases), not a one-shottiun.userread. Entitlements change mid-session. Re-check access on everyuserChange: readuser.productAccessfor subscriptions and one-time products, and calltiun.checkProductAccess(productId, { referenceId })for a repeatable product (ortiun.listProductAccess()for a list).'checkout'means access was gained or lost;'update'is a profile change, not an access change. React Native has theeventfield from@tiun/react-native-sdk0.5.0. Seereferences/events.md.- Verify on the server when your backend serves protected resources. For those requests:
tiun.getUserVerificationToken()returns a JWT (5-minute lifetime), fetch a fresh one for every request (parallel requests can each fetch their own), send it to your backend, the backend validates it viaPOST /live_api/s2s/v2/users/verificationwithX-TIUN-API-KEY. The verified user is theuserobject (userId,email,hasNewsletterOptIn,productAccess). For time-based, use thesessionIdfrompaywallHideagainstPATCH /live_api/s2s/v1/sessions/{sessionId}/status. Repeatable one-time purchases are checked perreferenceId, not viaproductAccess. Seereferences/server-verification.md. - The hosted UI is a black box — do not reimplement it and do not modify it. tiun renders checkout, login, and the connect overlay in shadow DOM. Open them with
tiun.checkout({ productId }),tiun.login(), ortiun.start(), and stop there. Never pierceshadowRootto query, append, or observe nodes; never inject text, tooltips, badges, or banners into it; never target it with CSS (host selectors,::part,::slotted,!importantoverrides); never reposition or wrap it; never read values out of its inputs. Its internal structure is unversioned and changes without notice, and it sits inside a payment flow — an injection breaks silently and takes checkout down with it. The only supported surfaces areinit()config (language,tone,appearance),tiun.setAppearance(), and dashboard settings. If the customer needs extra copy or explanation, put it on their own page next to the trigger, before the overlay opens — not inside it. Anything the config and dashboard do not expose is a request to support@tiun.io, not a client-side patch. See references/overview.md. - Do not wrap SDK methods to add
isInitialized/waitForReadyguards.tiun.checkout,tiun.login,tiun.start,tiun.setContent, andtiun.logoutalready handle initialization and wait for readiness internally. The product methods (listProducts,getProduct,listProductAccess,checkProductAccess) also wait for the snippet when called early. - Unsubscribe handlers returned from
tiun.on(...)on component unmount to avoid stale listeners. Or calltiun.destroy()if the whole subtree is going away. Callinginit()again afterdestroy()(a remount) needs@tiun/sdk0.12.0 or later; before that,checkout(),login(),start(), andsetContent()wait forever. After a re-init,tiun.userstays empty until the next login, logout, or checkout. - Live and sandbox are independent parallel environments. Each has its own snippet ID, products, product-ID prefix (
p-live-...vsp-test-...), API keys, webhook endpoints, and API base URL (https://api.tiun.livevshttps://api-sandbox.tiun.live). The environment switch (sandboxflag on web,hostin React Native) must match the dashboard view and the product-ID prefix, or checkout silently fails.localhostis blocked in live and enabled by default in sandbox. Each environment has its own Settings → Environment setup (live domain for web, app scheme for apps) and its own API & Webhook endpoints. - Products are created in the dashboard; the SDK reads them. Products are configured at
my.tiun.businessand referenced byproductId. From@tiun/sdk0.12.0,tiun.listProducts()lists them andtiun.getProduct(productId)returns localized pricing (pricingLine), so a pricing page doesn't need hardcoded prices. On older versions, hardcode the IDs and prices. The SDK cannot create or edit products. Do not invent other names such astiun.getProducts(). - Webhooks carry IDs only and are unsigned. tiun POSTs
user.create,user.revoke_consent,product_access.add, andproduct_access.remove. Confirm current state with a server-to-server call before changing access or stored data. Do not invent event types, signatures, or payload fields. Sandbox and live use separate endpoints. App gating still comes fromuserChangeand server verification. Seereferences/webhooks.md. - Stay upstream-faithful. All code examples must match https://docs.tiun.io. If a pattern isn't documented upstream (custom SSR wiring, multi-env setups, backend SDKs in other languages, etc.), point the user at the upstream docs rather than inventing a snippet.
- Do not infer integration mode from the account's product inventory. Always confirm with the user (see "Step 0"). What the MCP reports is what exists; it does not report what the integrator wants to build.
- A one-time purchase does not renew and cannot be cancelled. By default its product ID enters
productAccessat checkout and stays there. Limited access removes that ID when the purchase reaches its end date, anduserChangefires; nothing starts a new period. Repeat purchases are tracked perreferenceId. The product ID shows up inproductAccessafter the first reference and stays until the last one ends, and it never names which reference was bought.tiun.checkProductAccess(productId, { referenceId })is the check (@tiun/sdk0.12.0+), or the same check on the server when there's a backend. Do not generate renewal, cancellation, or trial handling for a one-time product. Seereferences/one-time.md. - Do not pass
baseUrltoinit(). It is an internal-only field reserved for tiun's own infrastructure. In the web SDK, usesandbox: truefor non-production environments; that is the only public environment switch, and the SDK routes to the matching API host automatically. (React Native is the exception: it has nosandboxflag and selects the environment withhost— seereferences/react-native.md.) languageis a closed enum:'en' | 'de' | 'fr', case-insensitive. Unsupported values trigger a one-time console warning and fall back to'en'. Do not generate other values.- Do not branch app logic on
error.code. It's a string but there's no published enum; codes can change between SDK versions. Displayerr.messageto users and logerr.codefor support. - Write runtime config to files the bundler actually loads.
.env.exampleis documentation and is never evaluated. Vite loads.env/.env.local; Next.js loads.env.localand requires theNEXT_PUBLIC_*prefix for client-exposed values; Nuxt loads viaruntimeConfig.publicinnuxt.config.ts. Seereferences/installation.mdfor the per-host table. - Use authentication for account entry and checkout for purchases. Signing up or signing in →
tiun.login(); buying a product or plan →tiun.checkout({ productId }); signing out →tiun.logout(). Choose by the action's purpose, not its label. Checkout handles the authentication and returning-customer cases that come with purchasing, so a purchase action opens it directly rather than routing through a separate login. This is about what a purchase action opens, not about app structure — purchase-first and account-first journeys are both valid. Seereferences/subscriptions.md→ "Choosing checkout or login". - React Native checkout needs one scheme in three places. The dashboard's Settings → Environment setup → App scheme (e.g.
myapp://), the native registration (iOSInfo.plist+RCTLinkingManagerforwarding inAppDelegate; Android intent filter +android:launchMode="singleTask"), and thereturnUrlinTiunConfig(e.g.myapp://tiun/return). Reuse the app's existing scheme rather than inventing one, and tell the user to register it in the dashboard for the environmenthostpoints at. A mismatch fails in one of two ways: ifreturnUrl's scheme isn't the dashboard App scheme for that environment, login and checkout close as soon as they open; if the dashboard accepts it but the native registration doesn't match, payment succeeds but checkout never returns. Seereferences/react-native.md. - Never assign the SDK to
window.tiun. The snippet script uses that name and replaces it when it loads. Keep using the importedtiun, or pick another global name such aswindow.tiunSdk = tiun.
Minimal working example
Three primitives — works in every supported environment. Adapt the reactive primitive (state hook, ref, signal, store, DOM update) to your stack.
import { tiun } from '@tiun/sdk';
tiun.init({ snippetId: 'YOUR_SNIPPET_ID', language: 'en' });
const off = tiun.on('userChange', ({ event, isAuthenticated, user }) => {
// push into your framework's reactive primitive
});
document.querySelector('#buy').onclick =
() => tiun.checkout({ productId: 'p-live-pro' });
// off(); tiun.destroy();
Full per-mode walkthroughs in references/subscriptions.md, references/one-time.md, and references/time-based.md. Per-framework adaptations in references/frameworks.md.
Decision cues
- User says "subscription", "recurring", "members", "paid account", "products and tiers" → subscription flow. Route to subscriptions.md.
- User says "buy once", "pay once", "one-time", "lifetime", "lifetime deal", "single payment", "unlock forever", "fixed fee", "perpetual license", "no subscription" → one-time flow (permanent, once per customer, unless they also want an end date or repeat purchases). Route to one-time.md.
- User says "buy again", "ticket", "booking", "pay per article", "reference ID", "repeat purchases" → repeatable one-time. Pass
referenceIdat checkout (@tiun/sdk0.11.0+ or@tiun/react-native-sdk0.4.0+) and check that reference withtiun.checkProductAccess(productId, { referenceId })(@tiun/sdk0.12.0+), or on the server when there's a backend. Route to one-time.md. - User says "access for N days", "pass expires", "limited access" on a one-time product → one-time with limited access. The product ID leaves
productAccessat the end date. Nothing renews. Route to one-time.md. - User says "webhook", "user.create", "product_access.add", "product_access.remove" → references/webhooks.md.
- User says "article paywall", "watch a video then pay", "session", "no account needed", "donation prompt", "first N seconds free" → time-based flow. Route to time-based.md.
- User says "videos behind a paywall", "premium content" (ambiguous) → ask which mode. Don't guess.
- User says "how do I get my agent to integrate tiun?" / "set this up with an AI coding agent" → point at the upstream Agent integration guide on docs.tiun.io and the quickstart in
references/mcp.md(npx skills add https://mcp.tiun.business; add-ywhen you run it). - User asks "how do I list products?" / "show prices" / "get all products?" →
tiun.listProducts()andtiun.getProduct(productId)(@tiun/sdk0.12.0+). Products are still created in the dashboard atmy.tiun.business. (The MCP's product inventory is for the agent during setup.) - User wants an account page with renewal or end dates, or "My purchases" →
tiun.listProductAccess()(activatedAt,expiresAt,referenceId;@tiun/sdk0.12.0+). - User says "price includes VAT", "tax on top", or "prices excluding tax" → tax behavior on a subscription or one-time product. See references/mcp.md.
- User mentions "verify on the backend", "protect API", "trust the client" → server verification (
X-TIUN-API-KEYheader; per-environment base URLs). - User mentions sandbox /
localhost/ "why won't it work locally" → confirmsandbox: true+ sandbox snippet ID +p-test-...product IDs (live is hard-blocked onlocalhost). - User asks for light mode, dark mode, or a theme that follows the OS on the hosted overlay →
appearance: 'light' | 'dark' | 'auto'(default'light') ontiun.initor React NativeTiunProvider. On the web SDK,tiun.setAppearance(appearance)switches the theme without a reload and is safe before ready. - User asks to restyle the overlay, relabel its fields, or add help text / a note / a tooltip inside checkout or login → not supported. The overlay's internals are off limits (Rule 5); put the copy on their own page next to the trigger, and route branding requests to support@tiun.io.
- User is wiring purchase, sign-in, or sign-out actions → match each to its purpose: purchases open
tiun.checkout({ productId }), account entry openstiun.login(), sign-out callstiun.logout(). Keep the app's existing journey (Rule 18). - Errors like "overlay doesn't appear", "methods called before ready" → troubleshooting.
- Project is React Native, or user mentions
@tiun/react-native-sdk,TiunProvider,useTiun, "iOS/Android app", "deep link", "returnUrl", "checkout doesn't come back to the app" → references/react-native.md. Not the WebView section of frameworks.md, and not@tiun/sdk. - User wants time-based billing in a React Native app → not supported by the React Native SDK; say so and point at support@tiun.io.
How can the creator link this skill?
Add the canonical catalog link to the repository README so users can inspect current installs and available audits. The publishing guide covers the complete discovery path.
<a href="https://skillzs.dev/skills/mcp.tiun.business/tiun-sdk">View tiun-sdk on skillZs</a>