Integration through the Google Analytics API

  • Mise à jour

Integration

With integration through the Google Analytics API (GA API), advertisers gather data on actions completed on the site using their own Google Analytics counters. Then, Admitad Affiliate receives the order number and amount, and other information through a special API and uploads it into its own statistics.

Admitad_integration_through_GA_API_EN.png


Important:

  • When updating your site, make sure the Google Analytics counter hasn't been deleted and is still working.
  • If you have the mobile version of the site, the mobile app, or quick-order or one-click-order forms, they will also be integrated into Google Analytics.
     

To start working with Admitad Affiliate, provide a transition link to your site. By default, a link in the advertiser's brief is used as the main link.

There can be several links, but only one will be the program's main link (by default).

Example of a transition link
https://site.ru/?utm_source=admitad&utm_medium=cpa&utm_campaign={{publisher_id}}&utm_content={{admitad_uid}}

Once you've chosen integration through the GA API, we recommend using only standard UTM parameters: utm_source=admitad&utm_medium=cpa&utm_campaign={{publisher_id}}&utm_content={{admitad_uid}}

Affiliate links for publishers will be generated based on the transition link. Then publishers will place the affiliate links on their own ad spaces to attract traffic to your site.
 

Setting up integration through GA API

Important:

  • From here on out, the abbreviation GA API will be used instead of Google Analytics API.
  • We don't recommend using integration through the GA API, as Google's visit counter is liable to be blocked by adblockers and other extensions. If you can, use the standard method of integration through tracking codes. Admitad Affiliate does not provide technical support for GA API and does not bear responsibility for programs that have suffered because they use Google Analytics as a tool for gathering information about target actions.
  • These instructions describe the steps that need to be taken to gather information about Admitad Affiliate orders through the GA API. The instructions do not constitute the process itself but only serve to demonstrate it. All of the variables, macros, rules, and tags are for illustrative purposes only.
     

Integration steps

