Track SKU products or subscriptions separately in Shopify


SKU tracking

You can create a goal that would fire only when a product with a certain SKU is purchased.

For this, you would need to install the following JavaScript code in the same way that the manual revenue tracking is installed on Shopify. You could append the code along the manual revenue tracking code, making a goal for general revenue tracking and one for a specific SKU. 

You would only need to change the id, to the revenue goal that you create for this on the Convert app.

<script>
total_sku_revenue = 0;
total_sku_products = 0;

function reportRevenue(revenue,product_count) {
    _conv_q = window._conv_q || [];
    // Replace the number for your Revenue Goal Id
    _conv_q.push(["pushRevenue", revenue, product_count, "100134184"]);
    console.log('SKU Specific Report:revenue='+revenue+': Product Count='+product_count);
}
Shopify.checkout.line_items.forEach(product => {
  if (product.sku.includes('rose')){
    total_sku_revenue = product.line_price + total_sku_revenue;      
    total_sku_products =  1 + total_sku_products;
  }
})

if (total_sku_products > 0) {
reportRevenue(total_sku_revenue,total_sku_products)
}
total_sku_revenue = 0;
total_sku_products = 0;

function reportRevenue(revenue,product_count) {
    _conv_q = window._conv_q || [];
    // Replace the number for your Revenue Goal Id
    _conv_q.push(["pushRevenue", revenue, product_count, "100134184"]);
    console.log('SKU Specific Report:revenue='+revenue+': Product Count='+product_count);
}
Shopify.checkout.line_items.forEach(product => {
  if (product.sku.includes('rose')){
    total_sku_revenue = product.line_price + total_sku_revenue;      
    total_sku_products =  1 + total_sku_products;
  }
})

if (total_sku_products > 0) {
reportRevenue(total_sku_revenue,total_sku_products)
}
</script>

Subscription Tracking

To separate subscriptions from non-subscriptions you can use the following code. Make sure you add a separate revenue goal for subscriptions and non subscriptions.

<script>

document.addEventListener("DOMContentLoaded", function() {

convertRevenueCurrency = false;
currencyToConvertTo = 'USD';

function reportRevenue(revenue, product_count, goal_id, purchase_type, Currency) {
_conv_q = window._conv_q || [];
// Enable next line if currency conversion is needed.
if (convertRevenueCurrency) {
revenue = Currency.convert(revenue, Shopify.checkout.currency, currencyToConvertTo);
}
_conv_q.push(["pushRevenue", revenue, product_count, goal_id]);
console.log(purchase_type + ' Report:revenue=' + revenue + ': Product Count=' + product_count);
}

const xhr = new XMLHttpRequest();
xhr.open('GET', 'https://cdn.shopify.com/s/javascripts/currencies.js');
xhr.onload = function() {
console.log('xhr status' + xhr.status);
if (xhr.status === 200) {
eval(xhr.responseText);
total_subs_revenue = 0;
total_subs_products = 0;
total_non_subs_revenue = 0;
total_non_subs_products = 0;

Shopify.checkout.line_items.forEach(product => {
// Following line checks if it is a subscribed product by query a specific property of the product
if (product.selling_plan_allocation.selling_plan.recurring_deliveries)
total_subs_revenue = product.line_price - product.line_level_total_discount + total_subs_revenue;
total_subs_products = 1 + total_subs_products;
} else {
total_non_subs_revenue = product.line_price - product.line_level_total_discount + total_non_subs_revenue;
total_non_subs_products = 1 + total_non_subs_products;
}
})

if (total_subs_products > 0) {
// Change goal id to the one created for subscriptions
reportRevenue(total_subs_revenue, total_subs_products, '10044705', 'subscriptions', Currency);
}
if (total_non_subs_products > 0) {
// Change goal id to the one created for non subscriptions
reportRevenue(total_non_subs_revenue, total_non_subs_products, '10044706', 'non subscription', Currency);
}
}
};
xhr.send();
});
</script>

Tracking Subscriptions within Shopify Customer Events

