<html><head><meta name="color-scheme" content="light dark"></head><body><pre style="word-wrap: break-word; white-space: pre-wrap;">const AccountDetails = localStorage.hasOwnProperty('Tixpix_AccountDetails') ? JSON.parse(localStorage.getItem('Tixpix_AccountDetails') || {}) : {};

if (window.Shopify &amp;&amp; window.Shopify.customer) {
    console.log(window.Shopify.customer);
}

const eventsName = {
    facebook: {
        page_viewed: "PageView",
        product_added_to_cart: "AddToCart",
        product_removed_from_cart: "",
        collection_viewed: "ViewContent",
        product_viewed: "ViewContent",
        cart_viewed: "ViewContent",
        checkout_started: "InitiateCheckout",
        checkout_address_info_submitted: "AddPaymentInfo",
        payment_info_submitted: "AddPaymentInfo",
        checkout_completed: "Purchase",
    },
    google: {
        page_viewed: "page_view",
        product_added_to_cart: "add_to_cart",
        product_removed_from_cart: "remove_from_cart",
        collection_viewed: "collection_viewed",
        product_viewed: "view_item",
        cart_viewed: "cart_viewed",
        checkout_started: "begin_checkout",
        checkout_address_info_submitted: "add_shipping_info",
        payment_info_submitted: "add_payment_info",
        checkout_completed: "purchase",
    },
    tiktok: {
        page_viewed: "PageView",
        product_added_to_cart: "AddToCart",
        product_removed_from_cart: "",
        collection_viewed: "ViewContent",
        product_viewed: "ViewContent",
        cart_viewed: "ViewContent",
        checkout_started: "InitiateCheckout",
        checkout_address_info_submitted: "AddPaymentInfo",
        payment_info_submitted: "AddPaymentInfo",
        checkout_completed: "Purchase",
    },
}

const customEventName = {
    track_Product_details_page_view: ["product_viewed"],
    track_Product_details_page_view_homepage: ["page_viewed", "collection_viewed"],
    track_add_to_cart: ["product_added_to_cart"],
    track_initiate_checkout: ["checkout_started"],
    payment_info_submitted: ["track_order_value_currency"],
    track_complate_payment: ["checkout_completed"],
    tracking_status: [],
};





function getCookie(name) {
    const cookies = document.cookie.split(';');
    for (let i = 0; i &lt; cookies.length; i++) {
        const cookie = cookies[i].trim();
        if (cookie.startsWith(name + '=')) {
            return cookie.substring(name.length + 1);
        }
    }
    return null;
}

function setCookie(name, value, days) {
    let expires = "";
    if (days) {
        const date = new Date();
        date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
        expires = "; expires=" + date.toUTCString();
    }
    document.cookie = name + "=" + value + expires + "; path=/";
}

async function sha256(text) {
    text = text?.toLowerCase();
    const encoder = new TextEncoder();
    const data = encoder.encode(text);
    const hashBuffer = await crypto.subtle.digest("SHA-256", data);
    const hashArray = Array.from(new Uint8Array(hashBuffer));
    return hashArray.map(byte =&gt; byte.toString(16).padStart(2, "0")).join("");
}

function generateEventId() {
    return `event-${crypto.randomUUID()}`;
}

async function ipinfo() {
    try {
        let ipinfo = getCookie('ipinfo');
        if (ipinfo) {
            return JSON.parse(ipinfo);
        }
        const response = await fetch('https://ipinfo.io/json');
        if (!response.ok) {
            throw new Error(`HTTP error! Status: ${response.status}`);
        }
        const ipInfo = await response.json();
        setCookie("ipinfo", JSON.stringify(ipInfo), 1);
        return ipInfo;
    } catch (error) {
        console.error("Error fetching IP info:", error);
        return null;
    }
}

class TixpixTracker {
  constructor(pixels) {
    this.pixels = pixels;
        this.init(this);
  }