Grant the Admitad Affiliate service account access to Google Analytics:

  1. Go to your personal account in Google Analytics and click Admin in the lower left-hand corner.

    2019-10-07_11-02-55.png

     
  2. Then go to Custom Definitions → Custom Dimension.

    2019-10-07_11-06-44.png

     
  3. Click + New Custom Dimension to add the following parameters:
     
    • suid (Scope — Hit);
    • user_id (Scope — Hit);
    • hit_id (Scope — Hit);
    • session_id (Scope — Сеанс);
    • client_id (Scope — Сеанс);
    • action_code (Scope — Hit);
    • tariff_code (Scope — Hit).

      4_2020-10-14_12-27-11.png
       
  4. Then, go to Admin → Tracking info  → Tracking code.

    5_2020-10-14_12-29-11.png
     
  5. Copy your Tracking ID. You'll need to embed it into the code mentioned in the next step.

    6_2020-10-14_12-32-11.png
     
  6. Copy the code below and add it to all pages on your site except the Thank you page. In this code, you should transmit all the required parameter values.

    Note
    There are comments with hints in the code after "//". 

    Open the code
    <!-- Global site tag (gtag.js) - Google Analytics -->
    <script async src="https://www.googletagmanager.com/gtag/js?id=UA-XXXXXXXXX-X"></script> 
    // instead UA-XXXXXXXXX-X specify the tracking id of your GA
      
    <!-- Google Analytics custom dimensions for Admitad -->
      
    <script>
      function clientid() {
          var match = document.cookie.match('(?:^|;)\\s*_ga=([^;]*)');
          var raw = (match) ? decodeURIComponent(match[1]) : null;
          if (raw) {
              match = raw.match(/(\d+\.\d+)$/);
          }
          var gacid = (match) ? match[1] : null;
          if (gacid) {
              return gacid;
          }
      }
    
      function getTimeStamp() {
          var now = new Date();
          var tzo = -now.getTimezoneOffset();
          var dif = tzo >= 0 ? '+' : '-';
          var pad = function(num) {
              var norm = Math.abs(Math.floor(num));
              return (norm < 10 ? '0' : '') + norm;
          };
          return now.getFullYear() +
              '-' + pad(now.getMonth() + 1) +
              '-' + pad(now.getDate()) +
              'T' + pad(now.getHours()) +
              ':' + pad(now.getMinutes()) +
              ':' + pad(now.getSeconds()) +
              '.' + pad(now.getMilliseconds()) +
              dif + pad(tzo / 60) +
              ':' + pad(tzo % 60);
      }
    
      function getSessionId() {
          return new Date().getTime() +
              '.' + Math.random().toString(36).substring(5);
      }
    
      function uuidv4() {
        return ([1e7] + -1e3 + -4e3 + -8e3 + -1e11).replace(/[018]/g, function(c) {return (c ^ (window.crypto || window.msCrypto).getRandomValues(new Uint8Array(1))[0] & 15 >> c /   4).toString(16)});
      }
    
    
      function referrer() {
          if (document.referrer === "") {
              return "direct none"
          } else return document.referrer
      }
    
      window.dataLayer = window.dataLayer || [];
    
      function gtag() {
          dataLayer.push(arguments);
      }
      gtag('js', new Date());
    
      gtag('config', 'UA-XXXXXXXXX-X'); // instead UA-XXXXXXXXX-X here and in the next string specify the tracking id of your GA
      gtag('config', 'UA-XXXXXXXXX-X', {
          'custom_map': {
              'dimensionX': 'suid',
              'dimensionX': 'client_id',
              'dimensionX': 'user_id',
              'dimensionX': 'session_id',
              'dimensionX': 'hit_id'
          } // for dimensionX instead of Х insert indexes of the parameters you created at the step 3
      });
      gtag('event', 'apv', {
          'suid': uuidv4(),
          'client_id': clientid(),
          'user_id': 'user id in your system', // if the ID is unknown transmit an empty string. See more on the User ID set-up
          'session_id': getSessionId(),
          'hit_id': getTimeStamp(),
      });
    </script>
    
  7. Enable the Ecommerce Tracking in the GA interface if you haven't.

    Articles on how to set up Ecommerce Tracking:

     

    Setting up Ecommerce is mandatory. Integration is impossible without it.

  8. Copy the code below and embed it into the Thank you page.

    Note
    There are comments with hints in the code after "//". 
    Places, where you should transmit values of the required variables, are marked with {{ value }}.

    Open the code
    <!-- Global site tag (gtag.js) - Google Analytics -->
    <script async src="https://www.googletagmanager.com/gtag/js?id=UA-XXXXXXXXX-X"></script>
    // instead of UA-XXXXXXXXX-X specify the tracking id of your GA
    
    <!-- Google Analytics Ecommerce with custom dimensions for Admitad -->
    <script> 
    window.dataLayer = window.dataLayer || [];
    
    function gtag() {
        dataLayer.push(arguments);
    }
    gtag('js', new Date());
    
    gtag('config', 'UA-XXXXXXXXX-X'); // instead of UA-XXXXXXXXX-X here and in the next string, specify the tracking id of your GA
    gtag('config', 'UA-XXXXXXXXX-X', {
        'custom_map': {
            'dimensionX': 'suid',
            'dimensionX': 'client_id',
            'dimensionX': 'user_id',
            'dimensionX': 'hit_id',
            'dimensionX': 'action_code',
            'dimensionX': 'tariff_code'
        } // for dimensionX, instead of Х insert indexes of the parameters you created in step 3
    
    });
    
    ga_items = [];
    
    var list_position = 1; 
    
    // this fragment should be repeated for each item in the chart
    ga_items.push({
        "id": "{{ item.product_id }}",
        "name": "{{ item.product_title }}",
        "quantity": "{{ item.quantity }}",
        "price": "{{ item.price }}",
        "category": "{{ item.product_type }}",
        "list_position": list_position,
        "variant": "{{ item.variant }}",
        "brand": "{{ item.brand }}",
    });
    list_position = list_position + 1; 
    // end of the repeated fragment
    
    function getTimeStamp() {
        var now = new Date();
        var tzo = -now.getTimezoneOffset();
        var dif = tzo >= 0 ? '+' : '-';
        var pad = function(num) {
            var norm = Math.abs(Math.floor(num));
            return (norm < 10 ? '0' : '') + norm;
        };
        return now.getFullYear() + '-' + pad(now.getMonth() + 1) + '-' + pad(now.getDate()) + 'T' + pad(now.getHours()) + ':' + pad(now.getMinutes()) + ':' + pad(now.getSeconds()) + '.' + pad(now.getMilliseconds()) + dif + pad(tzo / 60) + ':' + pad(tzo % 60);
    }
    
    function clientid() {
        var match = document.cookie.match('(?:^|;)\\s*_ga=([^;]*)');
        var raw = (match) ? decodeURIComponent(match[1]) : null;
        if (raw) {
            match = raw.match(/(\d+.\d+)$/);
        }
        var gacid = (match) ? match[1] : null;
        if (gacid) {
            return gacid;
        }
    }
    
    function getSessionId() {
        return new Date().getTime() +
            '.' + Math.random().toString(36).substring(5);
    }
    
    function uuidv4() {
        return ([1e7] + -1e3 + -4e3 + -8e3 + -1e11).replace(/[018]/g, function(c) {return (c ^ (window.crypto || window.msCrypto).getRandomValues(new Uint8Array(1))[0] & 15 >> c /   4).toString(16)});
      }
    
    gtag('event', 'purchase', {
        "transaction_id": "{{ order_number }}",
        "affiliation": "",
        "currency": "{{ shop.currency }}",
        "shipping": "{{ shipping_price }}",
        "items": ga_items,
        "action_code": "{{ action_code }}", // transmit values specified during the integration
        "tariff_code": "{{ tariff_code }}", // transmit values specified during the integration
        "suid": uuidv4(),
        "client_id": clientid(),
        "user_id": "id пользователя в вашей системе", // if the ID is unknown transmit an empty string. See more on the User ID set-up
        "session_id": getSessionId(),
        "hit_id": getTimeStamp(),
    });
    </script>
  9. Return to the Admin section, in the View section, select the site with statistics on sales, and click View Settings.

    7_2020-10-14_22-34-42.png
     
  10. Send the View ID to the Admitad Affiliate specialist.

    8_2020-10-14_22-37-43.png
     
  11. Return to the Admin section. If you have several sites in the View column, select the site with required statistics on the drop-down list and click View User Management.

    9_2020-10-14_22-38-58.png
     
  12. In the upper right-hand corner click RU_Admitad_integration_through_GA_API-13.png , then, Add users.

    2019-10-07_11-39-00.png
     
  13. Insert the service email you've received in the integration follow-up letter. Grant Read & Analyze permissions.

    2019-10-07_11-40-29.png
     
  14. Inform the Admitad specialist that you've set up custom dimensions.
    After that, Admitad tech specialists will prepare the handler for collecting orders.

    The following values will be used:

    dimensions:

    • ga:transactionId — order ID
    • ga:productSku — item SKU (can be used to determine the rate)
    • ga:adContent —  utm_content tag contents (used for storing the service value admitad_uid)
    • ga:dateHourMinute — date and time of the order
    • ga:currencyCode — currency code
       

    metrics:

    • ga:itemRevenue — order amount
    • ga:couponCode — promo code
       

     

