> For the complete documentation index, see [llms.txt](https://helps.ptengine.com/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://helps.ptengine.com/cn/start-guide/othertag/tag-shopify.md).

# Shopify 如何部署代码

> 关于Shopify应用集成配置，请参阅[Shopify集成](/cn/integrations/shopify.md)。

## Shopify电商埋码指南 <a href="#shopify-dian-shang-mai-ma-zhi-nan" id="shopify-dian-shang-mai-ma-zhi-nan"></a>

### 以下提供的脚本方便Shopify电商客户进行快速埋码设置 <a href="#yi-xia-ti-gong-de-jiao-ben-fang-bian-shopify-dian-shang-ke-hu-jin-xing-kuai-su-mai-ma-she-zhi" id="yi-xia-ti-gong-de-jiao-ben-fang-bian-shopify-dian-shang-ke-hu-jin-xing-kuai-su-mai-ma-she-zhi"></a>

#### 1. 代码中找到theme.liquid模板，设置基础埋码 <a href="#id-1-dai-ma-zhong-zhao-dao-themeliquid-mu-ban-she-zhi-ji-chu-mai-ma" id="id-1-dai-ma-zhong-zhao-dao-themeliquid-mu-ban-she-zhi-ji-chu-mai-ma"></a>

Tips: xxxxx位置[具体参考](/cn/start-guide/quick/tag-setup.md)![Alt](https://help-ptengine-com-vitepress.oss-cn-guangzhou.aliyuncs.com/Build/2-2/ji-chu-dai-ma.jpg)

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

#### 2. 事件采集部署 <a href="#id-2-shi-jian-cai-ji-bu-shu" id="id-2-shi-jian-cai-ji-bu-shu"></a>

打开设置中的“客户事件”，将下列代码中的sid和步骤一一样，替换为sid\
\
![](https://help-ptengine-com-vitepress.oss-cn-guangzhou.aliyuncs.com/shopify/%E5%BE%AE%E4%BF%A1%E6%88%AA%E5%9B%BE_20240226132049.png)\
\
并全部粘贴进自定义像素中。\
保存并连接。 请务必将id替换为您的sid

```
function trackEvent(eventType, eventProperties, cb) {
    //请务必将id替换为您的档案id
    const sid = "请输入档案id";
    const area = "com";
    const options = eventProperties || {};

    loadPtengineScript(sid, area)
      .then(() => {
        console.log("ptengine脚本加载完成");
        window.ptengine && window.ptengine.track(eventType, options);
        cb && typeof cb === "function" && cb();
      })
      .catch((error) => {
        console.error("ptengine脚本加载失败:", error);
      });
  }

  function loadPtengineScript(sid, area) {
    return new Promise((resolve, reject) => {
      if (window.ptengine) {
        // 如果ptengine已经存在，则立即解决
        resolve();
      } else {
        // 兼容 /wpm@.../web-pixel-... 与 /web-pixels@.../custom/web-pixel-... 两种沙箱路径
        const url = window.location.href.replace(
          /\/(?:wpm|web-pixels)@[^/]+\/(?:custom\/)?web-pixel-[^/]+\/sandbox\/modern/,
          ""
        );

        // 使用原始url进行发包
        window._pt_sp_2 = [];
        _pt_sp_2.push(`setAccount, ${sid}`);
        _pt_sp_2.push(`setPVTag,${url},replace`);

        // 动态加载ptengine脚本
        const script = document.createElement("script");
        // 判断是否在checkout页面
        const isCheckoutPage = window.location.href.includes("checkouts");
        const sandboxQuery = isCheckoutPage ? "" : "?sandbox"; // checkout页面不添加'?sandbox'
        script.src = `https://js.ptengine.${area}/${sid}.js${sandboxQuery}`;
        script.onload = () => resolve(); // 加载成功
        script.onerror = () => reject(new Error("Script loading failed")); // 加载失败
        document.head.appendChild(script);
      }
    });
  }

  // 去除空值属性，避免发送 null/undefined/'' 字段
  function removeEmptyKeys(obj) {
    for (let key in obj) {
      if (
        obj.hasOwnProperty(key) &&
        (obj[key] === null || obj[key] === undefined || obj[key] === "")
      ) {
        delete obj[key];
      }
    }
    return obj;
  }

  // 订单完成：1 条订单级 checkout_completed + 每个商品 1 条 checkout_completed_order
  analytics.subscribe("checkout_completed", (event) => {
    const checkout = event?.data?.checkout;
    if (!checkout) return;

    // 从订单客户 ID（gid://shopify/Customer/xxx）中提取数字 ID 作为 uid
    const rawCustomerId = checkout?.order?.customer?.id;
    const numericCustomerId = rawCustomerId ? rawCustomerId.split("/").pop() : null;
    const uid = numericCustomerId;
    const totalPrice = checkout?.totalPrice?.amount;
    const currencyCode = checkout?.totalPrice?.currencyCode;
    const orderId = checkout?.order?.id;
    const items = checkout?.lineItems || [];

    // 1) identify：整单一次，把订单信息写到用户档案
    if (uid) {
      window.ptengine &&
        ptengine.identify(uid, {
          totalPrice: totalPrice,
          totalorderid: orderId,
        });
    }

    // 2) track：只发一次订单级 checkout_completed（不含商品明细）
    const eventProperties = removeEmptyKeys({
      totalPrice: totalPrice,
      currencyCode: currencyCode,
      totalorderid: orderId,
      productCount: items.length,
    });
    trackEvent("checkout_completed", eventProperties, () => {
      // 3) 商品明细：每个商品单独发 1 条 checkout_completed_order，
      //    带 totalorderid 以便与订单级事件关联；此时脚本已加载完成，直接 track
      items.forEach((item) => {
        const itemProperties = removeEmptyKeys({
          totalorderid: orderId,
          sku: item?.variant?.sku,
          name: item?.title,
          spu: item?.variant?.product?.type,
          id: item?.id,
          quantity: item?.quantity,
          price: item?.finalLinePrice?.amount,
          currencyCode: currencyCode,
        });
        window.ptengine && window.ptengine.track("checkout_completed_order", itemProperties);
      });
    });
  });

  analytics.subscribe("search_submitted", (event) => {
    const eventProperties = removeEmptyKeys({
      keyword: event?.data?.searchResult?.query,
      resultCount: event?.data?.searchResult?.productVariants?.length,
    });
    trackEvent("search_submitted", eventProperties);
  });

  analytics.subscribe("collection_viewed", (event) => {
    const eventProperties = removeEmptyKeys({
      id: event?.data?.collection?.id,
      name: event?.data?.collection?.title,
      productCount: event?.data?.collection?.productVariants?.length,
    });
    trackEvent("collection_viewed", eventProperties);
  });

  analytics.subscribe("product_viewed", (event) => {
    const origin = event?.context?.window?.origin || window.location.origin;
    const variant = event?.data?.productVariant;
    const eventProperties = removeEmptyKeys({
      sku: variant?.sku,
      name: variant?.product?.title,
      type: variant?.product?.type,
      spu: variant?.product?.type,
      price: variant?.price?.amount,
      currencyCode: variant?.price?.currencyCode,
      url: variant?.product?.url ? `${origin}${variant.product.url}` : undefined,
      imageUrl: variant?.image?.src,
    });
    trackEvent("product_viewed", eventProperties);
  });

  analytics.subscribe("product_added_to_cart", (event) => {
    const origin = event?.context?.window?.origin || window.location.origin;
    const merchandise = event?.data?.cartLine?.merchandise;
    const eventProperties = removeEmptyKeys({
      url: merchandise?.product?.url ? `${origin}${merchandise.product.url}` : undefined,
      name: merchandise?.product?.title,
      sku: merchandise?.sku,
      quantity: event?.data?.cartLine?.quantity,
      price: merchandise?.price?.amount,
      currencyCode: merchandise?.price?.currencyCode,
      spu: merchandise?.product?.type,
    });
    trackEvent("product_added_to_cart", eventProperties);
  });

  analytics.subscribe("product_removed_from_cart", (event) => {
    const origin = event?.context?.window?.origin || window.location.origin;
    const merchandise = event?.data?.cartLine?.merchandise;
    const eventProperties = removeEmptyKeys({
      url: merchandise?.product?.url ? `${origin}${merchandise.product.url}` : undefined,
      name: merchandise?.product?.title,
      sku: merchandise?.sku,
      quantity: event?.data?.cartLine?.quantity,
      price: merchandise?.price?.amount,
      currencyCode: merchandise?.price?.currencyCode,
      spu: merchandise?.product?.type,
    });
    trackEvent("product_removed_from_cart", eventProperties);
  });

  analytics.subscribe("cart_viewed", (event) => {
    const cart = event?.data?.cart;
    if (!cart) {
      trackEvent("cart_viewed");
      return;
    }
    const origin = event?.context?.window?.origin || window.location.origin;
    const lines = cart?.lines || [];
    if (lines.length) {
      lines.forEach((line) => {
        const merchandise = line?.merchandise;
        const eventProperties = removeEmptyKeys({
          totalQuantity: cart?.totalQuantity,
          url: merchandise?.product?.url ? `${origin}${merchandise.product.url}` : undefined,
          name: merchandise?.product?.title,
          sku: merchandise?.sku,
          spu: merchandise?.product?.type,
          quantity: line?.quantity,
          price: line?.cost?.totalAmount?.amount,
          currencyCode: line?.cost?.totalAmount?.currencyCode,
        });
        trackEvent("cart_viewed", eventProperties);
      });
    } else {
      trackEvent("cart_viewed", removeEmptyKeys({ totalQuantity: cart?.totalQuantity }));
    }
  });

  analytics.subscribe("checkout_started", (event) => {
    const checkout = event?.data?.checkout;
    const origin = event?.context?.window?.origin || window.location.origin;
    const checkoutItems = checkout?.lineItems;
    const totalPrice = checkout?.subtotalPrice?.amount;
    const currencyCode = checkout?.subtotalPrice?.currencyCode;

    if (checkoutItems && checkoutItems.length) {
      checkoutItems.forEach((item) => {
        const eventProperties = removeEmptyKeys({
          totalPrice: totalPrice,
          currencyCode: currencyCode,
          url: item?.variant?.product?.url ? `${origin}${item.variant.product.url}` : undefined,
          name: item?.variant?.product?.title,
          sku: item?.variant?.sku,
          spu: item?.variant?.product?.type,
          quantity: item?.quantity,
          price: item?.finalLinePrice?.amount,
        });
        trackEvent("checkout_started", eventProperties);
      });
    } else {
      trackEvent("checkout_started", removeEmptyKeys({ totalPrice, currencyCode }));
    }
  });

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

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

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

  analytics.subscribe("payment_info_submitted", (event) => {
    const checkout = event?.data?.checkout;
    const eventProperties = removeEmptyKeys({
      totalPrice: checkout?.subtotalPrice?.amount,
      currencyCode: checkout?.subtotalPrice?.currencyCode,
    });
    trackEvent("payment_info_submitted", eventProperties);
  });
```

<br>

#### 3.事件定义： <a href="#id-3-shi-jian-ding-yi" id="id-3-shi-jian-ding-yi"></a>

search\_submitted:使用搜索功能

collection\_viewed：列表页访问

product\_viewed：商品详情页访问

product\_added\_to\_cart：添加购物车

product\_removed\_from\_cart：移除购物车

cart\_viewed：购物车页面访问

checkout\_started：进入checkout页面

checkout\_contact\_info\_submitted：输入联系方式：邮箱

checkout\_address\_info\_submitted：输入地址

checkout\_shipping\_info\_submitted：选择快递信息

payment\_info\_submitted：选择支付方式

checkout\_completed：支付成功（订单级，一单一条）

checkout\_completed\_order：支付成功的商品明细（商品级，一单内每个商品一条，通过totalorderid与订单级事件关联）