  async init(self) {
    let queue = [];
    let queueLock = false;

    setInterval(async function () {
        let i;
        for (i in localStorage) {
            if (localStorage.hasOwnProperty(i)) {
                if (i.match(/Tixpix_.{0,}/s) &amp;&amp; i!="Tixpix_AccountDetails") {
                    let value = localStorage.getItem(i);
                    queue.push({
                        'i': i,
                        'v': value
                    });
                }
            }
        }

        if (queue &amp;&amp; queue.length &gt; 0 &amp;&amp; !queueLock) {
            queueLock = true;

            let _queue = JSON.parse(JSON.stringify(queue))

            for (const pixelEvent of _queue) {
                try {
                    let event = JSON.parse(pixelEvent.v);
                    self.pixels.forEach(async (pixel) =&gt; {

                        let eventData = await self.eventDataFunc(event, pixel);
                        eventData.user_data = {
                            'fn': [await sha256(AccountDetails?.firstName || "")],
                            'ln': [await sha256(AccountDetails?.lastName || "")],
                            'em': [await sha256(AccountDetails?.email || "")],
                            'ph': [await sha256(AccountDetails?.phone || "")],
                        };
                        let eventParams = {
                            eventID: event.id
                        };

                        let eventChecker = Array.from(new Set(Object.keys(customEventName).map((k) =&gt; {
                            let eventFilter = pixel[k] ? customEventName[k] : [];
                            return eventFilter;
                        }).flat()));

                        if(eventChecker &amp;&amp; eventChecker.includes(event.name)){
                            if(pixel.platform=="facebook"){
                                if (pixel.access_token &amp;&amp; pixel.access_token.length &gt; 0) {
                                    console.log(pixel)
                                    self.sendConversionApi(pixel, event.name, eventData, event);
                                }else{
                                    fbq('trackSingle', pixel.pixel_id, eventsName.facebook[event.name], eventData, eventParams);
                                }
                            }else if(pixel.platform=="google-analytics"){
                                gtag('event', eventsName.google[event.name], {
                                    'send_to': pixel.pixel_id,
                                    ...eventData
                                });
                            }else if(pixel.platform=="tiktok"){
                                trackTikTokEvent(pixel.pixel_id, eventsName.tiktok[event.name], eventData);
                            }

                        }
                    });
                } catch (error) {
                    console.log(error);
                }

                window.localStorage.removeItem(pixelEvent.i);
            }
            queue = [];
            queueLock = false;
        }
    }, 100);
  }