Deduplication of orders

In this integration method, the deduplication of orders is enabled by default and is based on the last paid source in the value utm_source. If the value is "admitad," we consider the order to be ours.

The function "Unique promo code" is an exception (approval is required to enable it).
 

Setting up unique promo code transfers

A unique promo code is a promo code connected to a specific publisher. Details can be found here. If you intend to work with unique promo codes:

  1. Make sure the field Promo code is present in the order completion form on the website.
  2. Make sure that Enhanced Ecommerce tag transfers are enabled and set up in Google Analytics.
  3. Transfer the unique promo code from the order completion code to the coupon parameter in GA.
    Examples: analytics.js / gtag.js

When an order comes through with a coupon value that matches the unique promo code created in the system, the order will be attributed to the publisher associated with that promo code.
 

Transferring information about orders in Google Analytics

The order might not be recorded in Google Analytics if the tool was blocked by an adblocker in the user's browser (or due to some other issue with the Google Analytics script). In order for the target action that slipped through to be correctly added to Admitad's statistics, transfer information about it from your database to Google Analytics. The Google Measurement Protocol is used to do so.

Admitad_integration_through_GA_API_2_EN.png

For the back-up transfer of information about orders to work, you need to:

  1. Extract UTM parameters when a user visits the website.
  2. Add the UTM parameter to the database together with information about the order.
  3. Transfer information about the order from the database to Google Analytics using the Google Measurement Protocol.
     

Extracting UTM parameters

