Setting Up the Ptengine Tracking Code for Shopify

Setting Up the Ptengine Tracking Code for Shopify #

Follow these steps to install the Ptengine tracking code on your Shopify store for accurate visitor tracking and insights.

Add the Tracking Code to Your Theme #

To install the Basic Code, you need to add it to your Shopify theme file.

Steps to Add the Code:

  1. In your Shopify Admin Panel, go to Online Store > Themes.
  2. Click Actions > Edit Code for your active theme.
  3. Find and open the theme.liquid file.
  4. Paste the Ptengine Basic Code inside the <head> section.

Tip: Make sure to place XXXXX (specific code placement instruction goes here) in the correct spot to ensure accurate tracking.

<!-- Ptengine Tag -->
<script src="https://js.ptengine.com/xxxxx.js"></script>
<!-- End Ptengine Tag -->

Setting Up Event Tracking in Shopify #

To track key events on your Shopify store, follow these steps to add custom tracking pixels using your Ptengine SID.

Steps to Set Up Event Tracking:

  1. Go to Shopify Admin Panel and open Settings > Customer Events.
  2. Replace the SID in the code below with your SID from Step 1.
  3. Copy & paste the updated code into the Custom Pixels section.
  4. Click Save & Connect to activate tracking.

Tip: Make sure you replace the ID in the code with your correct Ptengine SID to ensure accurate tracking.


Updated code↓

function trackEvent(eventType, eventProperties, cb) {
//Please replace the id with your project id
const sid = "Please enter the project id";
const area = "com";
const options = eventProperties || {};

loadPtengineScript(sid, area)
.then(() => {
console.log("ptengine script loading complete");
window.ptengine && window.ptengine.track(eventType, options);
cb && typeof cb === "function" && cb();
})
.catch((error) => {
console.error("ptengine script loading failed:", error);
});
}

function loadPtengineScript(sid, area) {
return new Promise((resolve, reject) => {
if (window.ptengine) {
// If ptengine already exists, resolve it immediately
resolve();
} else {
// Keep the original url
const url = window.location.href.replace(
/\/wpm@[a-zA-Z0-9]+\/web-pixel-[a-zA-Z0-9]+@[a-zA-Z0-9]+\/sandbox\/modern/,
""
);
// Using the original url to send the event
window._pt_sp_2 = [];
_pt_sp_2.push(`setAccount, ${sid}`);
_pt_sp_2.push(`setPVTag,${url},replace`);

// Dynamically load the ptengine script
const script = document.createElement("script");
// Check if it is on the checkout page
const isCheckoutPage = window.location.href.includes("checkouts");
const sandboxQuery = isCheckoutPage ? "" : "?sandbox"; // None added on the checkout page '?sandbox'
script.src = https://js.ptengine.${area}/${sid}.js${sandboxQuery};
script.onload = () => resolve(); // Load successfully
script.onerror = () => reject(new Error("Script loading failed")); // Load failed
document.head.appendChild(script);
}


});
}

// 使用回调函数触发identify包例子
analytics.subscribe("checkout_completed", (event) => {
const checkout = event?.data?.checkout;
const checkoutTotalPrice = checkout?.totalPrice?.amount;
const checkoutItems = checkout?.lineItems;
const checkoutOrderId = checkout?.order?.id;
const uid = event?.data?.clientId;

const eventProperties = {
totalPrice: checkoutTotalPrice,
totalorderid: checkoutOrderId,
};

const identifyCallback = () => {
checkoutItems.forEach((checkoutItem) => {
ptengine &&
ptengine.identify(uid, {
totalPrice: checkoutTotalPrice,
totalorderid: checkoutOrderId,
totalquantity: checkoutItem?.quantity,
totaltitle: checkoutItem?.title,
totalid: checkoutItem?.id,
totalsku: checkoutItem?.variant?.sku,
totalProductType: checkoutItem?.variant?.product?.type,
});
});
};
trackEvent("checkout_completed", eventProperties, identifyCallback);
});

analytics.subscribe("search_submitted", (event) => {
trackEvent("search_submitted");
});

analytics.subscribe("collection_viewed", (event) => {
trackEvent("collection_viewed");
});

analytics.subscribe("product_viewed", (event) => {
trackEvent("product_viewed");
});

analytics.subscribe("product_added_to_cart", (event) => {
trackEvent("product_added_to_cart");
});

analytics.subscribe("product_removed_from_cart", (event) => {
trackEvent("product_removed_from_cart");
});

analytics.subscribe("cart_viewed", (event) => {
trackEvent("cart_viewed");
});

analytics.subscribe("checkout_started", (event) => {
trackEvent("checkout_started");
});

