Skip to main content

Google Tag Manager Integration

In this guide: Learn how to implement Li2 conversion tracking using Google Tag Manager - no code changes required.

Google Tag Manager

Google Tag Manager (GTM) is the most popular way to implement Li2 conversion tracking without touching your website’s code. This method is ideal for marketers who want control over tracking without depending on developers.

Prerequisites

Required: Your website must already have Google Tag Manager installed. If not, follow Google’s GTM installation guide first.
Before you begin, ensure you have:

GTM Container

GTM script installed on your website

Conversion Tracking Enabled

Enabled in touchpoint settings (see Setup Guide)

Publishable Key

Available in Settings → Analytics

GTM Edit Access

Permission to create tags and variables

GTM Setup: Install Li2 SDK

Step 1: Create Custom HTML Tag

1

Open GTM Container

Log in to Google Tag Manager and select your container
2

Create New Tag

Click TagsNew → Name it “Li2 Analytics - SDK Loader”
3

Configure Tag

  1. Tag Type: Choose Custom HTML
  2. HTML Content: Paste the script below
  3. Triggering: Select All Pages
Script to paste:
<script>
!(function (c, n) {
  c[n] = c[n] || function () {
    (c[n].q = c[n].q || []).push(arguments);
  };
  var methods = ["trackLead", "trackSale"];
  for (var i = 0; i < methods.length; i++) {
    (function(method) {
      c[n][method] = function() {
        var args = Array.prototype.slice.call(arguments);
        c[n].apply(c[n], [method].concat(args));
      };
    })(methods[i]);
  }
  var s = document.createElement("script");
  s.defer = 1;
  s.src = "https://unpkg.com/@li2/analytics/dist/index.global.js";
  s.setAttribute("data-publishable-key", "li2_pk_xxxxxxxx");
  document.head.appendChild(s);
})(window, "li2Analytics");
</script>
IMPORTANT: Replace li2_pk_xxxxxxxx with your actual publishable key from Settings → Analytics in Li2 dashboard.
Why All Pages trigger? The SDK needs to load on every page to:
  • Capture click IDs when users arrive from your touchpoints
  • Make li2Analytics object available for tracking events
  • Set the li_cid cookie for attribution

Step 2: Create Click ID Variable

This variable reads the li_cid cookie set by Li2 when users click your touchpoint links.
1

Create New Variable

Click VariablesUser-Defined VariablesNew
2

Configure Variable

  1. Variable Type: 1st Party Cookie
  2. Cookie Name: li_cid
  3. Variable Name: “Li2 Click ID”
3

Save Variable

Click Save. You can now reference this as {{Li2 Click ID}} in your tags

GTM Lead Tracking

Track when users sign up, register, or show interest in your product/service. When to use: You redirect users to a thank you page after form submission (e.g., /thank-you, /success, /welcome)
1

Create New Tag

TagsNew → Name: “Li2 - Track Lead - Thank You Page”
2

Configure Tag Type

Select Custom HTML and paste the script below
3

Set Up Trigger

TriggeringNew Trigger:
  • Trigger Type: Page View
  • This trigger fires on: Some Page Views
  • Condition: Page URL contains /thank-you (adjust to match your URL)
Script:
<script>
(function() {
  // Extract user info from URL parameters (common pattern)
  var params = new URLSearchParams(window.location.search);
  var email = params.get("email");
  var name = params.get("name");

  // Get click ID from GTM variable
  var clickId = {{Li2 Click ID}} || "";

  // Only track if we have both email and clickId
  if (email && clickId) {
    li2Analytics.trackLead({
      eventName: "Sign Up",
      customerExternalId: email,
      customerName: name || email,
      customerEmail: email,
      clickId: clickId
    });
  }
})();
</script>
Customize for your use case:
  • If customer info is in localStorage or sessionStorage, retrieve it from there
  • If you use data layer, read from dataLayer.push() variables
  • If form is on the same page, read from DOM elements (see Option 2)

Option 2: Form Submission Tracking

When to use: You want to track immediately when the form is submitted (no redirect)
1

Create New Tag

TagsNew → Name: “Li2 - Track Lead - Form Submission”
2

Configure Tag Type

Select Custom HTML and paste the script below
3

Set Up Trigger

TriggeringNew Trigger:
  • Trigger Type: Form Submission
  • This trigger fires on: Specific forms (use form ID or class)
  • Wait for Tags: Check “Wait for Tags” with max wait time 2000ms