Parameters need to be extracted so that information about the publisher and transition source can be transferred — this ensures that it will comply with the Last Paid Click attribution.

Example of code for extracting UTM parameters from cookies
<?php

$cookie_name = 'utm_cookie';
$expires_days = 90;

foreach ($_GET as $param_name => $param_value) {
    if (substr($param_name, 0, 4) === 'utm_') {
        $cookie_string = $cookie_string . $param_name . '=' . $param_value . ';';
    }
}

if (isset($cookie_string)) {
    setcookie($cookie_name, $cookie_string, time() + $expires_days * 24 * 60 * 60, '/');
}
?>


The script should extract the UTM parameters and rewrite them if new ones come.
 

Transferring UTM parameters and order information

The transfer of order information to the database is set up on an individual basis for each advertiser. It is important to send the UTM parameters from utm_cookie together with the order information. Check with your web developer to make sure these parameters are going through and, if not, enable this transfer.
 

Transfer of order information through the Google Measurement Protocol

Set up the transfer of information through the Google Measurement Protocol using the process described in Google documentation.

Example of code for sending information about a target action through the Google Measurement Protocol
<script>
function send(method, url, data, callback) {

    let xhr = window.XMLHttpRequest ? new XMLHttpRequest() : new ActiveXObject("Microsoft.XMLHTTP");

    xhr.onreadystatechange = function () {
        if (xhr.readyState === xhr.DONE && xhr.status === 200) {
            if (callback && typeof callback === 'function') {
                callback(xhr.responseText);
            }
        }
    };

    xhr.open(method, url);
    xhr.send(data);
}

function getProductKey(lp, key) {
    return 'pr' + lp + key;
}

let url = 'https://www.google-analytics.com/collect';
let paramsList = [];
let payload;

let lp = 1;

let item_price;
{% for item in checkout.line_items %}
item_price = '' + {{ item.final_price }};
item_price = insert(item_price, item_price.length - 2, '.');

/*
ga measurement protocol params
https://developers.google.com/analytics/devguides/collection/protocol/v1/parameters
*/
params = {
    'v': 1,
    'tid': 'UA-{{ adv_GA_id }}-1',     // Your GA id
    'cid': ([1e7] + -1e3 + -4e3 + -8e3 + -1e11).replace(/[018]/g, function(c) {return (c ^ (window.crypto || window.msCrypto).getRandomValues(new Uint8Array(1))[0] & 15 >> c / 4).toString(16)}),
    't': 'pageview',
    'pa': 'purchase',            // event type
    'dh': document.location.hostname,
    'dp': document.location.pathname,
    'dt': document.title,
    'z': '' + Date.now(),
}

/* purchase fields
{
  "transaction_id": '{{ order_number }}',
  "affiliation": "{{ utm_source }}",
  "currency": "{{ shop.currency }}",
  "action_code": ""
}
*/

params['ti'] = '{{ order_number }}';
params['ta'] = "";
params['cu'] = "{{ shop.currency }}";
params['cd1'] = "";

/* product fields
{
    "id": {{ item.product_id }},
    "name": "{{ item.product.title }}",
    "quantity": {{ item.quantity }},
    "price": '' + item_price,
    "category": "{{ item.product.type }}",
    "list_position": list_position,
    "variant": "{{ item.product.selected_variant.title }}",
    "brand": "{{ item.product.vendor }}"
}
*/

params[getProductKey(lp, 'id')] =  {{ item.product_id }};
params[getProductKey(lp, 'nm')] =  "{{ item.product.title }}";
params[getProductKey(lp, 'qt')] = {{ item.quantity }};
params[getProductKey(lp, 'pr')] = '' + item_price;
params[getProductKey(lp, 'ca')] = "{{ item.product.type }}";
params[getProductKey(lp, 'ps')] = lp;
params[getProductKey(lp, 'va')] = "{{ item.product.selected_variant.title }}";
params[getProductKey(lp, 'br')] = "{{ item.product.vendor }}";

paramsList = [];
for (let p in params) {
    paramsList.push(encodeURIComponent(p.toString()) + "=" + encodeURIComponent(params[p].toString()));
}

payload = paramsList.join("&");
send('POST', url, payload);

lp = lp + 1;
{% endfor %}
</script>

Cet article vous a-t-il été utile ?