How to Connect TikTok Pixel on Shopify [Manually]

How to Connect TikTok Pixel on Shopify

How to Connect TikTok Pixel on Shopify

In today’s article, we’re going to discuss how to connect TikTok Pixel on Shopify store. Many people have been facing issues recently because Shopify has removed the Additional Scripts section from its latest updates. 

Due to this change, many users are confused about how to integrate their TikTok Pixel properly now. There are two ways to install the TikTok Pixel on your Shopify store: one is through the official TikTok application, and the other is by doing it manually. 

While many users prefer using the app, it’s not always an option, especially for people working from countries like Pakistan, where the TikTok app integration is often unavailable in Shopify. That’s why in this guide, I’ll show you how to manually install the TikTok Pixel on your Shopify store step by step.


E-commerce is a vast platform where countless advertisers invest their money in marketing. Many individuals source different types of products and resell them online. 

Within the e-commerce space, there are various business models like white labeling, private labeling, and dropshipping. A large number of people are actively working in e-commerce, especially using platforms like Shopify to run their online stores.

If someone is investing in a business and running ads for marketing, they would definitely want to know how well those ads are performing. This is where pixels come into play! They help track data and show us how effective our results really are.


As you all know, I have knowledge of coding, and I’ve brought you a method through which you can very easily connect TikTok Pixel manually with your Shopify store.

I have created a script for you that you just need to copy and paste into your Shopify Store by going to the “Customer Events” section. After pasting it, simply click on the “Connect” button, and with just one click, your TikTok Pixel will be connected to your Shopify Store.

Along with sharing information about the TikTok Pixel, I’d also like to let you know that we offer Shopify paid themes, which will be provided to you with a valid license.

Benefits of this method

  1. Proper tracking.
  2. Activate all events (including complete payment).
  3. Easy to Install.

Since Shopify’s recent update, many users have been facing issues with the Complete Payment event not triggering properly. However, with the help of this script, you will be able to easily activate the Complete Payment event without any hassle.


Script for TikTok pixels:

// TikTok Pixel | code by M Asim Tech
if (!window.tiktokPixelLoaded) {
  !function (w, d, t) {
    w.TiktokAnalyticsObject = t;
    var ttq = w[t] = w[t] || [];
    ttq.methods = ["page", "track", "identify", "instances", "debug", "on", "off", "once", "ready", "alias", "group", "enableCookie", "disableCookie", "holdConsent", "revokeConsent", "grantConsent"];
    ttq.setAndDefer = function (t, e) {
      t[e] = function () {
        t.push([e].concat(Array.prototype.slice.call(arguments, 0)));
      };
    };
    for (var i = 0; i < ttq.methods.length; i++) ttq.setAndDefer(ttq, ttq.methods[i]);
    ttq.load = function (e, n) {
      var r = "https://analytics.tiktok.com/i18n/pixel/events.js";
      ttq._i = ttq._i || {}, ttq._i[e] = [], ttq._t = ttq._t || {}, ttq._t[e] = +new Date, ttq._o = ttq._o || {}, ttq._o[e] = n || {};
      var s = d.createElement("script");
      s.type = "text/javascript", s.async = !0, s.src = r + "?sdkid=" + e + "&lib=" + t;
      var f = d.getElementsByTagName("script")[0];
      f.parentNode.insertBefore(s, f);
    };
    ttq.load('D09GM8RC77U9CBHGPVC0'); // Replace it with your Pixel ID
    window.tiktokPixelLoaded = true;
  }(window, document, 'ttq');
}

// Helper function to generate a unique event ID
function generateEventId() {
  return 'event_' + Math.random().toString(36).substr(2, 9);
}

