# Analytics Integration

The plugin can inject custom JavaScript into the Global-e checkout overlay at two lifecycle points: when the checkout step **loads** and when the checkout **confirms** a successful order. Three analytics providers are supported out of the box: Google Analytics 4 (GA4), Facebook Pixel, and TikTok Pixel.

All analytics scripts are injected as inline `<script>` tags via `wp_add_inline_script()` on WooCommerce checkout pages only (when `is_checkout()` or `gcbwc_is_globale_international_checkout()` is true).

---

## The `OnCheckoutStepLoaded` event contract

Global-e's checkout overlay fires the `OnCheckoutStepLoaded` callback at two `StepId` values. All analytics are wired inside this single callback:

```javascript
var glegem = glegem || function() {
    (window['glegem'].q = window['glegem'].q || []).push(arguments)
};

glegem('OnCheckoutStepLoaded', function(data) {
    switch (data.StepId) {

        case data.Steps.LOADED:
            // GA4 checkout loaded snippet fires here
            break;

        case data.Steps.CONFIRMATION:
            if (data.IsSuccess && !data.IsPageReload) {
                // GA4 confirmation snippet fires here
                // Facebook Pixel snippet fires here
                // TikTok Pixel snippet fires here
            }
            break;
    }
});
```

`data.IsSuccess` guards confirmation events so duplicate page reloads (`data.IsPageReload`) do not re-fire purchase events.

The four configured snippets are inserted into the `%1$s`–`%4$s` placeholders using `sprintf()` in `GlobaleProIntegration::enqueueScriptsAndStyles()`. Empty strings are substituted for disabled providers.

---

## GA4 — checkout loaded

**Config keys:** `ENABLE_GA4_ON_CHECKOUT_LOADED`, `GA4_ON_CHECKOUT_LOADED`  
**Step:** `data.Steps.LOADED`

The default snippet sends a `begin_checkout` GA4 event with the full product array from `data.details.ProductInformation`:

```javascript
window.dataLayer = window.dataLayer || [];
function gtag() { dataLayer.push(arguments); }
gtag('js', new Date());
gtag('config', 'G-XXXXXXXXXXX', {'debug_mode': true});

var product_arr = [];
if (typeof data.details.ProductInformation !== 'undefined') {
    for (var i = 0; i < data.details.ProductInformation.length; i++) {
        product_arr[i] = {
            item_id:   data.details.ProductInformation[i].SKU,
            item_name: data.details.ProductInformation[i].ProductName,
            currency:  data.details.MerchantCurrencyCode,
            index:     i,
            price:     data.details.ProductInformation[i].ProductPrices
                           .CustomerTransactionInMerchantCurrency
                           .CustomerDiscountedPriceInMerchantCurrency,
            quantity:  data.details.ProductInformation[i].Quantity
        };
    }
}

gtag('event', 'begin_checkout', {
    value:    data.details.OrderPrices.CustomerTransactionInMerchantCurrency
                  .CustomerTotalPriceInMerchantCurrency,
    currency: data.details.MerchantCurrencyCode,
    items:    product_arr
});
```

Replace `G-XXXXXXXXXXX` with your GA4 measurement ID.

---

## GA4 — confirmation

**Config keys:** `ENABLE_GA4_ON_CHECKOUT_CONFIRMATION`, `GA4_ON_CHECKOUT_CONFIRMATION`  
**Step:** `data.Steps.CONFIRMATION` (guarded by `data.IsSuccess && !data.IsPageReload`)

The default snippet sends a `purchase` GA4 event:

```javascript
gtag('event', 'purchase', {
    transaction_id: data.details.OrderID,
    affiliation:    'Google Merchandise Store',
    value:          data.details.OrderPrices.CustomerTransactionInMerchantCurrency
                        .CustomerTotalPriceInMerchantCurrency,
    tax:            data.details.OrderPrices.CustomerTransactionInMerchantCurrency
                        .CustomerVATInMerchantCurrency,
    shipping:       data.details.OrderPrices.CustomerTransactionInMerchantCurrency
                        .CustomerShippingPriceInMerchantCurrency,
    currency:       data.details.MerchantCurrencyCode,
    items:          product_arr
});
```

---

## Facebook Pixel — confirmation

**Config keys:** `ENABLE_FACEBOOK_PIXEL_ON_CHECKOUT_CONFIRMATION`, `FACEBOOK_PIXEL_ON_CHECKOUT_CONFIRMATION`  
**Step:** `data.Steps.CONFIRMATION` (guarded by `data.IsSuccess && !data.IsPageReload`)

The default snippet sends a `Purchase` standard event:

```javascript
if (data.IsSuccess) {
    fbq('track', 'Purchase', {
        content_ids: data.details.ProductInformation.SKU,
        eventref:    'fb_oea',
        currency:    data.details.MerchantCurrencyCode,
        num_items:   data.details.ProductInformation.length,
        value:       data.details.OrderPrices.CustomerTransactionInMerchantCurrency
                         .CustomerTotalDiscountedProductsPriceInMerchantCurrency
    });
}
```

The Facebook Pixel base code (`fbq('init', '...')`) must be loaded separately on the page; this snippet only fires the event.

---

## TikTok Pixel — confirmation

**Config keys:** `ENABLE_TIKTOK_PIXEL_ON_CHECKOUT_CONFIRMATION`, `TIKTOK_PIXEL_ON_CHECKOUT_CONFIRMATION`  
**Step:** `data.Steps.CONFIRMATION` (guarded by `data.IsSuccess && !data.IsPageReload`)

The default snippet sends a `CompletePayment` event:

```javascript
if (data.IsSuccess) {
    ttq.track('CompletePayment', {
        content_id:   data.OrderId,
        content_type: '{}',
        quantity:     data.details.ProductInformation[i].Quantity, // sum all quantities
        value:        data.details.OrderPrices.CustomerTransactionInMerchantCurrency
                          .CustomerTotalPriceInMerchantCurrency,
        currency:     data.details.MerchantCurrencyCode,
    });
}
```

The TikTok Pixel base code (`ttq.load('...')`) must be loaded separately.

---

## Legacy checkout JS code field

`CHECKOUT_JS_CODE_ON_CHECKOUT_PAGE` (`checkout_js_code_on_checkout_page`) is an older textarea that injects JS on the checkout page. It wraps the same `OnCheckoutStepLoaded` callback pattern. Its enable toggle (`ENABLE_JS_CODE_ON_CHECKOUT_PAGE`) defaults to `yes` for backwards compatibility but is superseded by the Analytics section above. When the Analytics section is in use, the legacy field should be cleared or disabled to avoid duplicate event firing.

The default snippet included in `Config::getDefaultJsCodeOnCheckoutPage()` is a skeleton `console.log` handler with `TODO` comments — it does not fire any analytics events.

---

## Enabling / disabling analytics

All four analytics providers are disabled by default. To enable:

1. Go to **WooCommerce → Settings → Integrations → Global-e Cross-Border Integration**.
2. Scroll to the **Analytics** section.
3. Check the enable toggle for the desired provider.
4. Paste your custom snippet or edit the default one in the textarea.
5. Save settings.

Scripts are only loaded when `GlobalePro::isApplyGlobaleModifications()` is `true` — i.e. not on admin pages, not on 404s, not on `PURGE` requests, and not on Global-e API requests (except search result actions).