Script:
<script>
(function() {
  // Get form field values (adjust selectors to match your form)
  var nameField = document.getElementById("name");
  var emailField = document.getElementById("email");
  var name = nameField ? nameField.value : "";
  var email = emailField ? emailField.value : "";

  // Get click ID from GTM variable
  var clickId = {{Li2 Click ID}} || "";

  // Only track if we have both email and clickId
  if (email && clickId) {
    li2Analytics.trackLead({
      eventName: "Sign Up",
      customerExternalId: email,
      customerName: name || email,
      customerEmail: email,
      clickId: clickId
    });
  }
})();
</script>
IMPORTANT: Update the DOM selectors (getElementById, querySelector) to match your actual form field IDs or classes. Inspect your form HTML to find the correct selectors.

GTM Sale Tracking

Track revenue when customers make purchases. When to use: You redirect users to an order confirmation page after successful payment (e.g., /order-confirmation, /checkout/success)
1

Create New Tag

TagsNew → Name: “Li2 - Track Sale - Order Confirmation”
2

Configure Tag Type

Select Custom HTML and paste the script below
3

Set Up Trigger

TriggeringNew Trigger:
  • Trigger Type: Page View
  • This trigger fires on: Some Page Views
  • Condition: Page URL contains /order-confirmation (adjust to match your URL)
Script:
<script>
(function() {
  // Extract order info from URL parameters (common for payment gateways)
  var params = new URLSearchParams(window.location.search);
  var customerId = params.get("customer_id");
  var amount = params.get("amount");
  var invoiceId = params.get("invoice_id") || params.get("order_id");

  // Get click ID from GTM variable
  var clickId = {{Li2 Click ID}} || "";

  // Only track if we have required fields
  if (customerId && amount && clickId) {
    li2Analytics.trackSale({
      eventName: "Purchase",
      customerExternalId: customerId,
      amount: parseInt(amount), // Amount in cents (e.g., 4999 = $49.99)
      invoiceId: invoiceId || undefined,
      currency: "usd", // Change to "vnd" if needed
      paymentProcessor: "stripe", // Or "paypal", "paddle", etc.
      clickId: clickId
    });
  }
})();
</script>
Amount Format: Amount must be in smallest currency unit (cents for USD, đồng for VND):
  • ✅ CORRECT: amount: 4999 = $49.99
  • ❌ WRONG: amount: 49.99 = $0.49

Option 2: E-commerce Data Layer Tracking

When to use: Your site pushes e-commerce data to GTM’s data layer (common for Shopify, WooCommerce, Magento)
1

Create New Tag

TagsNew → Name: “Li2 - Track Sale - Data Layer”
2

Configure Tag Type

Select Custom HTML and paste the script below
3

Set Up Trigger

TriggeringNew Trigger:
  • Trigger Type: Custom Event
  • Event Name: purchase (or your e-commerce event name)
Script:
<script>
(function() {
  // Read from GTM data layer (pushed by your e-commerce platform)
  var ecommerce = {{Ecommerce}};
  var transaction = (ecommerce && ecommerce.purchase) ? ecommerce.purchase : {};
  var actionField = transaction.actionField || {};

  var customerId = actionField.customer_id || "";
  var revenue = actionField.revenue || 0;
  var amount = Math.round(parseFloat(revenue) * 100);
  var invoiceId = actionField.id || "";
  var currencyRaw = actionField.currency || "usd";
  var currency = currencyRaw.toLowerCase();

  // Get click ID from GTM variable
  var clickId = {{Li2 Click ID}} || "";

  // Only track if we have required fields
  if (customerId && amount > 0 && clickId) {
    li2Analytics.trackSale({
      eventName: "Purchase",
      customerExternalId: customerId,
      amount: amount,
      invoiceId: invoiceId || undefined,
      currency: currency,
      paymentProcessor: "stripe",
      clickId: clickId
    });
  }
})();
</script>
Data Layer Structure: The script above assumes standard Enhanced Ecommerce format. If your platform uses a different structure, adjust the object paths accordingly. Check GTM Preview mode to inspect your actual data layer structure.

Testing Your GTM Setup

Step 1: Use GTM Preview Mode

1

Enable Preview Mode

In GTM workspace, click Preview button (top right)
2

Connect to Website

Enter your website URL and click Connect. A new window opens with GTM debugger overlay
3

Test SDK Loader Tag

  1. Navigate through your site
  2. In GTM debugger, verify “Li2 Analytics - SDK Loader” fires on all pages
  3. Check Tags Fired section