// Đảm bảo các sự kiện chỉ được đăng ký một lần
if (!window.tiktokEventsRegistered) {
  // Event: PageView (kích hoạt khi trang được tải)
  ttq.track('PageView');

  // Event: ViewContent (kích hoạt khi xem sản phẩm)
  analytics.subscribe('product_viewed', (event) => {
    try {
      const eventId = generateEventId(); // Tạo event_id duy nhất
      const payload = {
        content_id: event.id?.toString() || '',
        content_name: event.title || '',
        value: 1,
        currency: 'USD',
        event_id: eventId // Thêm event_id vào payload
      };
      ttq.track('ViewContent', payload);
    } catch (error) {
      console.error('Error tracking ViewContent:', error);
    }
  });

  // Event: AddToCart (kích hoạt khi thêm sản phẩm vào giỏ hàng)
  analytics.subscribe('product_added_to_cart', (event) => {
    try {
      if (!event.data || !event.data.cartLine) {
        console.error('Invalid event data for AddToCart');
        return;
      }
      const cartLine = event.data.cartLine;
      const eventId = generateEventId(); // Tạo event_id duy nhất
      const payload = {
        contents: [{
          content_id: cartLine.merchandise.id || '',
          content_name: cartLine.merchandise.title || '',
          quantity: cartLine.quantity || 1,
          price: parseFloat(cartLine.cost.totalAmount.amount) || 0,
        }],
        value: parseFloat(cartLine.cost.totalAmount.amount) || 0,
        currency: cartLine.cost.totalAmount.currencyCode || 'USD',
        content_type: 'product',
        event_id: eventId // Thêm event_id vào payload
      };
      ttq.track('AddToCart', payload);
    } catch (error) {
      console.error('Error tracking AddToCart:', error);
    }
  });

  // Event: InitiateCheckout (kích hoạt khi bắt đầu thanh toán)
  analytics.subscribe('checkout_started', (event) => {
    try {
      if (!event.data || !event.data.checkout) {
        console.error('Invalid event data for InitiateCheckout');
        return;
      }
      const checkout = event.data.checkout;
      const firstItem = checkout.lineItems[0];
      const eventId = generateEventId(); // Tạo event_id duy nhất
      const payload = {
        contents: [{
          content_id: firstItem?.variant.id || '',
          content_type: 'product', // Sửa thành "product" hoặc "product_group"
          content_name: firstItem?.variant.product.title || '',
        }],
        value: parseFloat(firstItem?.variant.price.amount) || 0,
        currency: checkout.currencyCode || 'USD',
        event_id: eventId // Thêm event_id vào payload
      };
      ttq.track('InitiateCheckout', payload);
    } catch (error) {
      console.error('Error tracking InitiateCheckout:', error);
    }
  });

  // Event: AddPaymentInfo (kích hoạt khi người dùng nhập thông tin thanh toán và gửi đi)
  analytics.subscribe('payment_info_submitted', (event) => {
    try {
      if (!event.data || !event.data.checkout) {
        console.error('Invalid event data for AddPaymentInfo');
        return;
      }

      const checkout = event.data.checkout;
      const checkoutTotalPrice = checkout.totalPrice?.amount;
      const firstDiscountType = checkout.discountApplications[0]?.type;
      const discountCode = firstDiscountType === 'DISCOUNT_CODE' ? checkout.discountApplications[0]?.title : null;

      const eventId = generateEventId(); // Tạo event_id duy nhất
      const payload = {
        value: parseFloat(checkoutTotalPrice) || 0,
        currency: checkout.totalPrice?.currencyCode || 'USD',
        discount_code: discountCode || '', // Thêm mã giảm giá nếu có
        event_id: eventId // Thêm event_id vào payload
      };

      // Gửi sự kiện về TikTok Pixel
      ttq.track('AddPaymentInfo', payload);
    } catch (error) {
      console.error('Error tracking AddPaymentInfo:', error);
    }
  });

  // Event: CompletePayment (kích hoạt khi thanh toán hoàn tất)
  analytics.subscribe('checkout_completed', (event) => {
    try {
      if (!event.data || !event.data.checkout) {
        console.error('Invalid event data for CompletePayment');
        return;
      }
      const checkout = event.data.checkout;
      const firstItem = checkout.lineItems[0];
      const eventId = generateEventId(); // Tạo event_id duy nhất
      const payload = {
        content_id: firstItem?.variant.id || '',
        content_name: firstItem?.variant.product.title || '',
        value: parseFloat(checkout.totalPrice?.amount) || 0,
        currency: checkout.totalPrice?.currencyCode || 'USD',
        order_id: checkout.order?.id || '',
        event_id: eventId // Thêm event_id vào payload
      };
      ttq.track('CompletePayment', payload);
    } catch (error) {
      console.error('Error tracking CompletePayment:', error);
    }
  });

  window.tiktokEventsRegistered = true;
}


How to apply the script? 

Step 1:

Log in to your Shopify dashboard and click on the settings.

How to Connect TikTok Pixel on Shopify

Step 2:

Click on the customer event option.


How to Connect TikTok Pixel on Shopify

Step 3:

Click on 'Add custom pixel'

How to Connect TikTok Pixel on Shopify

Step 4:

Paste your script in the code area and save it.

How to Connect TikTok Pixel on Shopify

Step 4:

Make sure to change your pixel ID. Mostly, it is available in 21 lines of code.

How to Connect TikTok Pixel on Shopify

Step 5:

Click save after replacing the ID, and then click on the connect button.


How to Connect TikTok Pixel on Shopify

Step 6:

Congratulations, your pixel is successfully connected with your Shopify store.

How to Connect TikTok Pixel on Shopify

That's it. Look how easy to connect TikTok pixel with Shopify. Now you have to put a fake order on your store just the activate all the events.

I hope you’ve got all the information related to TikTok Pixel. However, if you still have any questions, feel free to reach out to me on Instagram. I’ll be happy to assist you!
Post a Comment (0)
Previous Post Next Post