Developer docs
Embed try-on in minutes, not weeks
One script tag puts a working try-on on any product page. No app store, no theme rebuild, no backend — just an API key and a single snippet.
Getting started
The widget needs just one thing from you: an API key. The key is a long string that looks like tryon_live_xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx. It lets our API confirm which store the request comes from — nothing about your customers’ photos or data touches your server.
API keys are created by the team as part of your onboarding. Contact us if you haven’t received one yet. Keep it secret: anyone with the key can trigger try-ons against your credits.
One key per integration. Generate a separate key for each storefront or staging environment, so you can revoke one without affecting the others.
Beyond the key, the widget needs a way to know which reference image is on the current product. You pass that as the fabricImageUrl — the product’s featured image, or the specific fabric swatch the visitor is looking at. For ready-made garments (shirt, t-shirt, one-piece, swimwear) you can pass a dedicated productImageUrl that takes precedence over the fabric URL.
Catalog mode & garment types
Every store is either fabric-based or ready-made — set your “What do you sell?” checkboxes on the dashboard and the widget automatically adapts. Fabric-based stores render the fabric into a garment first (a shared, cached fabric→garment step), then fit it to the model. Ready-made stores skip any type picker — a single generic prompt identifies the garment straight from the product photo.
Fabric-based catalogs are grouped by category (Women / Men) with a garment-type picker per category. Each store decides which types it actually offers — the dashboard exposes a “Garment catalog” toggle for every fabric type. Only the checked types are shown to visitors; a category with nothing enabled disappears from the widget.
Women
Men
Widgets default to the Women category and remember the visitor’s last choice for the product. The type chosen is stored per product on your side and passed as garmentType; if you leave one off, the widget selects the first enabled type of the active category.
Ready-made items send the canonical ready-made garment type. The legacy per-item names shirt, t-shirt, one-piece, and swimwear are still accepted by the API for backward compatibility, but widgets never offer them.
Shopify (manual install)
First create an API key for the store in Dashboard → API keys (shown once), and lock it to the storefront domain. Then open the theme — Online Store → Themes → Edit code — and paste this into the product template near the “Add to cart” button. It reads the product’s id, title and per-variant colour images automatically, so it works across the catalogue; changing the swatch re-targets the live widget, and the widget’s “Buy now” adds that exact colour and opens the cart drawer.
{%- if template contains 'product' -%}
{%- comment -%} Variant id → colour image, so the try-on follows the swatch {%- endcomment -%}
<script>
window.__TRYON_VARIANTS__ = {
{%- for v in product.variants -%}
{{ v.id | json }}: {%- if v.featured_image -%}{{ v.featured_image | image_url: width: 800 | json }}{%- else -%}null{%- endif -%}{%- unless forloop.last -%},{%- endunless -%}
{%- endfor -%}
};
window.__TRYON_DEFAULT_IMAGE__ = {%- if product.featured_image -%}{{ product.featured_image | image_url: width: 800 | json }}{%- else -%}null{%- endif -%};
window.__TRYON_SELECTED_VARIANT__ = {{ product.selected_or_first_available_variant.id | json }};
</script>
<div id="tryon-widget"></div>
<script src="https://tryon.yourdomain.com/tryon-widget.js"></script>
<script>
(function () {
var ORIGIN = "https://tryon.yourdomain.com";
var API_KEY = "tryon_live_xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"; // Dashboard → API keys (shown once)
if (!window.TryOn) { console.warn("[TryOn] widget script failed to load"); return; }
function selectedVariantId() {
var form = document.querySelector('form[action*="/cart/add"]');
var field = form && form.querySelector('[name="id"]');
if (!field) field = document.querySelector('select[name="id"]');
return (field && field.value) || String(window.__TRYON_SELECTED_VARIANT__ || "");
}
function imageFor(id) {
return (window.__TRYON_VARIANTS__ || {})[String(id)] || window.__TRYON_DEFAULT_IMAGE__;
}
function quantity() {
var q = document.querySelector('form[action*="/cart/add"] [name="quantity"]');
return q && Number(q.value) > 0 ? Number(q.value) : 1;
}
var handle = window.TryOn.render({
container: "#tryon-widget",
apiKey: API_KEY,
apiBaseUrl: ORIGIN,
productId: {{ product.id | json }},
productName: {{ product.title | json }},
productUrl: {{ canonical_url | json }},
fabricImageUrl: imageFor(selectedVariantId()),
garmentType: "saree",
buyUrl: {{ product.url | json }},
buyLabel: "Buy now",
launchLabel: "Virtual Try On",
onBuyNow: function (ctx) { addToCartAndOpenDrawer(selectedVariantId(), quantity(), ctx); }
});
/* Keep the live widget on the colour the shopper is now viewing. */
function syncColour() {
if (handle && handle.update) handle.update({ fabricImageUrl: imageFor(selectedVariantId()) });
}
document.addEventListener("change", function (e) {
if (e.target && e.target.name === "id") syncColour();
});
document.addEventListener("variant:change", syncColour);
document.addEventListener("product:variant-change", syncColour);
/* Add the tried-on colour, then open the cart drawer (not the /cart page). */
function addToCartAndOpenDrawer(variantId, qty, ctx) {
var id = Number(variantId);
if (!id) { location.href = "/cart"; return; }
fetch("/cart/add.js", {
method: "POST",
headers: { "Content-Type": "application/json", "Accept": "application/json" },
body: JSON.stringify({ items: [{ id: id, quantity: qty || 1 }] })
})
.then(function (r) { if (!r.ok) throw new Error("add failed"); return r.json(); })
/* Stamp the try-on id on the cart so the order webhook can attribute it. */
.then(function () {
if (!ctx || !ctx.generationId) return null;
return fetch("/cart/update.js", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ attributes: {
_tryon_generation: ctx.generationId,
_tryon_visitor: ctx.visitorId || "",
_tryon_product: ctx.productId || ""
} })
});
})
.then(function () { return fetch("/cart.js").then(function (r) { return r.json(); }); })
.then(function (cart) {
document.querySelectorAll("[data-cart-count], .cart-count, #cart-count").forEach(function (el) {
el.textContent = cart.item_count;
});
if (!openCartDrawer()) location.href = "/cart";
})
.catch(function () { location.href = "/cart"; });
}
/* The one theme-specific line: open the shop's cart drawer. */
function openCartDrawer() {
var drawer = document.querySelector("cart-drawer, .cart-drawer, #CartDrawer, #cart-drawer");
try {
if (drawer && typeof drawer.open === "function") { drawer.open(); return true; } /* Dawn */
if (drawer && typeof drawer.show === "function") { drawer.show(); return true; }
if (drawer) { drawer.classList.add("is-open", "open", "active"); drawer.removeAttribute("hidden"); }
document.dispatchEvent(new CustomEvent("cart:open"));
document.dispatchEvent(new CustomEvent("cart-drawer:open"));
if (drawer) return true;
} catch (e) {}
return false;
}
})();
</script>
{%- endif -%}That’s the entire storefront installation. No app, no theme app extension, no setup screen — the widget loads the script from our CDN and does everything else itself.
Sales attribution (optional)
The try-on works without this. To see purchases that followed a try-on in the dashboard, forward Shopify’s orders/create webhook to our sales endpoint. The widget above stamps the try-on id on the cart; this bridge verifies Shopify’s HMAC signature and relays the order server-side.
// app/api/shopify-order-webhook/route.ts (Next.js / Vercel)
import crypto from "crypto";
const TRYON_ORIGIN = process.env.TRYON_ORIGIN!; // https://tryon.yourdomain.com
const TRYON_SALES_KEY = process.env.TRYON_SALES_API_KEY!; // server-only key (scripts/create-server-key.js)
const SHOPIFY_SECRET = process.env.SHOPIFY_WEBHOOK_SECRET!; // custom app API secret
export async function POST(req: Request) {
const raw = await req.text();
const hmac = req.headers.get("x-shopify-hmac-sha256") || "";
const digest = crypto
.createHmac("sha256", SHOPIFY_SECRET)
.update(raw, "utf8")
.digest("base64");
const ok =
hmac.length === digest.length &&
crypto.timingSafeEqual(Buffer.from(hmac), Buffer.from(digest));
if (!ok) return new Response("bad hmac", { status: 401 });
const order = JSON.parse(raw);
const attrs: Record<string, string> = {};
for (const a of order.note_attributes || []) attrs[a.name] = a.value;
const gen = attrs._tryon_generation || "";
const generationId =
/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(gen) ? gen : null;
const payload = {
orderId: String(order.id),
currency: order.currency,
soldAt: order.created_at,
generationId,
visitorId: attrs._tryon_visitor || null,
generationProductId: attrs._tryon_product || null,
lineItems: (order.line_items || []).map((li: any) => ({
productId: String(li.product_id),
productName: li.title,
qty: li.quantity,
price: Number(li.price),
})),
};
const res = await fetch(TRYON_ORIGIN + "/api/tryon/sales", {
method: "POST",
headers: {
Authorization: "Bearer " + TRYON_SALES_KEY,
"Content-Type": "application/json",
},
body: JSON.stringify(payload),
});
return new Response(res.ok ? "ok" : "forward failed", { status: res.ok ? 200 : 502 });
}Point a Shopify custom-app webhook (topic orders/create, JSON) at that route, and mint the TRYON_SALES_API_KEY with node scripts/create-server-key.js <merchantId> "Shopify orders". It must be a server-only key — the storefront key is rejected by the sales endpoint by design.
WordPress
With WooCommerce, add a Custom HTML block to your product page template, or drop it straight into the theme’s content-product.php template if you’re comfortable editing PHP files. For a manually-managed product catalogue, hard-code the image URL in place of the placeholder below.
<div id="tryon-widget"></div>
<script src="https://tryon.yourdomain.com/tryon-widget.js"></script>
<script>
TryOn.render({
container: "#tryon-widget",
apiKey: "tryon_live_xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx",
productId: "MY_PRODUCT_ID",
fabricImageUrl: "https://your-store.com/path/to/fabric-image.jpg",
garmentType: "saree"
});
</script>To glue the widget to WooCommerce storefront data (variant images, fields like SKUs), read those values into variables before calling TryOn.render — the script works with any values you feed it.
Custom sites
For anything else — React, Vue, plain HTML — load the script once on the product page and call TryOn.render wherever the button should appear.
<div id="tryon-widget"></div>
<script src="https://tryon.yourdomain.com/tryon-widget.js"></script>
<script>
TryOn.render({
container: "#tryon-widget",
apiKey: "tryon_live_xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx",
productId: "saree-1234",
fabricImageUrl: "https://your-store.com/images/saree-1234.jpg",
garmentType: "saree",
productName: "Handloom Cotton Saree"
});
</script>If you’re on React, you can use the component directly instead of the script tag:
import { TryOnWidget } from "@tryon/widget";
export function ProductPage({ product }) {
return (
<TryOnWidget
apiKey="tryon_live_xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"
productId={product.id}
fabricImageUrl={product.imageUrl}
productName={product.name}
fabrics={product.variants}
/>
);
}All network traffic goes to our API only — the widget never talks to any other service, and customer photos are used only to create the preview.
API key security
Your key is a bearer credential — anyone who copies it can trigger try-ons against your credits. The dashboard lets you lock a key to a list of storefront domains (for example shop.mystore.com). A locked key is rejected with a 403 unless the request’s Origin matches one of the allowed domains, or a subdomain of it.
Scope & limits. Domain locking makes casual copying harder, but it is not a hard security boundary: a determined attacker can spoof headers from their own server. Lock your key to the exact production storefront(s) it serves, keep one key per integration, and treat a locked key as a helper rather than a failsafe.
Widget options
TryOn.render({…}) (standalone) and <TryOnWidget /> (React) accept the same set of options.
| Option | Required | Notes |
|---|---|---|
| apiKey | Yes | tryon_live_… |
| container | Standalone only | Selector or element the widget mounts into. |
| productId | No | Used in download filenames and share text. |
| fabricImageUrl | Fabric stores | Fabric swatch / featured image. Drives the per-category (Women / Men) picker shown to fabric-mode customers, limited to the store’s enabled garment types. Mutually sufficient with productImageUrl. |
| productImageUrl | Ready-made stores | Product photo for ready-made mode. When both URLs are set and the store sells both, fabric mode wins. |
| garmentType | No | Default selected type — one of saree, suit, co-ord set, lehenga, kurta set (Women) or men-shirt, men-pant, men-blazer, men-kurta, men-sherwani (Men). Defaults to the first enabled Women’s type (saree). |
| productName | No | Shown in the widget preview row. |
| merchantName | No | Modal title; falls back to the account name resolved from the key. |
| apiBaseUrl | No | API host; defaults to the same origin. |
| position | No | corner (default) — floating bottom-right panel, no backdrop, always fully visible; the panel is rendered at the page root so it docks to the true viewport even when theme wrappers apply CSS transforms. Docks full-width on small screens. modal — centred dialog with a full-screen backdrop. |
| buttonBorderRadius buttonBackgroundColor buttonTextColor buttonFontWeight | No | Optional launch-button overrides so the button can match your theme (corner radius, background color, text color, font weight). Any unset value keeps the default gradient pill. The widget inherits your site’s font family automatically. |
API reference
You normally never need to call the API yourself — the widget does. This reference documents exactly what happens on the wire, which is useful for testing and debugging your embed.
POST /api/tryon/generate
Creates one try-on generation. Called with multipart/form-data, authenticated with your API key in the Authorization header.
| Field | In | Required | Notes |
|---|---|---|---|
| Authorization | Header | Yes | Bearer tryon_live_… |
| garmentType | Form | Yes | One of saree, suit, co-ord set, lehenga, kurta set (Women), men-shirt, men-pant, men-blazer, men-kurta, men-sherwani (Men), ready-made (or a legacy shirt / t-shirt / one-piece / swimwear name for backward compatibility). A store that hasn’t enabled the requested fabric type gets a 400. |
| fabricImage | Form (file) | For saree / suit / co-ord set / lehenga / kurta set and the men’s fabric types | Fabric swatch. JPEG/PNG/WebP, max 10 MB |
| productImage | Form (file) | For ready-made / shirt / t-shirt / one-piece / swimwear | Product photo. JPEG/PNG/WebP, max 10 MB |
| fabricImageUrl / productImageUrl | Form | No | Reference URL matching the image field for the garment type. For fabric-based types it keys the shared fabric→garment render cache (recommended); otherwise it is stored as provenance. |
| customerImage | Form (file) | Yes | JPEG/PNG/WebP, max 10 MB |
Success — 200
{
"generationId": "…",
"resultImageUrl": "https://…signed-url…",
"status": "success",
"usedCachedRender": false
}The resultImageUrl is a temporary signed link (valid 1 hour). Likely-young browsers can show it directly; your server never needs to proxy it. usedCachedRender reports whether a fabric-to-garment render from the shared cache was reused. Credit cost follows: a cache hit (render already saved for that fabric URL + type) charges 1 credit, a fresh fabric+type that must be rendered charges 2, and ready-made charges 1.
Errors
| Status | Meaning |
|---|---|
| 400 | Validation failed — missing field or unsupported file type/size |
| 401 | Missing, malformed, or revoked API key |
| 402 | Not enough credits — a fresh fabric+type needs 2, a cached or ready-made generation needs 1 |
| 404 | Merchant not found |
| 429 | Rate limit exceeded — see below |
| 500 | Generation failed on our side. Retry, ideally after a short delay. |
GET /api/tryon/config
Resolves embed-level configuration for a key: branding, any per-session try-on counter, and the merchant’s catalog mode. The widget calls this automatically on open.
| Field | Meaning |
|---|---|
| removeBranding | Whether to hide the “Powered by TryOn” badge. |
| merchantName | Store name shown in the widget header. |
| limitActive / remaining | Per-session try-on counter state, when configured. |
| catalogMode | "fabric" or "garment". Fabric shows the per-category type picker; garment skips the picker and the generic prompt identifies whatever item is in the photo. |
| enabledGarmentTypes | string[] — the fabric types this store offers (fabric mode). Widgets filter the picker by category against this list and hide a category with nothing enabled. |
The generate endpoint enforces the same value server-side, returning a 400 if a request uses a pipeline the store isn’t configured to run or a fabric type the store hasn’t enabled.
Rate limits
As a safety net, each API key is limited to 6 generation requests per minute — image generation is slow and expensive, so this cap simply catches a misconfigured integration that would otherwise spin in a loop. It’s a per-instance, in-memory limiter (a friendly nudge rather than a hard SLA). Requests that exceed the cap get a 429 response. A healthy embed never hits it.
Ready to try it on your store?
We’ll set you up with an API key and walk through your first embed on a staging page.
Get an API key