// Step 1: Initialize the Facebook Pixel SDK
!function(f,b,e,v,n,t,s)
{if(f.fbq)return;n=f.fbq=function(){n.callMethod?
n.callMethod.apply(n,arguments):n.queue.push(arguments)};
if(!f._fbq)f._fbq=n;n.push=n;n.loaded=!0;n.version='2.0';
n.queue=[];t=b.createElement(e);t.async=!0;
t.src=v;s=b.getElementsByTagName(e)[0];
s.parentNode.insertBefore(t,s)}(window, document,'script',
'https://connect.facebook.net/en_US/fbevents.js');
// **初始化两个 Facebook Pixel**
const pixelIds = ['pixelida', 'pixelidb'];
pixelIds.forEach(id => fbq('init', id));
pixelIds.forEach(id => fbq('track', 'PageView', {}, { eventID: `pageview-${id}` }));
// **封装函数,避免重复代码**
function trackEvent(eventName, eventData) {
pixelIds.forEach(id => {
fbq('track', eventName, eventData, { eventID: `${eventName}-${id}` });
});
}
// Step 2: 订阅 Shopify Customer Events 并追踪到多个 Pixel
analytics.subscribe("product_viewed", event => {
trackEvent('ViewContent', {
content_ids: [event.data.productVariant.product.id],
content_name: event.data.productVariant.product.title,
content_type: 'product_group',
content_category: event.data.productVariant.product.type,
value: event.data.productVariant.price.amount,
currency: event.data.productVariant.price.currencyCode
});
});
analytics.subscribe("product_added_to_cart", event => {
trackEvent('AddToCart', {
content_ids: [event.data.cartLine.merchandise.id],
content_name: event.data.cartLine.merchandise.title,
content_type: 'product',
value: event.data.cartLine.cost.totalAmount.amount,
currency: event.data.cartLine.cost.totalAmount.currencyCode,
quantity: event.data.cartLine.quantity
});
});
analytics.subscribe("checkout_started", event => {
trackEvent('InitiateCheckout', {
value: event.data.checkout.totalPrice.amount,
currency: event.data.checkout.totalPrice.currencyCode
});
});
analytics.subscribe("checkout_completed", event => {
const lineItems = event.data.checkout.lineItems.map(item => ({
id: item.variant.id,
name: item.title,
price: item.variant.price.amount,
quantity: item.quantity
}));
trackEvent('Purchase', {
content_ids: lineItems.map(item => item.id),
content_type: 'product',
value: event.data.checkout.totalPrice.amount,
currency: event.data.checkout.totalPrice.currencyCode,
num_items: lineItems.length,
contents: lineItems
});
});
参考:https://developers.facebook.com/docs/meta-pixel/advanced/?locale=zh_CN