4

Test Lead Tracking

  1. Navigate to form page or thank you page
  2. Verify lead tracking tag fires
  3. Check tag configuration and variable values in debugger
5

Test Sale Tracking

  1. Navigate to order confirmation page
  2. Verify sale tracking tag fires
  3. Confirm amount, customerId, and clickId are captured correctly

Step 2: Browser Console Verification

Open browser console (F12) and verify: 1. SDK Loaded:
li2Analytics
// Should return: {trackLead: ƒ, trackSale: ƒ, ...}
2. Click ID Cookie:
document.cookie.split(';').find(c => c.includes('li_cid'))
// Should return: " li_cid=cm3w..."
3. Manual Event Test:
li2Analytics.trackLead({
  eventName: "Test Lead",
  customerExternalId: "[email protected]",
  customerEmail: "[email protected]"
})
// Check Network tab for POST request to Li2 API

Step 3: Network Tab Verification

  1. Open DevToolsNetwork tab
  2. Filter by “track” or your API domain
  3. Trigger lead/sale events
  4. Look for POST requests to Li2 API endpoints
  5. Check request payload to ensure correct data is sent
Debug Mode: Add ?li2_debug=true to your URL to enable verbose logging in the console. This shows exactly what data Li2 SDK is capturing and sending.

Troubleshooting

Common causes:
  1. Trigger conditions don’t match: Check that page URL or form selector matches exactly
  2. Tag sequence issue: Ensure SDK loader tag fires before tracking tags
  3. Variable not returning value: Test {{Li2 Click ID}} in GTM Variables section
Fix:
  • Use GTM debugger to see why trigger didn’t match
  • Test trigger conditions manually (check actual URL, form ID in inspector)
  • Verify variable is configured correctly (cookie name = li_cid)
Cause: SDK loader tag hasn’t fired or script failed to loadFix:
  1. Check GTM Preview - did “Li2 Analytics - SDK Loader” fire?
  2. Check Network tab - is script loading from unpkg.com?
  3. Ad blocker blocking? Disable and test again
  4. Check browser console for JavaScript errors
  5. Verify publishable key is correct (no typos)
Cause: DOM selectors don’t match your actual form structureFix:
  1. Inspect your form HTML to find actual field IDs/classes
  2. Update selectors in the script:
    // ❌ If this doesn't match your HTML
    var emailField = document.getElementById("email");
    var email = emailField ? emailField.value : "";
    
    // ✅ Change to match your form
    var emailField = document.querySelector("input[name='user_email']");
    var email = emailField ? emailField.value : "";
    
  3. Test in browser console first to verify selector works
Cause: Amount not converted to centsFix:
// ❌ WRONG: Sending dollars
amount: 49.99  // → Treated as 49 cents = $0.49

// ✅ CORRECT: Multiply by 100 to convert to cents
amount: Math.round(49.99 * 100)  // → 4999 cents = $49.99
Cause: Tag firing multiple times due to incorrect trigger setupFix:
  1. Check GTM debugger - how many times did tag fire?
  2. Review trigger conditions - is it too broad?
  3. For form submissions: Enable “Wait for Tags” and set max wait time
  4. For page views: Ensure URL condition is specific enough
  5. Use invoiceId parameter to prevent duplicate sales (Li2 deduplicates within 7 days)
Cause: Current domain not in allowed hostnames listFix:
  1. Go to Li2 Settings → Analytics → Security
  2. Add your domain to Allowed Hostnames:
    • For exact match: example.com
    • For all subdomains: *.example.com
    • For development: localhost or 127.0.0.1
  3. Save and test again

Best Practices

1. Use GTM Folders: Organize all Li2 tags in a folder called “Li2 Analytics” for easy management2. Name tags consistently: Use prefix “Li2 -” for all tags so they’re easy to find3. Document your setup: Add notes in tag descriptions explaining what each tag does4. Test in Preview before publishing: Always use GTM Preview mode to verify tags work before publishing to production5. Use version control: GTM auto-saves versions - add descriptive version names when publishing6. Set up error alerts: Configure GTM to send notifications when tags fail to fire

Coming Soon

Shopify Integration

Native Shopify app for automatic conversion tracking

WooCommerce Plugin

WordPress plugin for WooCommerce stores

Zapier Integration

Connect Li2 to 5,000+ apps via Zapier

Segment Integration

Send conversion events through Segment CDP
Want early access? Contact us at [email protected] to join our beta program for upcoming integrations.

Next Steps