# WEARFITS Integration Guide
> Source: https://tryon.wearfits.com/docs/integration.html
> Markdown version for AI/LLM ingestion and developer reference.

For a Shopify-specific rollout guide, see [shopify/README.md](./shopify/README.md).

---

Integrate AI-powered virtual try-on technology into your e-commerce website.

## About WEARFITS Virtual Try-On

WEARFITS is a cutting-edge **generative AI virtual try-on solution** that revolutionizes online fashion shopping. Our technology uses advanced **digital twin technology** to create a personalized 3D avatar from a simple selfie and full-body photo.

The AI then renders selected clothing items onto this digital twin with **photorealistic accuracy**, allowing customers to see exactly how garments will look on their unique body shape before purchasing.

Key benefits include **reduced return rates**, **increased conversion**, and an **engaging shopping experience** that builds customer confidence.

### Core Features

- **Generative AI Technology**: State-of-the-art AI models render clothing with photorealistic quality and accurate fit visualization.
- **Digital Twin Creation**: Create a personalized avatar from just a selfie and body photo - no special equipment needed.
- **Easy Integration**: Multiple integration options: iframe, JavaScript modal, or standalone page with simple API.
- **Mobile Optimized**: Fully responsive design with camera support for on-the-go virtual try-on experiences.

## Table of Contents

