当前位置:迷你笔记 » 技术 » 用Shopify Custom Events方式向谷歌分析GA4传值(实例一)

用Shopify Custom Events方式向谷歌分析GA4传值(实例一)

// Step 1. Add and initialize your third-party JavaScript pixel (make sure to exclude HTML)
// Replace with you GA4 Tag
const TAG_ID = 'G-XXXXXXXXXX';

const script = document.createElement('script');
script.setAttribute('src', `https://www.googletagmanager.com/gtag/js?id=${TAG_ID}`);
script.setAttribute('async', '');
document.head.appendChild(script);

window.dataLayer = window.dataLayer || [];
function gtag(){dataLayer.push(arguments);}

gtag('js', new Date());
gtag('config', TAG_ID);
gtag('config', TAG_ID, {'send_page_view': false}); // Disable default page view tracking, doesn't send decent page view data to GA4, reference: https://help.shopify.com/en/manual/promoting-marketing/pixels/custom-pixels/gtm-tutorial

// Step 2. Subscribe to customer events using the analytics.subscribe() API
const sendGAEvent = (eventName, eventData) => {
  gtag("event", eventName, eventData);
};

const createItemData = (product) => {
  return {
    item_id: product.sku,
    item_name: product.product.title,
    item_variant: product.title,
    currency: product.price.currencyCode,
    item_brand: product.product.vendor,
    price: product.price.amount,
  };
};

const createLineItemsData = (lineItems) => {
  return lineItems.map((item) => {
    return {
      item_id: item.variant.sku,
      item_name: item.title,
      item_variant: item?.variant.title,
      currency: item.variant.price.currencyCode,
      item_brand: item.variant.product.vendor,
      price: item.variant.price.amount,
      quantity: item.quantity,
    };
  });
};

// Send page view data with custom event instead, reference: https://developers.google.com/tag-platform/gtagjs/reference/events#page_view
analytics.subscribe("page_viewed", event => {
  gtag("event", "page_view", {
    page_location: event.context.window.location.href,
    page_title: event.context.document.title,
    language: event.context.navigator.language,
    page_encoding: event.context.document.characterSet,
    user_agent:  event.context.navigator.userAgent,
    client_id: event.clientId
  });
});

analytics.subscribe("search_submitted", (event) => {
  const { query } = event.data.searchResult;
  sendGAEvent("search", { search_term: query });
  sendGAEvent("view_search_results", { search_term: query, items: [] });
});

analytics.subscribe("collection_viewed", (event) => {
  const { id, title } = event.data.collection;
  sendGAEvent("view_item_list", { item_list_id: id, item_list_name: title, items: [] });
});

analytics.subscribe("product_added_to_cart", (event) => {
  const { cartLine } = event.data;
  const totalPrice = cartLine.merchandise.price.amount * cartLine.quantity;
  const itemData = createItemData(cartLine.merchandise.product);

  sendGAEvent("add_to_cart", {
    currency: cartLine.merchandise.price.currencyCode,
    value: totalPrice.toFixed(2),
    items: [Object.assign(itemData, { quantity: cartLine.quantity })],
  });
});

analytics.subscribe("product_viewed", (event) => {
  const { productVariant } = event.data;
  const itemData = createItemData(productVariant);

  sendGAEvent("view_item", {
    currency: productVariant.price.currencyCode,
    value: productVariant.price.amount,
    items: [itemData],
  });
});

analytics.subscribe("checkout_started", (event) => {
  const checkoutData = ga4CheckoutEvents(event);
  sendGAEvent("begin_checkout", checkoutData);
});

analytics.subscribe("payment_info_submitted", (event) => {
  const checkoutData = ga4CheckoutEvents(event);
  sendGAEvent("add_payment_info", checkoutData);
});

analytics.subscribe("checkout_completed", (event) => {
  const checkoutData = ga4CheckoutEvents(event);
  const { checkout } = event.data;
  
  checkoutData.transaction_id = checkout.order?.id || checkout.token;
  checkoutData.shipping = checkout.shippingLine?.price.amount || checkout.shipping_line?.price.amount || 0;
  checkoutData.tax = checkout.totalTax?.amount || 0;
  
  sendGAEvent("purchase", checkoutData);
});

function ga4CheckoutEvents(event) {
  const { checkout } = event.data;
  const lineItems = createLineItemsData(checkout.lineItems);
  
  return {
    currency: checkout.totalPrice.currencyCode,
    value: checkout.totalPrice.amount,
    items: lineItems,
  };
}

如果“增强转化”功能无法正常工作。你可以通过自定义事件添加出站链接跟踪,也可以在GA4配置里关闭出站链接(Outbound clicks)。另外建议禁用下图中的所有这些功能,这样网页加载会变快,主要这些你也用不上。

未经允许不得转载:迷你笔记 » 用Shopify Custom Events方式向谷歌分析GA4传值(实例一)

相关文章

评论 (0)

7 + 3 =