analytics.subscribe("checkout_contact_info_submitted", (event) => {
trackEvent("checkout_contact_info_submitted");
});

analytics.subscribe("checkout_address_info_submitted", (event) => {
trackEvent("checkout_address_info_submitted");
});

analytics.subscribe("checkout_shipping_info_submitted", (event) => {
trackEvent("checkout_shipping_info_submitted");
});

analytics.subscribe("payment_info_submitted", (event) => {
trackEvent("payment_info_submitted");
});

3. Events definition:

search_submitted: use searching

collection_viewed:collection page viewed

product_viewed:product detail page viewed

product_added_to_cart:add to cart

product_removed_from_cart:remove the cart

cart_viewed:cart viewed

checkout_started:enter the checkout page

checkout_contact_info_submitted:input contacting information: email

checkout_address_info_submitted:input the adress

checkout_shipping_info_submitted:select the shipping method

payment_info_submitted:select the payment method

checkout_completed:purchase

Tracking Events with Code #

For advanced tracking, you can use the ptengine.track method to monitor key user actions, such as:

  • Successful form submissions
  • Completed purchases
  • Clicks on important buttons

This method lets you track specific user interactions and even add extra details, like product information or customer behavior data.

How to Implement Event Tracking

1️⃣ Use the ptengine.track method to track events.

2️⃣ Embed this code inside any user action (e.g., checkout, form submission).

3️⃣ Customize event properties to collect more detailed insights.

📌 Example Code:

This example tracks a purchase event, including product details.

ptengine.track("check_out", {  //Event name,for example purchase、signup…
product_category: "Clothing",  //Event profile, for example sku, signup information…
product_pricing: "1293"
});

Learn More

Not familiar with Ptengine’s event definitions? [Check out this guide] to learn more about event tracking.

Example 1 : Collect users who register by clicking the Register button

document.getElementById('btnLogin').addEventListener('click', function (){
ptengine&&ptengine.track('signup');
});

Example 2: When there are two add-to cart buttons on the page, but we want to mark both two buttons as one event

try {
<script type="text/javascript">try {window.ptengine && window.ptengine.track("purchase");} catch (e) {console.error("Error tracking purchase:", e);}</script> opationRecord = [];
function ptEventSend(eventName) {
          if (eventName && !opationRecord.includes(eventName)) {
              opationRecord.push(eventName);
              window.ptengine && window.ptengine.track(eventName);
          }
      }

      function addEventListenersToElements() {
          var addCartBottom = document.getElementById(add_cart_bottom);
          var addCart = document.getElementById(add_cart);

          if (addCartBottom) {
              addCartBottom.addEventListener(click, function() {
                  ptEventSend(add the products to cart);
              }, false);
          }

          if (addCart) {
              addCart.addEventListener(click, function() {
                  ptEventSend(add to cart from the sticky bar);
              }, false);
          }
      }

      addEventListenersToElements();

      var ptTimer = setInterval(addEventListenersToElements, 500);

  } catch (e) {}

Setting Up Personalized User Tracking #

What Does the Identify Code Do? #

The Identify Code helps recognize and track users, turning anonymous visitors into identified users. This allows you to:

  1. Track individual users across sessions for better insights.
  2. Collect key user details, such as:
    • Last Active Date
    • Registration Date
    • Total Sessions
    • Referring Domain on First Visit
    • Source URL on First Visit
  3. Create detailed user profiles for personalized content and marketing.

Where to Place the Identify Code #

We recommend adding the Identify Code on pages where users log in, sign up, or enter personal details, such as:

  • Login Page
  • Registration Page
  • Membership Signup Page

When a user logs in or registers, Ptengine links their information to their device, making it possible to track individual behavior and optimize their experience.

How the Identify Code Works #

Example Code:

<script>
document.getElementById('btnSignup').addEventListener('click', function() {
ptengine.identify(document.getEleme
ntById('uid').value, {
//Get email Data
email : document.getElementById('email').value,
//Get Phone Data
phone : document.getElementById('phone').value,
//Get genger Data
gender: document.getElementById('sex').value,
//Get age Data
age: document.getElementById('age').value,
last_active_date: new Date()
})
});
</script>

This example assigns a unique ID (Uid) to a user and stores key details like name, email, and membership type.

Viewing and Exporting User Data #

Once users are identified, Ptengine binds user attributes to their unique ID (Uid). You can:

  • View user data inside the User Module.
  • Export user insights for analysis and marketing campaigns.

Was this article helpful?

  • Yes, great!
  • Not really

Thanks for your feedback.

  Sorry about that. Do you mind sharing how we can improve?

    Write your feedback here...