- [Overview](#overview)
- [How It Works](#how-it-works)
- [Product JSON Format](#product-json-format)
- [Integration Options](#integration-options)
- [Event Communication](#event-communication)
- [Best Practices](#best-practices)
- [Custom API Access](#custom-api-access)
- [Support](#support)

## Overview

The WEARFITS Virtual Try-On application enables customers to visualize how clothing items would look on them using **AI-powered digital twin technology**. Our generative AI creates photorealistic renderings of garments on personalized avatars, helping customers make confident purchasing decisions.

The application can be integrated into any e-commerce website through three methods:

- **Iframe Embedding** - Embed the app in an iframe and communicate via postMessage
- **JavaScript Modal** - Open the app as a modal overlay using JavaScript
- **Standalone Page** - Link to the app with URL parameters for products, direct step navigation, and pre-loaded avatar

## How It Works

The WEARFITS virtual try-on process uses advanced AI in two main stages:

### 1. Digital Twin Creation

The customer provides a selfie (face photo) and a full-body photo. Our AI analyzes these images to create a personalized **digital twin** - a 3D avatar that accurately represents the customer's body shape, proportions, and appearance. This process takes approximately 30-60 seconds and the digital twin can be reused for multiple try-ons.

### 2. Virtual Garment Rendering

Once the digital twin is created, customers can select clothing items from your product catalog. Our **generative AI** renders each selected garment onto the digital twin with photorealistic accuracy, showing how the clothing would drape, fit, and look on their specific body type. The rendering considers fabric properties, fit, and realistic lighting.

### Supported Product Categories

- **Tops** - T-shirts, blouses, shirts, sweaters, jackets
- **Full Body** - Dresses, jumpsuits, rompers, full outfits
- **Bottoms** - Pants, jeans, skirts, shorts
- **Shoes** - All types of footwear

## Product JSON Format

Products are passed to the application using a standardized JSON format.

### Basic Structure

```json
{
  "products": [
    {
      "id": "product-123",
      "name": "Blue Cotton T-Shirt",
      "category": "top",
      "images": [
        "https://example.com/products/tshirt-lifestyle.jpg",
        "https://example.com/products/tshirt-packshot.jpg"
      ]
    }
  ]
}
```

### Product Fields

| Field | Type | Required | Description |
| --- | --- | --- | --- |
| `id` | string | Yes | Unique product identifier |
| `name` | string | Yes | Product display name |
| `category` | string | Yes | Product category (see below) |
| `images` | array | Yes | Array of image URLs (1-2 images) |
| `default` | boolean | No | If true, product is pre-selected on load |

### Product Categories

| Category | Value | Description |
| --- | --- | --- |
| Tops | `"top"` | T-shirts, blouses, shirts, sweaters |
| Full Body | `"fullBody"` | Dresses, jumpsuits, full outfits |
| Bottoms | `"bottom"` | Pants, skirts, shorts |
| Shoes | `"shoes"` | All footwear |

### Image Array

The `images` array should contain 1-2 URLs:

- `images[0]` - Primary image (lifestyle/model view) used in result preview
- `images[1]` - Secondary image (packshot/product view) used in selection carousel

If only one image is provided, it will be used for both purposes.

Products marked with `default: true` are pre-selected across standalone, iframe, and modal integrations.

## Integration Options

Choose the integration method that best fits your e-commerce platform.

### Iframe Embedding

Embed the WEARFITS app in an iframe and use postMessage for communication. This is the recommended approach for maximum control and seamless integration.

#### HTML Setup

```html
<iframe
  id="wearfits-frame"
  src="https://tryon.wearfits.com"
  style="width: 100%; height: 100vh; border: none;"
  allow="camera"
></iframe>
```

#### JavaScript Integration

```javascript
// Get reference to iframe
const iframe = document.getElementById('wearfits-frame');

// Wait for iframe to be ready
window.addEventListener('message', (event) => {
  // Validate origin in production
  // if (event.origin !== 'https://tryon.wearfits.com') return;

  const { type, payload } = event.data;

  switch (type) {
    case 'WEARFITS_READY':
      // App is ready, send initialization
      initializeApp();
      break;

    case 'WEARFITS_COMPLETE':
      // Try-on completed successfully
      console.log('Result image:', payload.resultImageUrl);
      break;

    case 'WEARFITS_ERROR':
      // An error occurred
      console.error('Error:', payload);
      break;

    case 'WEARFITS_CLOSE':
      // User requested to close
      hideIframe();
      break;
  }
});

// The app sends WEARFITS_READY automatically once the iframe is ready.
// Wait for that event before posting WEARFITS_INIT.

// Initialize the app with products
function initializeApp() {
  iframe.contentWindow.postMessage({
    type: 'WEARFITS_INIT',
    payload: {
      products: [
        {
          id: 'top-001',
          name: 'Classic White Blouse',
          category: 'top',
          default: true,
          images: [
            'https://cdn.example.com/products/blouse-model.jpg',
            'https://cdn.example.com/products/blouse-flat.jpg'
          ]
        }
      ]
    }
  }, '*'); // Replace '*' with specific origin in production
}
```

#### PostMessage Types Reference

| Message Type | Direction | Description |
| --- | --- | --- |
| `WEARFITS_READY` | App → Parent | App loaded and ready for initialization |
| `WEARFITS_INIT` | Parent → App | Initialize with products and config |
| `WEARFITS_SET_PRODUCTS` | Parent → App | Update product list |
| `WEARFITS_COMPLETE` | App → Parent | Try-on completed, includes result URL |
| `WEARFITS_ERROR` | App → Parent | Error occurred |
| `WEARFITS_CLOSE` | App → Parent | User requested to close |

### JavaScript Modal

Open the WEARFITS app as a modal overlay within your website. Great for product detail pages where you want a "Try On" button.

#### Open Modal with JavaScript

```javascript
// Product data from your backend
const currentProduct = {
  id: 'top-001',
  name: 'Classic White Blouse',
  category: 'top',
  default: true,
  images: [
    'https://cdn.example.com/products/blouse-model.jpg',
    'https://cdn.example.com/products/blouse-flat.jpg'
  ]
};

// Configure the modal
window.__WEARFITS_CONFIG__ = {
  products: [currentProduct],
  onComplete: (result) => {
    console.log('Try-on complete!', result.resultImageUrl);
    // Show result to user, save to wishlist, etc.
  },
  onError: (error) => {
    console.error('Try-on failed:', error);
  },
  onClose: () => {
    console.log('Modal closed');
  }
};

window.__WEARFITS_MODAL_MODE__ = true;

// Create and load modal
const container = document.createElement('div');
document.body.appendChild(container);

// Load the modal from your WEARFITS deployment
import('https://tryon.wearfits.com/embed/modal.js')
  .then(({ mountModal }) => {
    mountModal(container, {
      onClose: () => window.__WEARFITS_CONFIG__.onClose?.()
    });
  });
```

### Standalone Page with URL Parameters

Link directly to the WEARFITS app using URL parameters. The simplest integration — no JavaScript required.

#### URL Parameters Reference

| Parameter | Description |
| --- | --- |
| `products` | Encoded product JSON or URL path to a hosted products JSON file |
| `productsUrl` | Legacy alias for a hosted products JSON file URL |
| `step` | Set to `fitting` to open directly on product selection, skipping avatar upload |
| `avatarId` | Pre-load an existing digital twin ID — try-on is immediately available |

#### `products` — Load a Product Catalog

The `products` parameter supports two formats and is auto-detected:

- encoded JSON array or object with a `products` field
- URL to a hosted products JSON file

For short payloads you can pass the product data directly:

```text
https://tryon.wearfits.com/?products=%5B%7B%22id%22%3A%22top-001%22%2C%22name%22%3A%22Classic%20White%20Blouse%22%2C%22category%22%3A%22top%22%2C%22images%22%3A%5B%22https%3A%2F%2Fcdn.example.com%2Fblouse.jpg%22%5D%7D%5D
```

For larger payloads, host a JSON file with your products (see [Product JSON Format](#product-json-format)) and pass its URL as the `products` parameter. The file can be served from your own CDN or from the same origin.

```text
https://tryon.wearfits.com/?products=/products/my-catalog.json
https://tryon.wearfits.com/?products=https://cdn.example.com/tryon-products.json
```

Legacy alias still supported:

```text
https://tryon.wearfits.com/?productsUrl=https://cdn.example.com/tryon-products.json
```

Example products JSON file:

```json
{
  "version": "1.0.0",
  "products": [
    {
      "id": "top-001",
      "name": "Classic White Blouse",
      "category": "top",
      "images": ["https://cdn.example.com/blouse.jpg"]
    },
    {
      "id": "bottom-001",
      "name": "Navy Dress Pants",
      "category": "bottom",
      "images": ["https://cdn.example.com/pants.jpg"]
    }
  ]
}
```

#### `step=fitting` — Skip Avatar Upload

Open the app directly on the product selection screen (step 3), bypassing the photo upload steps. Useful for browsing products or when the avatar is provided separately via `avatarId`.

Without `avatarId`, the **Create Look** button is disabled and displays *"Upload Avatar to Try On"* — the user can browse products but cannot generate a try-on.

```text
https://tryon.wearfits.com/?step=fitting&products=/products/my-catalog.json
```

#### `avatarId` — Pre-load a Digital Twin

Pass an existing digital twin ID to make try-on immediately available without requiring the user to upload photos.

```text
https://tryon.wearfits.com/?step=fitting&products=/products/my-catalog.json&avatarId=dtwin_abc123
```

The provided `avatarId` is automatically saved to a cookie (30-day TTL). On subsequent visits — even without the `avatarId` parameter in the URL — the avatar is restored from the cookie and try-on remains available.

#### Avatar Persistence

Digital twin IDs are persisted in a browser cookie (`wearfits_twin`, 30-day TTL) regardless of how they were created:

| How the twin was created | Saved to cookie |
| --- | --- |
| User uploaded photos and generated a new twin | Yes — automatically on completion |
| `?avatarId=` URL parameter | Yes — on first load |

On subsequent visits the cookie is validated against the API. If the twin is still active, the user is taken directly to product selection. If expired or invalid, they are prompted to create a new one.

## Event Communication

### Handling Results

When a try-on is completed, you receive a result object:

```javascript
{
  resultImageUrl: "https://api.wearfits.com/results/abc123.jpg",
  selectedProducts: [
    { id: "top-001", name: "Classic White Blouse", category: "top" },
    { id: "bottom-001", name: "Navy Dress Pants", category: "bottom" }
  ],
  timestamp: "2024-01-15T10:30:00Z"
}
```

### Error Handling

```javascript
// Error object format
{
  code: "TWIN_CREATION_FAILED",
  message: "Failed to create digital twin. Please try again.",
  details: { /* additional error context */ }
}

// Common error codes:
// - TWIN_CREATION_FAILED: Could not create digital twin
// - FITTING_FAILED: Virtual try-on processing failed
// - INVALID_IMAGE: Image format not supported
// - NETWORK_ERROR: Connection issue
// - TIMEOUT: Processing took too long
```

### Processing Status Notifications (Coming Soon)

The iframe will send postMessage notifications during processing to keep the parent page informed about the try-on status:

```javascript
// Listen for processing status updates
window.addEventListener('message', (event) => {
  if (event.origin !== 'https://tryon.wearfits.com') return;

  const { type, payload } = event.data;

  switch (type) {
    case 'WEARFITS_PROCESSING_START':
      // Try-on processing has started
      // payload: { jobId, jobType: 'twin' | 'fitting' }
      break;

    case 'WEARFITS_PROCESSING_PROGRESS':
      // Progress update during processing
      // payload: { jobId, progress: 0-100, stage: string }
      break;

    case 'WEARFITS_PROCESSING_COMPLETE':
      // Processing finished successfully
      // payload: { jobId, jobType, resultImageUrl }
      break;

    case 'WEARFITS_PROCESSING_ERROR':
      // Processing failed
      // payload: { jobId, jobType, error }
      break;
  }
});
```

These notifications allow you to show custom loading indicators, track analytics, or trigger actions when processing completes.

## Best Practices

### 1. Image Requirements

- Use high-quality product images (minimum 500x500px)
- Ensure consistent lighting and white/neutral backgrounds
- Include both lifestyle and packshot images when available
- Use HTTPS URLs for all images

### 2. Security

- Always validate postMessage origins in production
- Use specific domains instead of '*' in production
- Implement proper CORS headers on your image CDN

```javascript
// Production-safe postMessage handler
window.addEventListener('message', (event) => {
  if (event.origin !== 'https://tryon.wearfits.com') {
    return; // Ignore messages from unknown origins
  }
  // Process message...
});
```

### 3. Performance

- Preload product images for faster loading
- Consider lazy-loading the try-on iframe
- Cache digital twin IDs when possible (handled automatically)

### 4. Job Persistence

The app automatically persists in-progress jobs across page reloads:

- If a user refreshes the page during digital twin creation or virtual fitting, the job will automatically resume
- Pending jobs are stored in localStorage with a 15-minute expiration
- Once the job completes or fails, the pending state is cleared
- This ensures users don't lose their progress if they accidentally navigate away

### 5. Mobile Considerations

- The app is fully responsive and mobile-optimized
- Camera access is required for creating digital twins
- Ensure your iframe allows camera permissions: `allow="camera"`

### 6. Product Selection Logic

- Top + Bottom OR Full Body is required for try-on
- Shoes are optional
- When Full Body is selected, Top and Bottom are cleared
- When Top or Bottom is selected, Full Body is cleared

## Custom API Access

### Building a Custom Try-On Experience?

If you need a **custom try-on viewer** or want to integrate virtual try-on functionality directly into your software, you can use our API directly.

The WEARFITS API provides full access to:

- Digital twin creation
- Virtual fitting generation
- Job status polling
- Result image retrieval

[View API Documentation](https://api.wearfits.com/reference)

## Support

For technical support and API access, [contact our support team](https://wearfits.com/contact?s=support).

Related guide: [View AR Shoes Try-On Integration Guide](https://tryon.wearfits.com/docs/integration-shoes.html)