  async eventDataFunc(data, pixel){
    let arr = {};
    if(data.name=="page_viewed"){
        arr = {
            page_title: data.data?.title,
            page_path: window.location.pathname,
            page_location: window.location.href,
        }
    }else if(data.name=="collection_viewed"){
        if(pixel.platform=="facebook"){
            arr = {
                content_name: data.event.data?.collection?.title ||"",
                contents: data.event.data?.collection?.productVariants?.map((v) =&gt; {
                    return { item_id: v?.id, item_name: v?.title, price: v?.price?.amount, currency: v?.price?.currencyCode }
                })
            };
        }else if(pixel.platform=="google-analytics"){
            arr = {
                item_list_name: data.event?.data?.title,
                items: data.event.data?.collection?.productVariants?.map((v) =&gt; {
                    return { item_id: v?.id, item_name: v?.title, price: v?.price?.amount, currency: v?.price?.currencyCode }
                })
            };
        }else if(pixel.platform=="tiktok"){
            arr = {
                content_id: data.event.data?.collection?.id,
                content_name: data.event.data?.collection?.title,
                content_type: 'collection'
            };
        }
    }else if(data.name=="product_viewed"){
        if(pixel.platform=="facebook"){
            arr = {
                page_title: data.data?.title,
                page_path: window.location.pathname,
                page_location: window.location.href,
            }
        }else if(pixel.platform=="google-analytics"){
            arr = {
                page_title: data.data?.title,
                page_path: window.location.pathname,
                page_location: window.location.href,
            }
        }else if(pixel.platform=="tiktok"){
            arr = {
                content_id: data.data?.product?.id,
                content_name: data.data?.product?.title,
                content_type: 'product',
                value: data.data?.price?.amount,
                currency: data.data?.price?.currencyCode
            };
        }
    }else if(data.name=="product_added_to_cart"){
        if(pixel.platform=="facebook"){
            arr = {
                content_ids: [data.data?.merchandise?.sku || data.data?.merchandise?.id],
                content_name: data.data?.merchandise?.title || data.data?.merchandise?.product?.title,
                content_category: 'Cart Items',
                content_type: 'product',
                value: data.data?.cost?.totalAmount?.amount,
                currency: data.data?.cost?.totalAmount?.currencyCode,
                contents: [{
                    id: data.data?.merchandise?.sku || data.data?.merchandise?.id,
                    quantity: data.data.quantity
                }],
            };
        }else if(pixel.platform=="google-analytics"){
            arr = {
                currency: data.data?.cost?.totalAmount?.currencyCode,
                value: data.data?.cost?.totalAmount?.amount,
                items: [
                    {
                        item_name: data.data?.merchandise?.title || data.data?.merchandise?.product?.title,
                        item_id: data.data?.merchandise?.sku || data.data?.merchandise?.id,
                        price: data.data?.merchandise?.price?.amount || 0,
                        quantity: data.data?.quantity || 0,
                        currency: data.data?.merchandise?.price?.currencyCode || 'USD'
                    }
                ]
            };
        }else if(pixel.platform=="tiktok"){
            arr = {
                content_id: data.data?.merchandise?.sku || data.data?.merchandise?.id,
                content_name: data.data?.merchandise?.title || data.data?.merchandise?.product?.title,
                content_type: 'product',
                value: data.data?.merchandise?.price?.amount || 0,
                quantity: data.data?.quantity || 0,
                currency: data.data?.merchandise?.price?.currencyCode || 'USD'
            };
        }
    }else if(data.name=="cart_viewed"){
        if(pixel.platform=="facebook"){
            arr = {
                contents: data.data?.lines?.map((v) =&gt; {
                    return { id: v?.merchandise?.id, quantity: v?.quantity, quantity: v?.quantity, price: v?.price?.amount, currency: v?.price?.currencyCode }
                }),
                value: data.data?.cost?.totalAmount?.amount,
                currency: data.data?.cost?.totalAmount?.currencyCode,
            };
        }else if(pixel.platform=="google-analytics"){
            arr = {
                currency: data.data?.cost?.totalAmount?.currencyCode,
                value: data.data?.cost?.totalAmount?.amount,
                items: data.data?.lines?.map((v) =&gt; {
                    return { item_id: v?.merchandise?.id, item_name: v?.merchandise?.title, quantity: v?.quantity, quantity: v?.quantity, price: v?.price?.amount, currency: v?.price?.currencyCode }
                })
            };
        }else if(pixel.platform=="tiktok"){
            arr = {
                currency: data.data?.cost?.totalAmount?.currencyCode,
                value: data.data?.cost?.totalAmount?.amount,
                items: data.data?.lines?.map((v) =&gt; {
                    return { item_id: v?.merchandise?.id, item_name: v?.merchandise?.title, quantity: v?.quantity, quantity: v?.quantity, price: v?.price?.amount, currency: v?.price?.currencyCode }
                })
            };
        }
    }else if(data.name=="checkout_address_info_submitted"){
        if(pixel.platform=="facebook"){
            arr = {
                contents: data.data?.lineItems?.map((v) =&gt; {
                    return { id: v?.id, quantity: v?.quantity, quantity: v?.quantity, price: v?.finalLinePrice?.amount, currency: v?.finalLinePrice?.currencyCode }
                }),
                value: data.data?.totalPrice.amount, // Total cart value
                currency: data.data?.totalPrice.currencyCode,
                email: await sha256(data.data?.email), // Hashed email (SHA256 recommended)
                first_name: data.data?.shippingAddress?.firstName,
                last_name: data.data?.shippingAddress?.lastName,
                city: data.data?.shippingAddress?.city,
                postal_code: data.data?.shippingAddress?.provinceCode,
                country: data.data?.shippingAddress?.countryCode
            };
        }else if(pixel.platform=="google-analytics"){
            arr = {
                currency: data.data?.totalPrice.currencyCode,
                value: data.data?.totalPrice.amount,
                items: data.data?.lineItems?.map((v) =&gt; {
                    return { item_id: v?.id, item_name: v?.title, quantity: v?.quantity, quantity: v?.quantity, price: v?.finalLinePrice?.amount, currency: v?.finalLinePrice?.currencyCode }
                }),
                shipping_info: {
                  city: data.data?.shippingAddress?.city,
                  region: data.data?.shippingAddress?.countryCode,
                  country: data.data?.shippingAddress?.countryCode
                }
            };
        }else if(pixel.platform=="tiktok"){
            arr = {
                event_name: 'CheckoutAddressInfoSubmitted',
                customer_email: await sha256(data.data?.email),
                customer_name: data.data?.shippingAddress?.firstName,
                address: '',
                city: data.data?.shippingAddress?.city,
                state: data.data?.shippingAddress?.countryCode,
                country: data.data?.shippingAddress?.countryCode,
                postal_code: data.data?.shippingAddress?.provinceCode
            };
        }
    }else if(data.name=="checkout_completed"){
        if(pixel.platform=="facebook"){
            arr = {
                contents: data.data?.lineItems?.map((v) =&gt; {
                    return { id: v?.id, quantity: v?.quantity, quantity: v?.quantity, price: v?.finalLinePrice?.amount, currency: v?.finalLinePrice?.currencyCode }
                }),
                value: data.data?.totalPrice.amount,
                currency: data.data?.totalPrice.currencyCode,
                transaction_id: data.data?.order?.id,
                email: await sha256(data.data?.email),
                first_name: data.data?.shippingAddress?.firstName,
                last_name: data.data?.shippingAddress?.lastName,
                city: data.data?.shippingAddress?.city,
                postal_code: data.data?.shippingAddress?.provinceCode,
                country: data.data?.shippingAddress?.countryCode
            };
        }else if(pixel.platform=="google-analytics"){
            arr = {
                transaction_id: data.data?.order?.id,
                value: data.data?.totalPrice.amount,
                currency: data.data?.totalPrice.currencyCode,
                tax: data.data?.totalTax.amount,
                items: data.data?.lineItems?.map((v) =&gt; {
                    return { item_id: v?.id, item_name: v?.title, quantity: v?.quantity, quantity: v?.quantity, price: v?.finalLinePrice?.amount, currency: v?.finalLinePrice?.currencyCode }
                })
            };
        }else if(pixel.platform=="tiktok"){
            arr = {
                contents: data.data?.lineItems?.map((v) =&gt; {
                    return { id: v?.id, name: v?.title, quantity: v?.quantity, quantity: v?.quantity, price: v?.finalLinePrice?.amount, currency: v?.finalLinePrice?.currencyCode }
                }),
                value: data.data?.totalPrice.amount,
                currency: data.data?.totalPrice.currencyCode,
                order_id: data.data?.order?.id
            };
        }
    }else if(data.name=="checkout_started"){
        arr = {};
    }
    return arr;
  }


  async sendConversionApi(pixel, type, event, data) {
    if (!pixel.pixel_id || !pixel.access_token) {
        return;
    }
    let ipinfoData = await ipinfo();

    const eventData = {
        data: [
            {
                event_id: data?.id,
                event_name: type,
                event_time: Math.floor(Date.now() / 1000),
                user_data: {
                    em: [await sha256(AccountDetails?.email || "")],
                    ph: [await sha256(AccountDetails?.phone || "")],
                    client_ip_address: ipinfoData.ip,
                    client_user_agent: data.context?.navigator?.userAgent
                },
                custom_data: { ...event },
                event_source_url: window.location.href,
                action_source: "website"
            }
        ]
    };
    if(pixel?.test_code){
        eventData['test_code'] = pixel?.test_code;
    }
    fetch(`https://graph.facebook.com/v19.0/${pixel.pixel_id}/events?access_token=${pixel.access_token}`, {
        method: "POST",
        headers: {
            "Content-Type": "application/json"
        },
        body: JSON.stringify(eventData)
    })
    .then(response =&gt; response.json())
    .then(data =&gt; {
            })
    .catch(error =&gt; console.error("Error:", error));
  }
}


document.addEventListener("readystatechange", function (event) {
    });
</pre></body></html>