You can substitute your Shopify Customer Event code to separate subscriptions from non-subscriptions.

// Define goal IDs for various events
const subsPurchaseGoalId = '100449649';
const nonSubsPurchaseGoalId = '100449650';
const addToCartGoalId = '100132264';

// Function to post transaction details
function postTransaction(convertAttributesStr, purchaseEvent) {
try {
const subscriptionProductVars = JSON.parse(localStorage.getItem('recurringVariantIds'))
const convertAttributes = JSON.parse(convertAttributesStr);
const conversionRate = parseFloat(convertAttributes.conversionRate) || 1; // Default to 1 if not provided
console.log('Conversion attributes parsed successfully:', convertAttributes);
console.log('Conversion rate used:', conversionRate);
let totalSubsRevenue = 0;
let totalSubsProducts = 0;
let totalNonSubsRevenue = 0;
let totalNonSubsProducts = 0;

// Iterate over each product in the checkout event
purchaseEvent.data.checkout.lineItems.forEach(product = {
console.log('Processing product:', product);
console.log('product' + product);
if (subscriptionProductVars.includes(product.variant.id)) {
totalSubsRevenue += product.variant.price.amount / conversionRate;
totalSubsProducts += product.quantity;
} else {
totalNonSubsRevenue += product.variant.price.amount / conversionRate;
totalNonSubsProducts += product.quantity;
}
});
console.log('Total subscription products:', totalSubsProducts, 'Total revenue:', totalSubsRevenue);
console.log('Total non-subscription products:', totalNonSubsProducts, 'Total revenue:', totalNonSubsRevenue);

// Build POST data for subscription products
if (totalSubsProducts  0) {
postConversion(convertAttributes, subsPurchaseGoalId);
}
// Build POST data for non-subscription products
if (totalNonSubsProducts  0) {
postConversion(convertAttributes, nonSubsPurchaseGoalId);
}
} catch (error) {
console.error('Failed to parse conversion attributes:', error);
}
}

// Function to post conversion for Add to Cart events
function postConversion(convertAttributesStr, goalId) {
console.log('Convert: Triggering Add to Cart Shopify Customer Event with goal id:', goalId);
try {
const convertAttributes = JSON.parse(convertAttributesStr);
const post = {
'cid': convertAttributes.cid,
'pid': convertAttributes.pid,
'seg': convertAttributes.defaultSegments,
's': 'shopify',
'vid': convertAttributes.vid,
'ev': [{
'evt': 'hitGoal',
'goals': [goalId],
'exps': convertAttributes.exps,
'vars': convertAttributes.vars
}]
};
const data = JSON.stringify(post);
console.log('Data for Add to Cart:', data);
navigator.sendBeacon(`https://${convertAttributes.pid}.metrics.convertexperiments.com/track`, data);
} catch (error) {
console.error('Error parsing conversion attributes for Add to Cart:', error);
}
}

// Event subscriptions
analytics.subscribe("checkout_completed", async (event) = {
console.log('Checkout completed event received:', event);
const convertAttributesStr = localStorage.getItem('convert_attributes');
if (convertAttributesStr) {
console.log('Convert attributes string retrieved:', convertAttributesStr);
postConversion(convertAttributesStr, addToCartGoalId);
postTransaction(convertAttributesStr, event);
} else {
console.log('Convert localStorage retrieval failed.');
}
});

analytics.subscribe("product_added_to_cart", async (event) = {
console.log('Product added to cart event received:', event);
const convertAttributesStr = localStorage.getItem('convert_attributes');
if (convertAttributesStr) {
postConversion(convertAttributesStr, addToCartGoalId);
} else {
console.error('Convert localStorage retrieval failed.');
}
});
Need assistance? Start a conversation with our Support Team.
CONVERT MORE

Reliably Convert More Site Visitors, Even If Everything Else is Changing in Your Business.

START 15-DAY FREE TRIAL
✓ No Credit Card  ✓ Easy Set-Up  ✓ Access All Features

Comments