### Full Product Page Integration Example (HTML) Source: https://docs.selektable.com/guides/custom-store This HTML example demonstrates a complete product page integration, including basic product details, buttons to add to cart and view in a room, and the Selektable embed script. It utilizes JavaScript functions to handle user interactions and open the Selektable widget with product information and cart callbacks. ```html Modern Blue Sofa - My Shop

Modern Blue Sofa

Modern Blue Sofa

$899.00

``` -------------------------------- ### Handle Selektable SDK Loading Order (Option 1) Source: https://docs.selektable.com/sdk/installation When calling Selektable SDK methods from inline scripts, especially in SPAs, ensure the SDK is loaded first. This example shows how to check for `window.Selektable` before executing SDK functions. ```html ``` -------------------------------- ### Handle Selektable SDK Loading Order (Option 2) Source: https://docs.selektable.com/sdk/installation For scenarios where the SDK might not be immediately available, this option demonstrates using the `load` event listener to ensure SDK methods are called only after the script has fully loaded. ```html ``` -------------------------------- ### Configure Multiple Selektable Widgets Source: https://docs.selektable.com/sdk/installation A single Selektable embed script tag is sufficient for multiple widgets on a page. This example shows how to use `onclick` handlers to open different widgets, demonstrating the SDK's ability to manage multiple instances. ```html ``` -------------------------------- ### Verify Selektable SDK Loading in Console Source: https://docs.selektable.com/sdk/installation After embedding the script, check the browser's developer console to confirm that the `window.Selektable` object is available and contains the expected methods. This verifies the SDK has loaded correctly. ```javascript console.log(window.Selektable); // Should output an object with: open, close, preload, discover, identify, reset, getIdentity, setVisitorId ``` -------------------------------- ### JavaScript Example: Opening Selektable with Product Options Source: https://docs.selektable.com/sdk/product-options Demonstrates how to open the Selektable widget with product-specific options, including ID, title, image, and physical dimensions. This example shows a practical implementation of the ProductOptions object. ```javascript Selektable.open('widget_abc123', { productId: 'sofa-001', productTitle: 'Modern Blue Sofa', productImage: 'https://myshop.com/images/sofa.jpg', dimensions: { width: 220, height: 85, depth: 95, unit: 'cm' } }); ``` -------------------------------- ### Order Webhooks Source: https://docs.selektable.com/guides/custom-store Set up order webhooks to send purchase data to Selektable for conversion tracking and analytics. ```APIDOC ## POST https://app.selektable.com/api/webhooks/orders ### Description Receives order data from your system to track conversions and attribute them to Selektable interactions. ### Method POST ### Endpoint https://app.selektable.com/api/webhooks/orders ### Parameters #### Request Body - **orderId** (string) - Required - The unique identifier for the order. - **storeId** (string) - Required - The identifier for your store. - **customerEmail** (string) - Required - The email address of the customer. - **items** (array) - Required - An array of items included in the order. - **productId** (string) - Required - The unique identifier for the product. - **quantity** (number) - Required - The number of units purchased. - **price** (number) - Required - The price per unit. - **total** (number) - Required - The total amount of the order. - **currency** (string) - Required - The currency of the order (e.g., 'EUR', 'USD'). ### Request Example ```json { "orderId": "order-789", "storeId": "store_xxx", "customerEmail": "customer@example.com", "items": [ { "productId": "prod-456", "quantity": 1, "price": 899.00 } ], "total": 899.00, "currency": "EUR" } ``` ### Response #### Success Response (200) Typically returns a 200 OK status if the webhook is received successfully. Specific response body may vary. #### Response Example ```json { "message": "Order received successfully" } ``` ``` -------------------------------- ### Configure Selektable Widget with Data Attributes Source: https://docs.selektable.com/guides/custom-store Set up the Selektable widget declaratively using HTML data attributes. This approach automatically discovers and registers elements with the `data-selektable-widget` attribute. The widget is then opened when `Selektable.open()` is called, typically from a click event. ```html
``` -------------------------------- ### Open Selektable Widget with Product Data Source: https://docs.selektable.com/quickstart This HTML button uses JavaScript to open a Selektable widget when clicked. It passes a widget ID and product details such as ID, title, image, and URL to the widget. ```html ``` -------------------------------- ### Embed Selektable Widget Script Source: https://docs.selektable.com/quickstart Include this script tag in your HTML before the closing tag to load the Selektable embed functionality. Ensure you replace 'app.selektable.com' with your instance URL if self-hosting. ```html ``` -------------------------------- ### Vue Integration for Opening Selektable Widget Source: https://docs.selektable.com/sdk/examples/advanced This Vue 3 component demonstrates how to open the Selektable widget. It defines a `openWidget` function within the `setup` script that configures and opens the widget, including handling the `onAddToCart` event via a fetch request. ```vue ``` -------------------------------- ### Set Up Order Webhooks with JSON Source: https://docs.selektable.com/guides/custom-store Configure order webhooks by sending a POST request to `https://app.selektable.com/api/webhooks/orders` with a JSON payload containing order details. This enables conversion attribution in your Selektable analytics dashboard. Ensure all required fields like `orderId`, `storeId`, `items`, and `total` are included. ```json { "orderId": "order-789", "storeId": "store_xxx", "customerEmail": "customer@example.com", "items": [ { "productId": "prod-456", "quantity": 1, "price": 899.00 } ], "total": 899.00, "currency": "EUR" } ``` -------------------------------- ### Cart Integration Callbacks Source: https://docs.selektable.com/guides/custom-store This section details how to integrate Selektable with your e-commerce cart. It includes callbacks for adding items to the cart, viewing the cart, and initiating checkout. ```APIDOC ## POST /api/cart/add ### Description Adds a product to the user's shopping cart. ### Method POST ### Endpoint /api/cart/add ### Parameters #### Request Body - **productId** (string) - Required - The unique identifier for the product. - **quantity** (number) - Required - The number of units to add. - **variation** (array) - Optional - An array of objects specifying product variations, e.g., `[{ attribute: 'color', value: 'blue' }]`. ### Request Example ```json { "productId": "prod-456", "quantity": 1, "variation": [ { "attribute": "color", "value": "blue" } ] } ``` ### Response #### Success Response (200) - **success** (boolean) - Indicates if the item was successfully added. - **error** (string) - An error message if the addition failed. - **cartUrl** (string) - Optional URL to redirect the user to after adding the item. #### Response Example ```json { "success": true, "cartUrl": "/cart" } ``` ``` ```APIDOC ## Cart View and Checkout Actions ### Description These are JavaScript callback functions that are triggered by user interactions within the Selektable widget to navigate the user to their cart or the checkout page. ### Method JavaScript Function Calls ### Endpoint N/A (Client-side JavaScript) ### Parameters #### onViewCart Callback This function is called when the user chooses to view their cart. #### onCheckout Callback This function is called when the user chooses to proceed to checkout. ### Request Example ```javascript // Example for onViewCart Selektable.open('widget_abc123', { // ... other options onViewCart: function () { window.location.href = '/cart'; } }); // Example for onCheckout Selektable.open('widget_abc123', { // ... other options onCheckout: function () { window.location.href = '/checkout'; } }); ``` ### Response N/A (These actions typically involve client-side navigation.) ``` -------------------------------- ### Troubleshoot Selektable Widget Loading with JavaScript Source: https://docs.selektable.com/guides/custom-store If the Selektable widget button doesn't function, ensure the embed script has loaded before calling `Selektable.open()`. Wrap your calls in a check for `window.Selektable` to prevent errors if the script is still loading asynchronously. This prevents issues where `Selektable` might be undefined. ```javascript if (window.Selektable) { Selektable.open('widget_abc123', { ... }); } else { console.error('Selektable SDK not loaded yet'); } ``` -------------------------------- ### Variable Product Cart Integration with Selektable Source: https://docs.selektable.com/sdk/examples/cart-integration Shows how to handle products with variations (like size and color) when integrating with Selektable. This example includes defining product variations and attributes, and sending selected variation details to the backend. The `onAddToCart` function is adapted to include variation data. ```javascript Selektable.open('widget_abc123', { productId: 'tshirt-001', productTitle: 'Classic T-Shirt', productImage: 'https://myshop.com/images/tshirt-blue.jpg', type: 'variable', variations: [ { id: 101, attributes: [ { name: 'Color', value: 'Blue' }, { name: 'Size', value: 'M' } ], is_in_stock: true }, { id: 102, attributes: [ { name: 'Color', value: 'Red' }, { name: 'Size', value: 'L' } ], is_in_stock: true } ], attributes: [ { id: 1, name: 'Color', taxonomy: 'pa_color', has_variations: true, terms: [ { id: 10, name: 'Blue', slug: 'blue' }, { id: 11, name: 'Red', slug: 'red' } ] }, { id: 2, name: 'Size', taxonomy: 'pa_size', has_variations: true, terms: [ { id: 20, name: 'M', slug: 'm' }, { id: 21, name: 'L', slug: 'l' } ] } ], onAddToCart: async function (product, quantity, variation) { // variation: [{ attribute: 'Color', value: 'Blue' }, { attribute: 'Size', value: 'M' }] const body = { productId: product.id, quantity: quantity }; if (variation) { body.attributes = {}; variation.forEach(function (v) { body.attributes[v.attribute.toLowerCase()] = v.value; }); } const response = await fetch('/api/cart', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(body) }); return { success: response.ok }; } }); ``` -------------------------------- ### Svelte Integration for Opening Selektable Widget Source: https://docs.selektable.com/sdk/examples/advanced This Svelte component illustrates how to open the Selektable widget. It defines an `openWidget` function that configures and launches the widget with product details and includes an `onAddToCart` handler that makes a POST request to an API endpoint. ```svelte ``` -------------------------------- ### Server-Side Product Data Rendering (React/Next.js) Source: https://docs.selektable.com/integrations/custom-platform This React component example shows how to pass server-side product data to the Selektable SDK. It defines a function to open the widget using data passed as props to the component. ```jsx export default function ProductPage({ product }) { function openWidget() { window.Selektable.open('widget_abc123', { productId: product.id, productTitle: product.name, productImage: product.images[0]?.url, productImages: product.images.map((img, i) => ({ id: i, src: img.url, alt: img.alt })), productUrl: window.location.href }); } return ; } ``` -------------------------------- ### Configure Selektable Widget Using Data Attributes (HTML) Source: https://docs.selektable.com/sdk/examples/basic-usage This HTML example showcases a declarative approach to configuring the Selektable widget using data attributes. The SDK automatically detects these attributes and merges them with any options passed directly to the `Selektable.open()` function, simplifying integration. ```html
``` -------------------------------- ### Simple REST API Cart Integration with Selektable Source: https://docs.selektable.com/sdk/examples/cart-integration Demonstrates how to integrate a simple add-to-cart functionality using a REST API with Selektable. It handles product details, adding to cart, viewing the cart, and checkout actions. This example assumes a basic '/api/cart' endpoint for POST requests. ```javascript Selektable.open('widget_abc123', { productId: 'sofa-001', productTitle: 'Modern Blue Sofa', productImage: 'https://myshop.com/images/sofa.jpg', onAddToCart: async function (product, quantity) { const response = await fetch('/api/cart', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ productId: product.id, quantity: quantity }) }); const data = await response.json(); return { success: response.ok, error: response.ok ? undefined : data.message, cartUrl: '/cart' }; }, onViewCart: function () { window.location.href = '/cart'; }, onCheckout: function () { window.location.href = '/checkout'; } }); ``` -------------------------------- ### Error Handling for Add to Cart with Selektable Source: https://docs.selektable.com/sdk/examples/cart-integration Provides an example of how to implement robust error handling for the `onAddToCart` function in Selektable. It demonstrates catching network errors and handling non-successful HTTP responses from the server, returning specific error messages to the user. ```javascript onAddToCart: async function (product, quantity) { try { const response = await fetch('/api/cart', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ productId: product.id, quantity: quantity }) }); if (!response.ok) { const error = await response.json(); return { success: false, error: error.message || 'Failed to add to cart' }; } return { success: true, cartUrl: '/cart' }; } catch (err) { return { success: false, error: 'Network error. Please try again.' }; } } ``` -------------------------------- ### Add Products to Cart with JavaScript Source: https://docs.selektable.com/guides/custom-store Implement `onAddToCart`, `onViewCart`, and `onCheckout` callbacks to integrate Selektable with your e-commerce cart. The `onAddToCart` callback sends product details to your backend API and returns a success status and optional cart URL. Ensure the Selektable SDK is loaded before calling these functions. ```javascript Selektable.open('widget_abc123', { productId: 'prod-456', productTitle: 'Modern Blue Sofa', productImage: 'https://myshop.com/images/sofa.jpg', // Cart callbacks onAddToCart: async function (product, quantity, variation) { // product: { id, title, price?, image? } // quantity: number // variation: [{ attribute: 'color', value: 'blue' }] (optional) const response = await fetch('/api/cart/add', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ productId: product.id, quantity: quantity, variation: variation }) }); return { success: response.ok, error: response.ok ? undefined : 'Failed to add to cart', cartUrl: '/cart' // Optional: URL to redirect after adding }; }, onViewCart: function () { window.location.href = '/cart'; }, onCheckout: function () { window.location.href = '/checkout'; } }); ``` -------------------------------- ### React Integration for Opening Selektable Widget Source: https://docs.selektable.com/sdk/examples/advanced This React component shows how to integrate the Selektable widget. It uses the `useCallback` hook to create a stable function that opens the widget with product details and handles the `onAddToCart` event. ```jsx import { useCallback } from 'react'; function ProductPage({ product }) { const openWidget = useCallback(() => { if (!window.Selektable) return; window.Selektable.open('widget_abc123', { productId: product.id, productTitle: product.name, productImage: product.images[0]?.url, productImages: product.images.map((img, i) => ({ id: i, src: img.url, alt: img.alt })), productUrl: window.location.href, onAddToCart: async (cartProduct, quantity) => { const res = await addToCart(cartProduct.id, quantity); return { success: res.ok }; } }); }, [product]); return ( ); } ``` -------------------------------- ### Custom Platform Integration (JavaScript) Source: https://docs.selektable.com/integrations/custom-platform This section details the quick setup for integrating Selektable into any website using JavaScript, including adding the embed script, a button, and opening the widget with product data. ```APIDOC ## Custom Platform Integration (JavaScript) ### Description Integrate Selektable with any custom ecommerce platform using the generic JavaScript integration. This works with any website, whether it's built with Next.js, Nuxt, Ruby on Rails, Django, or plain HTML. ### Quick Setup 1. **Add the embed script:** ```html ``` 2. **Add a button:** ```html ``` 3. **Open the widget with product data:** ```javascript function openWidget() { Selektable.open('widget_abc123', { productId: 123, productTitle: 'Product Name', productImage: 'https://example.com/product.jpg', productImages: [ { id: 1, src: 'https://example.com/product.jpg', alt: 'Product' } ], productUrl: 'https://example.com/product', onAddToCart: async function(product, quantity, variation) { // Implement your cart logic const response = await yourCartApi.add(product.id, quantity); return { success: response.ok, error: response.ok ? undefined : 'Failed to add to cart' }; }, onViewCart: function() { window.location.href = '/cart'; }, onCheckout: function() { window.location.href = '/checkout'; } }); } ``` ### Required Parameters for `Selektable.open()` - **productId** (number/string) - Required - Unique identifier for the product. - **productTitle** (string) - Required - The name of the product. - **productImage** (string) - Required - URL of the main product image. ### Optional Parameters for `Selektable.open()` - **productImages** (array) - Optional - An array of image objects for the product. Each object should have `id`, `src`, and `alt` properties. - **productUrl** (string) - Optional - The URL of the product page. - **onAddToCart** (function) - Optional - Callback function executed when the "Add to Cart" action is triggered. It should return an object with `success` (boolean) and `error` (string, if `success` is false). - **onViewCart** (function) - Optional - Callback function executed when the "View Cart" action is triggered. - **onCheckout** (function) - Optional - Callback function executed when the "Checkout" action is triggered. ### Other Integrations - **Order Webhook**: To track conversions, send order data to `POST https://app.selektable.com/api/webhooks/orders`. - **Identity**: Call `Selektable.identify()` for logged-in users. - **Preloading**: Call `Selektable.preload()` for instant widget opening. ``` -------------------------------- ### Open Selektable Widget with Multiple Product Images (JavaScript) Source: https://docs.selektable.com/sdk/examples/basic-usage This JavaScript example shows how to open the Selektable widget with an array of product images. It allows customers to visualize different angles of a product, enhancing the shopping experience. The `productImage` property sets the primary image for AI generation, while `productImages` provides the full gallery. ```javascript Selektable.open('widget_abc123', { productId: 'sofa-001', productTitle: 'Modern Blue Sofa', productImage: 'https://myshop.com/images/sofa-front.jpg', productImages: [ { id: 1, src: 'https://myshop.com/images/sofa-front.jpg', alt: 'Front view' }, { id: 2, src: 'https://myshop.com/images/sofa-side.jpg', alt: 'Side view' }, { id: 3, src: 'https://myshop.com/images/sofa-top.jpg', alt: 'Top view' } ], productUrl: 'https://myshop.com/products/modern-blue-sofa' }); ``` -------------------------------- ### Open Different Widget Types Based on Product Category (JavaScript) Source: https://docs.selektable.com/sdk/examples/advanced This JavaScript function demonstrates how to open different Selektable widgets based on a product's category. It selects either a virtual try-on widget or a room visualizer widget and opens it with product-specific details. ```javascript function openVisualizer(product) { // Choose widget based on product category var widgetId = product.category === 'clothing' ? 'widget_tryon' // Virtual Try-On : 'widget_room'; // Room Visualizer Selektable.open(widgetId, { productId: product.id, productTitle: product.name, productImage: product.image, productUrl: product.url }); } ``` -------------------------------- ### Simple REST API Cart Integration Example (JavaScript) Source: https://docs.selektable.com/guides/cart-integration An example implementation of the `onAddToCart` callback using a simple REST API POST request. It sends product details and quantity to a '/api/cart' endpoint and returns a success status along with a cart URL based on the API response. ```javascript onAddToCart: async function (product, quantity) { const response = await fetch('/api/cart', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ productId: product.id, quantity: quantity }) }); if (!response.ok) { return { success: false, error: 'Could not add to cart' }; } return { success: true, cartUrl: '/cart' }; } ``` -------------------------------- ### Full Example: Product Page Tracking Widget Events to GA4 Source: https://docs.selektable.com/guides/analytics-events This HTML example demonstrates a product page that embeds the Selektable widget and tracks all its events to Google Analytics 4. It includes the widget embed script, a button to open the widget, and a JavaScript listener to capture and send widget messages to GA4. It also includes a note on filtering messages to ensure only Selektable-related events are processed. ```html ``` -------------------------------- ### Selektable Widget Context Element (HTML) Source: https://docs.selektable.com/sdk/methods An example HTML element demonstrating how to define a Selektable widget context using data attributes. These attributes provide the widget ID and product information, which are used by `Selektable.discover()`. ```html
``` -------------------------------- ### Shopify AJAX Cart Integration Example (JavaScript) Source: https://docs.selektable.com/guides/cart-integration An example for integrating with Shopify's AJAX cart API. It sends a POST request to '/cart/add.js' with product ID and quantity in JSON format. The callback returns a success status and a cart URL upon a successful response. ```javascript onAddToCart: async function (product, quantity) { const response = await fetch('/cart/add.js', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ id: product.id, quantity: quantity }) }); return { success: response.ok, cartUrl: '/cart' }; } ``` -------------------------------- ### Server-Side Product Data Rendering (Django Template) Source: https://docs.selektable.com/integrations/custom-platform This example illustrates how to embed server-side product data within a Django template for use with the Selektable SDK. It uses Django's template tags to access and format the product information. ```html ``` -------------------------------- ### Manage User Identity with Selektable (JavaScript) Source: https://docs.selektable.com/sdk/examples/advanced This JavaScript code shows how to manage user identity with the Selektable SDK. It includes functions for identifying users upon login, resetting identity on logout, and restoring identity for logged-in users on page load. ```javascript // On login async function onLogin(user) { Selektable.identify(user.id, { name: user.name, email: user.email }); } // On logout function onLogout() { Selektable.reset(); } // On page load: restore identity for logged-in users window.addEventListener('load', function () { var user = getAuthenticatedUser(); if (user) { Selektable.identify(user.id, { name: user.name, email: user.email }); } }); ``` -------------------------------- ### Conditionally Load Widget on Product Pages (HTML) Source: https://docs.selektable.com/sdk/examples/advanced This script loads the Selektable embed script only on pages that contain a product identifier. It dynamically creates and appends a script tag to the document's body if a '[data-product-id]' element is found. ```html ``` -------------------------------- ### Handle Dynamic Product Changes in SPAs (JavaScript) Source: https://docs.selektable.com/sdk/examples/basic-usage This JavaScript example is designed for single-page applications (SPAs) where product information changes without a full page reload. The `onProductChange` function updates the `onclick` handler for the 'try-on' button with new product data, ensuring the Selektable widget displays the correct item. ```javascript // When product changes in your SPA function onProductChange(product) { // Just pass the new product data when opening document.getElementById('try-on-btn').onclick = function () { Selektable.open('widget_abc123', { productId: product.id, productTitle: product.name, productImage: product.image, productImages: product.images.map(function (img, i) { return { id: i, src: img.url, alt: img.alt }; }), productUrl: window.location.href }); }; } ``` -------------------------------- ### Server-Side Conversion Tracking Webhook (Node.js, PHP) Source: https://docs.selektable.com/guides/conversion-tracking These server-side code examples show how to receive form submission data, including `visitorId` and `sessionId`, and then send this information as a conversion event to the Selektable API. Both Node.js and PHP implementations are provided, requiring an API key for authentication. ```javascript app.post('/appointment/book', async (req, res) => { const { visitorId, sessionId, name, email, phone } = req.body; // Save the appointment in your system const appointment = await saveAppointment({ name, email, phone }); // Track the conversion in Selektable await fetch('https://app.selektable.com/api/webhooks/orders', { method: 'POST', headers: { 'Content-Type': 'application/json', 'Authorization': 'Bearer sel_your_api_key' }, body: JSON.stringify({ orderId: 'appt-' + appointment.id, storeId: 'store_xxx', organizationId: 'org_xxx', visitorId: visitorId, sessionId: sessionId, totalCents: 0, currency: 'USD', platform: 'custom', status: 'completed', orderCreatedAt: new Date().toISOString(), items: [] }) }); res.redirect('/thank-you'); }); ``` ```php $visitor_id = $_POST['visitorId']; $session_id = $_POST['sessionId']; // Save the appointment in your system $appointment_id = save_appointment($_POST); // Track the conversion in Selektable $payload = json_encode([ 'orderId' => 'appt-' . $appointment_id, 'storeId' => 'store_xxx', 'organizationId' => 'org_xxx', 'visitorId' => $visitor_id, 'sessionId' => $session_id, 'totalCents' => 0, 'currency' => 'USD', 'platform' => 'custom', 'status' => 'completed', 'orderCreatedAt' => date('c'), 'items' => [], ]); $ch = curl_init('https://app.selektable.com/api/webhooks/orders'); curl_setopt($ch, CURLOPT_POST, true); curl_setopt($ch, CURLOPT_POSTFIELDS, $payload); curl_setopt($ch, CURLOPT_HTTPHEADER, [ 'Content-Type: application/json', 'Authorization: Bearer sel_your_api_key', ]); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); curl_exec($ch); curl_close($ch); ``` -------------------------------- ### Configure Product Images for Selektable Widget (JavaScript) Source: https://docs.selektable.com/guides/product-image Demonstrates how to use `Selektable.open()` to pass specific `productImage` for AI generation and `productImages` for the widget's gallery in a custom integration. This requires the Selektable library to be loaded. ```javascript Selektable.open('widget_abc123', { productId: 'sofa-001', productTitle: 'Modern Blue Sofa', // Use the clean product photo for AI generation productImage: 'https://myshop.com/images/sofa-isolated.jpg', // The full gallery (including lifestyle shots) displayed in the widget productImages: [ { id: 1, src: 'https://myshop.com/images/sofa-isolated.jpg', alt: 'Product photo' }, { id: 2, src: 'https://myshop.com/images/sofa-lifestyle.jpg', alt: 'In living room' }, { id: 3, src: 'https://myshop.com/images/sofa-detail.jpg', alt: 'Fabric detail' } ] }); ``` -------------------------------- ### Customer Identification Source: https://docs.selektable.com/guides/custom-store Identify logged-in customers by their user ID to associate their activity with their account for more accurate tracking. ```APIDOC ## Selektable.identify(userId, traits) ### Description Associates a visitor with a unique user ID and optional traits (like name and email) for improved user tracking and personalization. ### Method JavaScript Function Call ### Endpoint N/A (Client-side JavaScript) ### Parameters - **userId** (string) - Required - The unique identifier for the customer. - **traits** (object) - Optional - An object containing user properties. - **name** (string) - Optional - The customer's name. - **email** (string) - Optional - The customer's email address. ### Request Example ```javascript Selektable.identify('user-123', { name: 'John Doe', email: 'john@example.com' }); ``` ### Response N/A (This is a client-side function call.) ``` -------------------------------- ### Identify Customers with JavaScript Source: https://docs.selektable.com/guides/custom-store Associate website visitors with their user IDs using `Selektable.identify()` after login or when an authenticated user's details are available. This function takes a user ID and an optional object containing user properties like name and email for improved tracking. Refer to the Identity Tracking guide for more details. ```javascript // After login or page load with authenticated user Selektable.identify('user-123', { name: 'John Doe', email: 'john@example.com' }); ``` -------------------------------- ### Fetch Product Data and Open Widget (JavaScript) Source: https://docs.selektable.com/integrations/custom-platform This snippet demonstrates how to fetch product data from a client-side API endpoint and then use that data to initialize and open a Selektable widget. It requires the Selektable SDK to be loaded and assumes an API endpoint returning product information in JSON format. The output is the opened widget with pre-filled product details. ```javascript const product = await fetch('/api/products/123').then(r => r.json()); Selektable.open('widget_abc123', { productId: product.id, productTitle: product.name, productImage: product.images[0].url, productImages: product.images.map((img, i) => ({ id: i, src: img.url, alt: img.alt || product.name })), productUrl: window.location.href }); ``` -------------------------------- ### Open Widget with Initial Product Data (JavaScript) Source: https://docs.selektable.com/sdk/examples/multi-product Opens the Selektable widget for a single product, which serves as the initial product when multi-product mode is enabled. This function requires product details like ID, title, and image sources. ```javascript Selektable.open('widget_room', { productId: 'sofa-001', productTitle: 'Modern Blue Sofa', productImage: 'https://myshop.com/images/sofa.jpg', productImages: [ { id: 1, src: 'https://myshop.com/images/sofa.jpg', alt: 'Blue Sofa' } ] }); ``` -------------------------------- ### Preload Widget with JavaScript Source: https://docs.selektable.com/guides/widgets Demonstrates how to preload an iframe for faster widget opening using the Selektable JavaScript library. This involves calling `Selektable.preload()` on page load and `Selektable.open()` when the user interacts. ```javascript Selektable.preload('widget_abc123'); Selektable.open('widget_abc123', { ... }); ``` -------------------------------- ### Open Selektable Widget with JavaScript API Source: https://docs.selektable.com/guides/custom-store Integrate the Selektable widget into your website using the JavaScript API. This method allows you to dynamically open the widget with product data when a user interacts with a button. It requires a widget ID and product details such as ID, title, images, and URL. ```javascript document.getElementById('try-on-btn').addEventListener('click', function () { Selektable.open('widget_abc123', { // Required productId: 'prod-456', productTitle: 'Modern Blue Sofa', // Primary image used for AI generation productImage: 'https://myshop.com/images/sofa-main.jpg', // All product images (displayed in widget) productImages: [ { id: 1, src: 'https://myshop.com/images/sofa-front.jpg', alt: 'Front view' }, { id: 2, src: 'https://myshop.com/images/sofa-side.jpg', alt: 'Side view' }, { id: 3, src: 'https://myshop.com/images/sofa-back.jpg', alt: 'Back view' } ], // Product page URL productUrl: 'https://myshop.com/products/modern-blue-sofa' }); }); ``` -------------------------------- ### WooCommerce AJAX Cart Integration Example (JavaScript) Source: https://docs.selektable.com/guides/cart-integration Provides an example of integrating with WooCommerce using its AJAX add-to-cart functionality. It constructs a `FormData` object with product details and variations, then sends it to the WooCommerce AJAX endpoint. The success is determined by the response status. ```javascript onAddToCart: async function (product, quantity, variation) { const formData = new FormData(); formData.append('product_id', product.id); formData.append('quantity', quantity); if (variation) { variation.forEach(function (v) { formData.append('attribute_' + v.attribute, v.value); }); } const response = await fetch('/?wc-ajax=add_to_cart', { method: 'POST', body: formData }); return { success: response.ok }; } ``` -------------------------------- ### Product Context Resolution Source: https://docs.selektable.com/sdk/product-options Explains the priority order in which the widget resolves product data. ```APIDOC ## Product Context Resolution ### Description Explains the priority order in which the widget resolves product data. ### Method N/A ### Endpoint N/A ### Parameters N/A ### Request Example N/A ### Response N/A ### Priority Order: 1. **Explicit options** passed to `Selektable.open(widgetId, options)` — highest priority 2. **Data attributes** on the context element (`data-selektable-widget`) 3. **Auto-detection** from the page DOM (WooCommerce body classes, JSON-LD, variation forms, etc.) **Note:** Auto-detection is primarily designed for WooCommerce pages. For custom platforms, explicitly pass product data via `Selektable.open()` options. ``` -------------------------------- ### Firebase/Firestore Cart Integration with Selektable Source: https://docs.selektable.com/sdk/examples/cart-integration Illustrates how to integrate Selektable's `onAddToCart` function with Firebase Firestore for managing cart data. This example uses Firestore's `doc`, `updateDoc`, and `arrayUnion` to add items to a user's cart document. It assumes `db` and `currentUser` are available in the scope. ```javascript onAddToCart: async function (product, quantity) { const { doc, updateDoc, arrayUnion } = await import('firebase/firestore'); const cartRef = doc(db, 'carts', currentUser.uid); await updateDoc(cartRef, { items: arrayUnion({ productId: product.id, title: product.title, quantity: quantity, addedAt: new Date() }) }); return { success: true, cartUrl: '/cart' }; } ``` -------------------------------- ### Get Identity Source: https://docs.selektable.com/sdk/identity Returns the current identity object, including visitor ID, session ID, anonymous ID, and optionally user ID and traits. ```APIDOC ## getIdentity() ### Description Returns the current identity object. ### Method `getIdentity` ### Request Example ```javascript const identity = Selektable.getIdentity(); ``` ### Response #### Success Response (200) - **visitorId** (string) - Persistent browser ID - **sessionId** (string) - Current session ID - **anonymousId** (string) - Anonymous ID (initially same as visitorId) - **userId** (string) - Optional - Set after identify() is called - **traits** (Record) - Optional - Set after identify() is called ``` -------------------------------- ### Server-Side Product Data Rendering (HTML/EJS/Jinja2) Source: https://docs.selektable.com/integrations/custom-platform This code demonstrates how to render product data server-side using templating engines like EJS, Jinja2, or Handlebars. The data is embedded in a script tag, making it accessible to the Selektable SDK on the client-side. ```html ```