> 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/start-guide/othertag/tag-shopify.md).

# Shopifyでタグ設置

> Shopifyアプリとの連携設定については[Shopify連携](/integrations/shopify.md)もご覧ください。

## 基本タグの設置

### 1. theme.liquidテンプレートを見つける

Shopify管理画面で「Online Store」→「Themes」を選択し、「…」ボタンから「Edit code」を選択

### 2. \<head>の下にptengineの基本タグを設置

下記画像右側の赤枠の部分に、Ptengineの基本タグを貼り付けてください。

#### **基本タグの一例**

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

{% hint style="danger" %}
**⚠️注意**

上記xxxxxxxxの部分はプロジェクトのIDであり、Ptengineのプロジェクトごとに異なります。

自社プロジェクトのIDと書き換えてください。

詳しくは[こちらの記事](https://ptmind-1.gitbook.io/ptengine-helpcenter/start-guide/quick/tag-setting)をご参照ください。
{% endhint %}

#### **Ptengineの基本タグの取得方法**

{% embed url="<https://app.arcade.software/share/9Co1auPt7xkZweCU7ehH>" %}

## イベントの設置

上記基本タグを設置するのみで、**購買完了、カートイン**などECサイトでよくある行動データの集計ができません。

そのため、Ptengine上でもイベントデータやCVデータを確認したい場合、イベントの設置もおすすめです。

### イベント収集タグの導入

#### 1、Shopify管理画面で「Settings」を選択

#### 2、「Customer events」を選択

#### 3、Pixel nameをつける

右上の黒いボタン「Add custom pixel」をクリックし、ポップアップの中でpixel nameを設定します。（下記図はサンプルとして「pt tracking on checkouts」という名前をつけております）

そしてAdd pixelをクリックしてください。

#### 4、保存

Codeに下記コードを貼り付けて、右上の「save」で保存します。

{% hint style="danger" %}
**⚠️注意**

**必ず**　`const sid`　**に自社PtengineのプロジェクトIDに置き換えてください！！！**
{% endhint %}

```js
// 貼り付け用コード
function trackEvent(eventType, eventProperties, cb) {
  const sid = "プロファイルidを入力してください";
  // プロジェクトIDを入れてください！
  const area = "jp";
  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
      resolve();
    } else {
      // /wpm@.../web-pixel-... と /web-pixels@.../custom/web-pixel-... の両方のサンドボックスパスに対応
      const url = window.location.href.replace(
        /\/(?:wpm|web-pixels)@[^/]+\/(?:custom\/)?web-pixel-[^/]+\/sandbox\/modern/,
        ""
      );
      window._pt_sp_2 = [];
      _pt_sp_2.push(`setAccount, ${sid}`);
      _pt_sp_2.push(`setPVTag,${url},replace`);

      const script = document.createElement("script");
      const isCheckoutPage = window.location.href.includes("checkouts");
      const sandboxQuery = isCheckoutPage ? "" : "?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;
}

// 注文完了：checkout_completed は1回だけ送信
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 || [];

  // 商品明細を配列にまとめ、同一イベントに含めて送信
  const products = items.map((item) =>
    removeEmptyKeys({
      sku: item?.variant?.sku,
      name: item?.title,
      spu: item?.variant?.product?.type,
      id: item?.id,
      quantity: item?.quantity,
      price: item?.finalLinePrice?.amount,
    })
  );

  // 1) identify：注文ごとに1回、注文情報をユーザープロファイルに書き込む
  if (uid) {
    window.ptengine &&
      ptengine.identify(uid, {
        totalPrice: totalPrice,
        totalorderid: orderId,
      });
  }

  // 2) track：checkout_completed を1回だけ送信
  const eventProperties = removeEmptyKeys({
    totalPrice: totalPrice,
    currencyCode: currencyCode,
    totalorderid: orderId,
    products: products,
  });
  trackEvent("checkout_completed", eventProperties);
});

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);
});

```

#### 5、公開

最後に右上の「Connect」ボタンを押してStep4で設置したコードを公開します。

### イベントタグの発火タイミングについて

<table><thead><tr><th width="318.41796875">イベント名</th><th>発火タイミング</th></tr></thead><tbody><tr><td>search_submitted</td><td>検索機能を使用した際</td></tr><tr><td>collection_viewed</td><td>一覧ページを閲覧した際</td></tr><tr><td>product_viewed</td><td>商品詳細ページを閲覧した際</td></tr><tr><td>product_added_to_cart</td><td>カートに商品を追加した際</td></tr><tr><td>product_removed_from_cart</td><td>カートから商品を削除した際</td></tr><tr><td>cart_viewed</td><td>カートページを閲覧した際</td></tr><tr><td>checkout_started</td><td>Checkoutページへ遷移した際</td></tr><tr><td>checkout_contact_info_submitted</td><td>連絡先（メールアドレス）を入力した際</td></tr><tr><td>checkout_address_info_submitted</td><td>住所情報を入力した際</td></tr><tr><td>checkout_shipping_info_submitted</td><td>配送方法を選択した際</td></tr><tr><td>payment_info_submitted</td><td>支払い方法を選択した際</td></tr><tr><td>checkout_completed</td><td>支払いが完了した際</td></tr></tbody></table>

## 注意事項

ShopifyでPtengineをご利用いただく際は、以下の点を必ずご確認ください。

### **1. Ptengineの基本タグは「Shopifyのテーマ」に直接設置してください**

Ptengineの基本タグは、Shopifyのテーマ（theme.liquid）へ直接設置してください。

Google Tag Manager経由での設置は、Shopifyの仕様上イベント計測ができない場合がございます。

そのため、GTMなどなどのタグマネージャーの経由での設置は推奨しておらず、サポート対象外となります。

### **2. ページ単位の送信制限や条件追加をしないでください**

Ptengine の基本スクリプトをアレンジし特定ページのみで発火させることやURL条件などで発火を制限することを推奨しておりません。

その状態で発生したデータ計測の不具合については、原因調査やサポート対応ができかねますのでご了承ください。

### **3. テーマを変更した場合は、再度タグ設置が必要です**

Shopifyでは、テーマを変更すると theme.liquid の内容がリセットされます。

そのため、テーマの切り替えや新しいテーマの適用を行った場合、

新しいテーマにもPtengineの基本タグを再度設置してください。

タグを再設置しない場合、Ptengineの計測は行われませんのでご注意ください。
