Initialize the Rep AI Web-Client
Follow the steps described below to initialize the REP AI web client:
Inject this CDN URL into the website's root file. https://d1o5e9vlirdalo.cloudfront.net/initRepConfig.min.js
-
Use this script to initialize the chat
(function () { var config = { partnerKey: "{{account_key}}", analyticsProcessingAllowed: true, localization: "{{localization}}", currencySymbol: "{{currencySymbol}}", // optional, default value USD }; function init() { window.initRepConfig(config); } if (typeof window.initRepConfig === "function") { init(); } else { window.addEventListener("initRepConfigReady", init); } })();
{{account_key}} - Required field. It has to be replaced by the value that REP AI provides to identify each Rep AI account.
{{currencySymbol}} - Optional field. Default value “USD”. ISO 4217 CurrencyCode - Storefront API
{{localization}} - Required field. ISO country code 2 letters. https://shopify.dev/docs/api/storefront/2025-01/enums/countrycode
{{analyticsProcessingAllowed}} - Required field. It should be false if a Cookie consent banner appears on a website and/or the user disapproves of the Cookie Consent. In any other case, it should be true.
Cases:
The website is not using the Cookie consent banner - analyticsProcessingAllowed: true
The website using the Cookie consent banner - analyticsProcessingAllowed: false
The website uses the Cookie consent banner, and the user already approved it before the chat initialization - analyticsProcessingAllowed: true
-
Every page load should trigger an event that tracks the “page viewed” event.
window.rep.triggerEvent("PAGE_VIEWED", {{eventData}});
eventData - an object containing information about the page, which is important for the AI to deliver the correct behavior. The fields which have to be sent per each event can be found in the section: Mapping from Shopify frontend fields to Rep AI events.
PAGE_VIEWED should be triggered when every page loads. This is a general event that occurs in combination with other page-viewed events listed in the next step.
-
Every page load should trigger a second event specific to the page type:
After sending the general PAGE_VIEWED event on page load, each page should trigger a special page load event based on the page type.
window.rep.triggerEvent({{EVENT_TYPE}}, {{eventData}});
EVENT_TYPE - Possible values: OTHER_PAGE_VIEWED, HOMEPAGE_VIEWED, CART_VIEWED, PRODUCT_VIEWED, PRODUCT_LIST_VIEWED. The correct value to send depends on the page type. More information about which value to choose is described in the section: Trigger event API in the last table.
eventData - an object containing information about the page, which is important for the AI to deliver the correct behavior. The fields which have to be sent per each event type can be found in the section: Mapping from Shopify frontend fields to Rep AI events.
-
Setup cart events - Send an event when there are interactions with the cart.
window.rep.triggerEvent({{EVENT_TYPE}}, eventData);
EVENT_TYPE - Possible values here:CART_VIEWED,PRODUCT_ADDED,CART_UPDATED,PRODUCT_REMOVED. Trigger an event based on the specific action performed by the user. More information about these types of events under the section Trigger Event API in the last table.eventData - An object containing information about the cart, which is important for the AI to deliver correct behavior. The correct fields which have to be sent per each event can be found in the section: Mapping from Shopify frontend fields to Rep AI events.
-
Add listeners to the chat events— Rep AI provides listeners to subscribe to in order to get notified about actions the user chooses to perform using the AI’s assistance.
-
Here is a list of listeners the Rep AI chat provides:
Product added to the cart by the AI
Redirect by the AI to a different URL
User-approving cookie collection using the consent message in the Rep AI web client
-
Listener example:
window['rep'].on({{EVENT_TYPE}}, callBackFn);
EVENT_TYPE - Possible values: Any one of these events:updateCartByProducts,redirect,acceptCookie
More information about listeners can be found in the section: Web-Client event listeners
-
Important note:
We are compliant with the EU GDPR laws. For this purpose, we are listening to the Cookie Consent banner and blocking the chat for messaging and data analytics collection until the user approves the cookie collection. No proper chat APIs will be triggered until Cookie collection is approved.
Users can also approve cookie collection from within the web client. In this case, we provide an event you can subscribe to and be notified about. Once the cookie collection is approved, you should hide your own cookie consent banner so the user can communicate with the chat.
-
Trigger
IDENTIFYevent on customer login - only relevant to shops that support customer login functionality.
window.rep.triggerEvent( 'IDENTIFY', { customerId: {{customerId}} } );customerId - is a user ID from customer details
-
Cart details - Add a listener for
getCartDetailsevent. This listener will be fired if we need cart details like “attributes“ or “products” from the cart.
window['rep'].on("getCartDetails", {{handleGetCartdetails()}});
handleGetCartdetails - This function accepts a callback function (callBackFn) that will be triggered with the cart details. The callback function (callBackFn)accepts three params:
cartItems- list of products in the cartattributes- cart attributescartToken- in hydrogen id of a cart
Example of usage:
const callBackFn = (cartDetails: { cartItems: Record<string, any>[];
attributes: Record<string, any>;
cartToken: string }) => { // cartDetails } const handleGetCartdetails = (callBackFn) => { const cartDetails = //some logic here callBackFn({ cartItems: [...cartDetails.cartItems], attributes: {...cartDetails.attributes} cartToken: cartDetails.id }); } window['rep'].on("getCartDetails", handleGetCartdetails);
-
Update cart details (attributes, notes): This function listens for changes to cart details such as attributes and/or notes. Those parameters should update the cart's respected details.
const onRepUpdateCartAtributes = (detailsToCArtUpdate: { attributes: { rep_session_id: string, rep_assisted: boolean, }, note: string }, callBackFn ) => { const cartDetails = //some logic here callBackFn(cartDetails.id); }; window['rep'].on('updateCartAttributes', onRepUpdateCartAtributes);
callBackFn - a function that has to be fired with the cart ID as a parameter after the cart is updated.
-
Apply discount—A user can ask the AI to apply a discount. Add a listener to be notified of this scenario and apply a discount code to a cart.
window['rep'].on('applyDiscount', (discountCode) => { // your code here }) -
Once the order is completed and the “Thank you” page is shown, trigger the event “ORDER_COMPLETED” -
window['rep'].triggerEvent("ORDER_COMPLETED", { totalPrice: number | string; orderId: string | null; discountCode: string | null; currency: string; discountsAmount: number | null; taxPrice: number | null; shippingPrice: number | null; })Trigger event API
This API was developed for merchants that want to invoke or trigger events on demand. It is also useful for websites that are using SPA or SSR applications.
You can now invoke this functionality from your SPA, SSR application, or console developer tools in the browser. Code examples are attached below.
How to trigger an event from an application:
window.rep.triggerEvent(eventType: TriggerEventType, eventData: Record<string, any>) => void
How to trigger an event from the browser:window.rep.triggerEvent('PAGE_VIEWED', { pageTitle: 'Home page', cartRevenue: 0 });Parameters:
eventType: TriggerEventTypeeventData: Record<string, any>
The first parameter is
eventType, which can receive one of these events (a more detailed list with description is at the bottom of this document):'PAGE_VIEWED','OTHER_PAGE_VIEWED','HOMEPAGE_VIEWED','CART_VIEWED','PRODUCT_VIEWED', 'PRODUCT_LIST_VIEWED','CART_UPDATED','PRODUCT_REMOVED','PRODUCT_ADDED'.
The second parameter iseventData, which can receive data using an object with different possible structures, depending on the eventType parameter. Below is a table with all the possibleeventDataobject structures byeventType.Event type
Event data
CART_VIEWEDObject structure definition:
{ pageTitle: string, cartRevenue: number, cartItems: { productId: number | string, productTitle: string, productVariantId: number | string, productVariantTitle: string, productPrice: number, productQuantity: number, }[], }Object structure example:
{ pageTitle: 'Home page', cartRevenue: 0, cartItems: [{ productId: 1, productTitle: 'Product name', productVariantId: 1, productVariantTitle: 'Product variant name', productPrice: 9.99, productQuantity: 1 , }], }PAGE_VIEWED,OTHER_PAGE_VIEWED,HOMEPAGE_VIEWEDObject structure definition:
{ pageTitle: string, cartRevenue: number }Object structure example:
{ pageTitle: 'Home page', cartRevenue: 0 }PRODUCT_VIEWEDObject structure definition:
{ productId: number | string, productSku: string, productTitle: string, productVariantTitle: string, productPrice: number, productImage: string, productVendor: string, productType: string, }Object structure example:
{ productId: 1, productSku: '1', productTitle: 'Product name', productVariantTitle: 'Product variant name', productPrice: 9.99, productImage: 'https://...', productVendor: 'Vendor', productType: 'Type', }PRODUCT_LIST_VIEWEDObject structure definition:
{ collectionId: number | string, collectionType: string, }Object structure example:
{ collectionId: 1, collectionType: 'Some type', }
CART_UPDATEDObject structure definition:
{ cartRevenue: number, cartItems: { productId: number | string, productTitle: string, productVariantId: number | string, productVariantTitle: string, productPrice: number, productQuantity: number, }[], }Object structure example:
{ cartRevenue: 1, cartItems: [{ productId: 1, productTitle: 'Product name', productVariantId: 1, productVariantTitle: 'Product variant name', productPrice: 9.99, productQuantity: 1 , }], }PRODUCT_REMOVED,PRODUCT_ADDEDObject structure definition:
{ productId: number | string, productTitle: string, productVariantTitle: string, productPrice: number, productImage: string, productQuantity: number, cartRevenue: number, }Object structure example:
{ productId: 1, productTitle: 'Product name', productVariantTitle: 'Product variant name', productPrice: 9.99, productImage: 'https://...', productQuantity: 1, cartRevenue: 0, }ORDER_COMPLETED{ totalPrice: number | string; orderId: string | null; discountCode: string | null; currency: string; discountsAmount: number | null; taxPrice: number | null; shippingPrice: number | null; }How and where to get each field value is listed in the section:
Mapping from Shopify frontend fields to Rep AI events
If you pass unsupportedeventTypeor invalideventDataobject data, you will see a warning message in the browser console, and your event will not be sent.Event
When to trigger
PRODUCT_REMOVEDWhen a product is removed from the Cart
When the number of items in a product was decreased, For example: “Apples“ from 2 to 1
PRODUCT_ADDEDWhen a product is added to the Cart
When the number of items in a product was increased. For example: “Apple“ from 1 to 2
CART_UPDATEDEach time the Cart is updated - any changes to the cart
PRODUCT_LIST_VIEWEDIt should be sent once per page and only when the page loads.
It should fire only on a collection page.
Common pattern of a page URL:{{domain}}/collections/{{collection handle}}PRODUCT_VIEWEDIt should be sent once per page and only when the page loads.
It should fire only on a product page (product preview page).
Common pattern of a page URL:{{domain}}/products/{{product handle}}CART_VIEWEDThere might be two scenarios based on what website is used:
1. Cart modal—In this case, an event is sent each time the user opens the cart modal. If it is closed and then re-opened, another event should be sent.2. Cart page - Should be sent once, on page load.
Fires on the cart page.
Common pattern of a page URL:{{domain}}/cartPAGE_VIEWEDIt should be sent once per page and only when the page loads.
It fires on all pages with no dependency on other events.HOMEPAGE_VIEWEDIt should be sent once per page and only when the page loads.
It should fire only on the homepage
Common pattern of a page URL:
{{domain}}/OTHER_PAGE_VIEWEDIt should be sent once per page and only when the page loads.
Fires in all cases that were not covered by the events:
PRODUCT_LIST_VIEWED,PRODUCT_VIEWED, CART_VIEWED, HOMEPAGE_VIEWED-
No pattern of URLORDER_COMPLETEDWhen the order is completed.
Usually triggered on the page:{{domain}}/thank_youMapping from Shopify frontend fields to Rep AI events
This document outlines how to get the relevant event field values that are necessary for the functioning of the Rep AI platform.
Web-Client event listeners
This API provides the option to subscribe to events triggered by the Rep AI platform.
window['rep'].on({{eventType}}, callBackFunction)
Possible event types (eventType):
1.updateCartByProducts- Triggered as a directive to signal that products should be added to the cart. The cart should be updated with the products that are sent as a parameter of the callback functioncallBackFunction(payload),The given payload is an array of objects of product details.
Object structure:
{ productId: number, productQuantity: number; }-
redirect- Triggered as a directive to signal that a URL redirect should happen. The Rep AI web client will not redirect automatically but will use this function to alert of a redirect request.
Redirects should be handled based on the details in the callBackFunction
Object structure:
{ redirectUrl: string; redirectType?: string; redirectStoreId?: string; }
redirectType: Possible values: PRODUCT, COLLECTION, CHECKOUT, CART, OTHER
redirectStoreId (optional): Id of a product/collection, (only relevant for redirectType of the types: COLLECTION, PRODUCT)
redirectUrl (optional): Used in other cases and as a fallback if no redirectType == null or ifredirectType: OTHER
Note: When
redirectType: CARTA few scenarios are possible based on how Cart was implemented on a website:
1. If a Cart is a separate page - then navigation to this page should happen
2. If a Cart is inside the modal (e.g., cart drawer) - then the modal should openacceptCookie- Triggered as a directive to signal that the user approved the Cookie Consent displayed in the Rep AI chat window. If the user approves cookie consent handled by the website, the following API should be fired so the Rep AI platform will be aware of it, and the cookie consent banner within the Rep AI chat window will disappear.window['rep'].setUserPrivacyPolicyProved(true);
In any other case, the banner within the Rep AI Chat Window will not disappear, and the user will have to click on the “Accept cookie“ button for the AI functionality to continue.load- The REP AI chat has fully loadedopen- The chat window was opened by the userclose- The chat window was closed (minimized) by the user
Hydrogen implementation
This document helps you to implement trigger events in your Hydrogen project and send tracked events to the chat.
Ready-made examples of Hydrogen components can be found here.
Please pay attention that they are not production-ready versions of the Hydrogen component and should only serve as an example.-
Update root.tsx
To start sending events, you need to set up the RepAiIntegration or your custom Analytics component in your Hydrogen project's root route.// root.tsx import { RepAiIntegration } from '~/components/RepAiIntegration';
Then update the root component to wrap your Hydrogen app with the Analytics provider component.// root.tsx <Analytics.Provider cart={data.cart} shop={data.shop} consent={data.consent} > <PageLayout {...data}>{children}</PageLayout> <RepAiIntegration /> </Analytics.Provider> -
Update routes with analytics sub-components
To track page views, you need to add pageview components to each route you want to track.
Add theAnalytics.ProductViewcomponent to your nested route. This component sends a pageview event to chat when the route is loaded. TheProductViewsubcomponent takes adataprop with the product data to send to chat.// products.handle.tsx <Analytics.ProductView data={{ products: [ { id: product.id, title: product.title, price: selectedVariant?.price.amount || '0', vendor: product.vendor, variantId: selectedVariant?.id || '', variantTitle: selectedVariant?.title || '', quantity: 1, image: selectedVariant?.image?.url || '', }, ], }} />
Repeat this pattern for each route you want to track. Different routes have different preset analytics sub-components and require different data payloads. Follow the same pattern for other routes...// collections.handle.tsx <Analytics.CollectionView customData={{ title: collection.title, }} data={{ collection: { id: collection.id, handle: collection.handle, }, }} />// {{some}}.handle.tsx <Analytics.CustomView type="custom_other_page_viewed" />