Conversion Tracking
Conversion tracking allows you to attribute orders and conversions to specific AI agent interactions. When a user engages with one of your agents and later completes a purchase, you can record that conversion to measure the direct impact of your AI agents on revenue.
How It Works
BadgerFy.ai automatically tracks user engagements with your AI agents in the browser's local storage. Each engagement is stored with a 30-day expiration window. When a conversion occurs (typically on an order confirmation page), you call the recordConversionfunction to send the engagement data along with order details to your analytics.
- User Engages: A user interacts with one of your AI agents (assistant, quiz, nudge, exit-offer, or recommendation strip).
- Engagement Stored: The engagement is automatically recorded in local storage with a 30-day expiration.
- Conversion Occurs: The user completes a purchase on your site.
- Record Conversion: On your order confirmation page, call
recordConversionwith the order details. - Analytics Updated: The conversion is attributed to all agents the user engaged with, and the engagement data is cleared.
Engagement Actions by Agent Type
Each agent type has specific actions that qualify as an engagement. These engagements are automatically tracked when the user performs the corresponding action:
AI Assistant
Action: chat-engagement
An engagement is recorded when a user sends their first message and receives a response from the AI Assistant. Simply opening the chat widget does not count as an engagement—there must be an actual conversation.
Quiz
Action: quiz-completed
An engagement is recorded when a user completes the quiz and views their personalized results. Starting or partially completing a quiz does not count as an engagement.
Nudge
Action: nudge-cta-click
An engagement is recorded when a user clicks the call-to-action (CTA) button on a nudge. Simply viewing the nudge does not count as an engagement.
Recommendation Strip
Action: product-clicked
An engagement is recorded when a user clicks on a product link within the recommendation strip. Viewing the strip without clicking a product does not count as an engagement.
Survey
Action: survey-result
An engagement is recorded when a user completes a survey by submitting a rating (star rating) or selecting a sentiment (emoji reaction). Simply viewing or dismissing a survey does not count as an engagement.
Engagement Storage
Engagements are stored in the browser's local storage under the key badgerfyai_engagements. Each engagement record includes:
agentId- The unique identifier of the agentagentType- The type of agent (assistant, quiz, nudge, exit-offer, recommendation-strip, survey)engagementAction- The specific action that triggered the engagementengagedAt- Timestamp of when the engagement occurredexpiresAt- Timestamp when the engagement expires (30 days)pagePath- The page path where the engagement occurred
Recording Conversions
To record a conversion, call the recordConversion function from your order confirmation page. This function sends analytics events for each stored engagement and then clears the engagement data.
Basic Conversion Recording
// On your order confirmation pageconst result = await window.badgerfyai.recordConversion({orderId: 'ORD-12345',orderValue: '299.99'});console.log(result);// { success: true, message: 'Recorded 2 of 2 conversion(s)', recorded: 2, errors: [] }
Conversion with Product Details
For more detailed analytics, you can include product information with your conversion:
// Record conversion with full product detailsconst result = await window.badgerfyai.recordConversion({orderId: 'ORD-12345',orderValue: '549.98',products: [{productName: 'Wireless Gaming Mouse',sku: 'WGM-001',price: '79.99',quantity: 1,category: 'Peripherals'},{productName: 'Mechanical Keyboard',sku: 'MK-PRO-002',price: '149.99',quantity: 1,category: 'Peripherals'},{productName: 'USB-C Hub',sku: 'HUB-7P',price: '39.99',quantity: 2,category: 'Accessories'}]});
Function Parameters
The recordConversion function accepts an object with the following properties:
| Property | Type | Required | Description |
|---|---|---|---|
orderId | string | Yes | Unique identifier for the order |
orderValue | string | Yes | Total order value as a decimal string (e.g., "1299.99") |
products | array | No | Array of product objects (see below) |
Product Object Structure
Each product in the products array should have the following properties:
| Property | Type | Required | Description |
|---|---|---|---|
productName | string | Yes | Name of the product |
sku | string | Yes | Product SKU or identifier |
price | string | Yes | Unit price as a decimal string (e.g., "29.99") |
quantity | number | Yes | Quantity purchased |
category | string | Yes | Product category |
Static Website Implementation
For static HTML websites, add the conversion tracking code to your order confirmation page:
<!-- Order Confirmation Page --><script>// Wait for BadgerFy.ai to loadfunction recordOrderConversion() {if (typeof window.badgerfyai === 'undefined') {// Script not loaded yet, retry after a short delaysetTimeout(recordOrderConversion, 500);return;}// Get order data from your page (example using data attributes)const orderData = {orderId: document.getElementById('order-id').textContent,orderValue: document.getElementById('order-total').dataset.value,products: JSON.parse(document.getElementById('order-products').dataset.products)};window.badgerfyai.recordConversion(orderData).then(result => {console.log('Conversion recorded:', result);}).catch(error => {console.error('Failed to record conversion:', error);});}// Start the conversion recording process when the page loadsif (document.readyState === 'loading') {document.addEventListener('DOMContentLoaded', recordOrderConversion);} else {recordOrderConversion();}</script>
Next.js / React Implementation
For React-based applications, record the conversion in a useEffect hook on your order confirmation page:
// pages/order-confirmation.jsimport { useEffect, useState } from 'react';import { useRouter } from 'next/router';export default function OrderConfirmation() {const router = useRouter();const { orderId } = router.query;const [order, setOrder] = useState(null);const [conversionRecorded, setConversionRecorded] = useState(false);// Fetch order detailsuseEffect(() => {if (orderId) {fetchOrderDetails(orderId).then(setOrder);}}, [orderId]);// Record conversion when order is loadeduseEffect(() => {if (!order || conversionRecorded) return;const recordConversion = async () => {// Wait for BadgerFy.ai to be availableif (typeof window.badgerfyai === 'undefined') {setTimeout(recordConversion, 500);return;}try {const result = await window.badgerfyai.recordConversion({orderId: order.id,orderValue: order.total.toFixed(2),products: order.items.map(item => ({productName: item.name,sku: item.sku,price: item.price.toFixed(2),quantity: item.quantity,category: item.category}))});console.log('Conversion recorded:', result);setConversionRecorded(true);} catch (error) {console.error('Failed to record conversion:', error);}};recordConversion();}, [order, conversionRecorded]);if (!order) {return <div>Loading order details...</div>;}return (<div><h1>Thank you for your order!</h1><p>Order ID: {order.id}</p>{/* Rest of your confirmation page */}</div>);}async function fetchOrderDetails(orderId) {// Your order fetching logicconst response = await fetch(`/api/orders/${orderId}`);return response.json();}
Shopify Implementation
For Shopify stores, add conversion tracking to your order confirmation (thank you) page using the Checkout Settings:
Setup Steps
- Go to Settings → Checkout in your Shopify admin
- Scroll to Order status page section
- In the Additional scripts field, add the following code:
{% if first_time_accessed %}<script>// Wait for BadgerFy.ai to loadfunction recordShopifyConversion() {if (typeof window.badgerfyai === 'undefined') {setTimeout(recordShopifyConversion, 500);return;}window.badgerfyai.recordConversion({orderId: '{{ order.order_number }}',orderValue: '{{ checkout.total_price | money_without_currency | remove: "," }}',products: [{% for line_item in checkout.line_items %}{productName: {{ line_item.product.title | json }},sku: {{ line_item.sku | json }},price: '{{ line_item.final_price | money_without_currency | remove: "," }}',quantity: {{ line_item.quantity }},category: {{ line_item.product.type | json }}}{% unless forloop.last %},{% endunless %}{% endfor %}]}).then(result => {console.log('BadgerFy conversion recorded:', result);}).catch(err => {console.error('BadgerFy conversion error:', err);});}if (document.readyState === 'loading') {document.addEventListener('DOMContentLoaded', recordShopifyConversion);} else {recordShopifyConversion();}</script>{% endif %}
first_time_accessed condition ensures the conversion is only recorded once, even if the customer refreshes the order confirmation page.BigCommerce Implementation
For BigCommerce stores, add conversion tracking to your order confirmation page using the Script Manager or by editing your theme files.
Method 1: Script Manager
- Go to Storefront → Script Manager in your BigCommerce admin
- Click Create a Script
- Configure the script:
- Name: BadgerFy Conversion Tracking
- Location: Footer
- Pages: Order Confirmation
- Script type: Script
- Paste the following code:
<script>(function() {function recordBigCommerceConversion() {if (typeof window.badgerfyai === 'undefined') {setTimeout(recordBigCommerceConversion, 500);return;}// BigCommerce provides order data in the page context// Access via Stencil's injected JSON or data attributesvar orderData = window.BCData && window.BCData.order;if (!orderData) {// Alternative: try to get from page elementsvar orderIdEl = document.querySelector('[data-order-id]');var orderTotalEl = document.querySelector('[data-order-total]');if (orderIdEl && orderTotalEl) {orderData = {id: orderIdEl.dataset.orderId,total: orderTotalEl.dataset.orderTotal};}}if (!orderData) {console.log('BadgerFy: No order data found');return;}var products = [];if (orderData.items && orderData.items.length) {orderData.items.forEach(function(item) {products.push({productName: item.name || item.product_name,sku: item.sku || item.product_id,price: (item.price || item.base_price || 0).toString(),quantity: item.quantity || 1,category: item.category || 'Product'});});}window.badgerfyai.recordConversion({orderId: orderData.id || orderData.order_id,orderValue: (orderData.total || orderData.grand_total || 0).toString(),products: products}).then(function(result) {console.log('BadgerFy conversion recorded:', result);}).catch(function(err) {console.error('BadgerFy conversion error:', err);});}if (document.readyState === 'loading') {document.addEventListener('DOMContentLoaded', recordBigCommerceConversion);} else {recordBigCommerceConversion();}})();</script>
Method 2: Stencil Theme
For more control, edit your Stencil theme's order confirmation template:
{{! templates/pages/order-confirmation.html }}{{#if order}}<script>(function() {function recordConversion() {if (typeof window.badgerfyai === 'undefined') {setTimeout(recordConversion, 500);return;}window.badgerfyai.recordConversion({orderId: '{{order.id}}',orderValue: '{{order.grand_total.value}}',products: [{{#each order.items}}{productName: {{{json name}}},sku: {{{json sku}}},price: '{{price.value}}',quantity: {{quantity}},category: {{{json category}}}}{{#unless @last}},{{/unless}}{{/each}}]}).then(function(result) {console.log('BadgerFy conversion recorded:', result);}).catch(function(err) {console.error('BadgerFy conversion error:', err);});}if (document.readyState === 'loading') {document.addEventListener('DOMContentLoaded', recordConversion);} else {recordConversion();}})();</script>{{/if}}
Adobe Commerce (Magento) Implementation
For Adobe Commerce (Magento 2) stores, add conversion tracking using a custom module or by editing the success page template.
Method 1: Template Override
Create a template override for the checkout success page. Add this file to your theme:
app/design/frontend/[Vendor]/[theme]/Magento_Checkout/templates/success.phtml
<?php/*** BadgerFy.ai Conversion Tracking for Magento 2* Add this to your success.phtml template*//** @var \Magento\Checkout\Block\Onepage\Success $block */$order = $block->getOrder();if ($order):$items = [];foreach ($order->getAllVisibleItems() as $item) {$items[] = ['productName' => $item->getName(),'sku' => $item->getSku(),'price' => number_format($item->getPrice(), 2, '.', ''),'quantity' => (int) $item->getQtyOrdered(),'category' => '' // Add category logic if needed];}?><script>(function() {function recordMagentoConversion() {if (typeof window.badgerfyai === 'undefined') {setTimeout(recordMagentoConversion, 500);return;}window.badgerfyai.recordConversion({orderId: '<?= $block->escapeJs($order->getIncrementId()) ?>',orderValue: '<?= $block->escapeJs(number_format($order->getGrandTotal(), 2, '.', '')) ?>',products: <?= json_encode($items) ?>}).then(function(result) {console.log('BadgerFy conversion recorded:', result);}).catch(function(err) {console.error('BadgerFy conversion error:', err);});}if (document.readyState === 'loading') {document.addEventListener('DOMContentLoaded', recordMagentoConversion);} else {recordMagentoConversion();}})();</script><?php endif; ?>
Method 2: Custom Module
For a cleaner implementation, create a custom module with an observer or use Layout XML to inject the tracking script:
<!-- app/code/Vendor/BadgerFy/view/frontend/layout/checkout_onepage_success.xml --><?xml version="1.0"?><page xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xsi:noNamespaceSchemaLocation="urn:magento:framework:View/Layout/etc/page_configuration.xsd"><body><referenceContainer name="content"><block class="Vendor\BadgerFy\Block\ConversionTracking"name="badgerfy.conversion.tracking"template="Vendor_BadgerFy::conversion-tracking.phtml"after="-"/></referenceContainer></body></page>
bin/magento cache:clean. You may also need to run bin/magento setup:upgrade for module changes.Method 3: Google Tag Manager
If you have GTM installed, you can use the dataLayer to trigger conversion tracking. Add a custom HTML tag that fires on the order success page:
<script>(function() {function recordConversion() {if (typeof window.badgerfyai === 'undefined') {setTimeout(recordConversion, 500);return;}// Get order data from dataLayer (requires Enhanced Ecommerce)var orderData = null;if (window.dataLayer) {for (var i = 0; i < window.dataLayer.length; i++) {var entry = window.dataLayer[i];if (entry.ecommerce && entry.ecommerce.purchase) {orderData = entry.ecommerce.purchase;break;}}}if (!orderData || !orderData.actionField) {console.log('BadgerFy: No purchase data in dataLayer');return;}var products = (orderData.products || []).map(function(p) {return {productName: p.name,sku: p.id || p.sku,price: (p.price || 0).toString(),quantity: p.quantity || 1,category: p.category || 'Product'};});window.badgerfyai.recordConversion({orderId: orderData.actionField.id,orderValue: (orderData.actionField.revenue || 0).toString(),products: products}).then(function(result) {console.log('BadgerFy conversion recorded:', result);}).catch(function(err) {console.error('BadgerFy conversion error:', err);});}if (document.readyState === 'loading') {document.addEventListener('DOMContentLoaded', recordConversion);} else {recordConversion();}})();</script>
WooCommerce Implementation
For WooCommerce stores, add conversion tracking to your thank you page using WordPress hooks or a custom plugin.
Method 1: Functions.php
Add the following code to your theme's functions.php file:
// Add BadgerFy.ai conversion tracking to WooCommerce thank you pageadd_action('woocommerce_thankyou', 'badgerfy_record_conversion', 10, 1);function badgerfy_record_conversion($order_id) {if (!$order_id) return;$order = wc_get_order($order_id);if (!$order) return;// Only run once per orderif ($order->get_meta('_badgerfy_conversion_tracked')) return;$items = array();foreach ($order->get_items() as $item) {$product = $item->get_product();$items[] = array('productName' => $item->get_name(),'sku' => $product ? $product->get_sku() : '','price' => number_format($item->get_total() / $item->get_quantity(), 2, '.', ''),'quantity' => $item->get_quantity(),'category' => $product ? implode(', ', wp_get_post_terms($product->get_id(), 'product_cat', array('fields' => 'names'))) : '');}?><script>(function() {function recordConversion() {if (typeof window.badgerfyai === 'undefined') {setTimeout(recordConversion, 500);return;}window.badgerfyai.recordConversion({orderId: '<?php echo esc_js($order->get_order_number()); ?>',orderValue: '<?php echo esc_js($order->get_total()); ?>',products: <?php echo json_encode($items); ?>}).then(function(result) {console.log('BadgerFy conversion recorded:', result);}).catch(function(err) {console.error('BadgerFy conversion error:', err);});}if (document.readyState === 'loading') {document.addEventListener('DOMContentLoaded', recordConversion);} else {recordConversion();}})();</script><?php// Mark as tracked to prevent duplicate conversions$order->update_meta_data('_badgerfy_conversion_tracked', true);$order->save();}
Method 2: Code Snippets Plugin
If you prefer not to edit theme files, install the Code Snippets plugin and add the same code as a new PHP snippet. This method survives theme updates.
functions.php directly, use a child theme to prevent losing your changes during theme updates.Wix Implementation
For Wix stores using Wix eCommerce, add conversion tracking using Velo by Wix (formerly Corvid).
Setup Steps
- Enable Dev Mode by clicking Dev Mode in your editor toolbar
- Go to your Thank You page (usually
Thank You Pagein the Pages panel under Store Pages) - Click + Add Code and add the following to the page:
// Thank You Page Code (Wix Velo)import wixWindow from 'wix-window';$w.onReady(function () {// Get order data from the page// Note: Adjust selectors based on your Thank You page elementsconst orderData = wixWindow.getRouterData();if (orderData && orderData.orderId) {recordBadgerFyConversion(orderData);}});async function recordBadgerFyConversion(orderData) {// Wait for BadgerFy.ai to loadconst checkBadgerFy = () => {return new Promise((resolve) => {const check = () => {if (typeof window.badgerfyai !== 'undefined') {resolve();} else {setTimeout(check, 500);}};check();});};await checkBadgerFy();try {const result = await window.badgerfyai.recordConversion({orderId: orderData.orderId,orderValue: orderData.totals.total.toString(),products: orderData.lineItems.map(item => ({productName: item.name,sku: item.sku || item.productId,price: item.price.toString(),quantity: item.quantity,category: item.productType || 'Product'}))});console.log('BadgerFy conversion recorded:', result);} catch (err) {console.error('BadgerFy conversion error:', err);}}
Squarespace Implementation
For Squarespace Commerce stores, add conversion tracking using the Order Confirmation page code injection.
Setup Steps
- Go to Settings → Advanced → Code Injection
- In the Order Confirmation Page section, paste the following code:
<script>(function() {function recordSquarespaceConversion() {if (typeof window.badgerfyai === 'undefined') {setTimeout(recordSquarespaceConversion, 500);return;}// Squarespace provides order data in Y.Squarespace.Commerce objectvar commerce = window.Y && window.Y.Squarespace && window.Y.Squarespace.Commerce;if (!commerce || !commerce.currentOrder) {console.log('BadgerFy: No order data found');return;}var order = commerce.currentOrder;var products = [];if (order.items && order.items.length) {order.items.forEach(function(item) {products.push({productName: item.productName || item.title,sku: item.sku || item.productId,price: (item.unitPrice / 100).toFixed(2),quantity: item.quantity,category: item.productType || 'Product'});});}window.badgerfyai.recordConversion({orderId: order.orderNumber || order.id,orderValue: (order.grandTotal / 100).toFixed(2),products: products}).then(function(result) {console.log('BadgerFy conversion recorded:', result);}).catch(function(err) {console.error('BadgerFy conversion error:', err);});}if (document.readyState === 'loading') {document.addEventListener('DOMContentLoaded', recordSquarespaceConversion);} else {recordSquarespaceConversion();}})();</script>
Alternative: Manual Data Attributes
If the automatic method doesn't work, you can add data attributes to your Order Confirmation page template and read from those:
<script>(function() {function recordConversion() {if (typeof window.badgerfyai === 'undefined') {setTimeout(recordConversion, 500);return;}// Read from URL parameters if Squarespace adds themvar urlParams = new URLSearchParams(window.location.search);var orderId = urlParams.get('orderNumber') ||document.querySelector('[data-order-id]')?.dataset.orderId;var orderValue = urlParams.get('orderTotal') ||document.querySelector('[data-order-total]')?.dataset.orderTotal;if (!orderId || !orderValue) {console.log('BadgerFy: Could not find order data');return;}window.badgerfyai.recordConversion({orderId: orderId,orderValue: orderValue}).then(function(result) {console.log('BadgerFy conversion recorded:', result);}).catch(function(err) {console.error('BadgerFy conversion error:', err);});}if (document.readyState === 'loading') {document.addEventListener('DOMContentLoaded', recordConversion);} else {recordConversion();}})();</script>
Response Format
The recordConversion function returns a promise that resolves to a result object:
// Success response{success: true,message: 'Recorded 2 of 2 conversion(s)',recorded: 2, // Number of conversions successfully recordederrors: [] // Array of any errors encountered}// Partial success (some engagements failed to record){success: true,message: 'Recorded 1 of 2 conversion(s)',recorded: 1,errors: ['Failed to record conversion for agent 456: Network error']}// No engagements to record{success: true,message: 'No agent engagements found to convert',recorded: 0,errors: []}// Validation error{success: false,message: 'orderId is required',recorded: 0,errors: ['orderId is required']}
Disabling Default Engagements
By default, BadgerFy.ai automatically tracks engagements for all agent types. If you want to manually control when engagements are recorded, you can disable the default tracking:
// Disable default engagement trackingwindow.badgerfyaiConfig = {engagementConfig: {disableDefaultEngagements: true}};// Then manually record engagements when neededwindow.badgerfyai.addAgentEngagement(agentId, 'custom-action');
Engagement Helper Functions
BadgerFy.ai exposes several helper functions for managing engagements:
Available Functions
// Check if a user has engaged with a specific agentconst hasEngaged = window.badgerfyai.hasAgentEngagement(agentId);// Returns: boolean// Get engagement details for a specific agentconst engagement = window.badgerfyai.getAgentEngagement(agentId);// Returns: engagement object or null// Get all current engagementsconst allEngagements = window.badgerfyai.getAllAgentEngagements();// Returns: array of engagement objects// Manually add an engagementwindow.badgerfyai.addAgentEngagement(agentId, 'custom-action');// Returns: boolean (true if added, false if already exists)// Clear engagement for a specific agentwindow.badgerfyai.clearAgentEngagement(agentId);// Returns: boolean// Clear all engagementswindow.badgerfyai.clearAllAgentEngagements();// Returns: boolean// Remove expired engagements (called automatically on page load)window.badgerfyai.cleanupExpiredEngagements();
Lifecycle Callbacks
BadgerFy.ai provides two lifecycle callbacks that you can use to integrate with your application's logic. Define these in your configuration before the script loads.
onLoad Callback
The onLoad callback fires when the BadgerFy.ai script has fully loaded and initialized. This is useful for triggering actions that depend on BadgerFy.ai being ready.
window.badgerfyaiConfig = {onLoad: () => {console.log('BadgerFy.ai is ready!');// Example: Track that BadgerFy is active in your analyticsanalytics.track('BadgerFy Loaded');// Example: Update UI statesetIsBadgerFyReady(true);// Example: Access BadgerFy.ai APIconst agents = window.badgerfyai.getAgents();console.log('Active agents:', agents);}};
onEngagement Callback
The onEngagement callback fires whenever a user engagement is recorded. This allows you to react to engagements in real-time, such as sending data to your own analytics platform or triggering custom logic.
window.badgerfyaiConfig = {onEngagement: ({ agentId, agentType, engagementAction, pagePath }) => {console.log('User engaged!', { agentId, agentType, engagementAction, pagePath });// Example: Send to your analytics platformanalytics.track('BadgerFy Engagement', {agentId,agentType,action: engagementAction,page: pagePath});// Example: Trigger a custom eventwindow.dispatchEvent(new CustomEvent('badgerfy:engagement', {detail: { agentId, agentType, engagementAction, pagePath }}));}};
Callback Parameters
The onEngagement callback receives an object with the following properties:
| Property | Type | Description |
|---|---|---|
agentId | string | The unique identifier of the agent that was engaged with |
agentType | string | The type of agent (assistant, quiz, nudge, exit-offer, recommendation-strip, survey) |
engagementAction | string | The action that triggered the engagement (e.g., chat-engagement, quiz-completed) |
pagePath | string | The page path where the engagement occurred |
Combined Configuration Example
Here's a complete example showing both callbacks along with other configuration options:
window.badgerfyaiConfig = {// Lifecycle callbacksonLoad: () => {console.log('BadgerFy.ai initialized');},onEngagement: ({ agentId, agentType, engagementAction, pagePath }) => {// Send to Google Analytics 4gtag('event', 'badgerfy_engagement', {agent_id: agentId,agent_type: agentType,engagement_action: engagementAction,page_path: pagePath});},// Optional: Disable default engagement tracking// disableDefaultEngagements: true,// Optional: Tool call handlersfunctions: [{pageAgentId: 'YOUR_AGENT_ID',functionName: 'addToCart',functionCall: async (params) => {// Your logic herereturn { success: true };}}]};
Best Practices
- Record Once: Only call
recordConversiononce per order. The function clears engagement data after recording, so subsequent calls will have no engagements to record. - Handle Errors: Always wrap the conversion call in a try/catch block to handle network errors or other issues gracefully.
- Valid Order Values: Ensure
orderValueis formatted as a decimal string (e.g., "99.99", "1250.00"). Invalid formats will be rejected. - Wait for Script: The BadgerFy.ai script loads asynchronously. Always check that
window.badgerfyaiis defined before calling functions. - Test Thoroughly: Use browser developer tools to inspect local storage (
badgerfyai_engagements) and verify engagements are being tracked correctly before deploying.