• Courses
    • Courses
    • Course bundles
  • Blog
  • Services
  • Resources
    • Youtube channel
    • E-books and Guides
    • GTM Recipes
    • View All Resources
    • GTM Community
    • GA4 community
  • About
    • About
    • Contact
  • Login
  • Courses
    • Courses
    • Course bundles
  • Blog
  • Services
  • Resources
    • Youtube channel
    • E-books and Guides
    • GTM Recipes
    • View All Resources
    • GTM Community
    • GA4 community
  • About
    • About
    • Contact
  • Login

April 18, 2018

Track Affiliate Sales with Google Tag Manager and Google Analytics

In one of my previous blog posts, I’ve shared an idea how to track affiliate link clicks with Google Tag Manager. But that guide is useful if YOU, as an affiliate, promote someone else’s products and just want to track all the outbound affiliate link clicks.

But what if you’re the owner of the affiliate program and you want to measure which partners are driving the most sales of YOUR product?

In this guide, I’ll show how to track affiliate sales with Google Tag Manager and Google Analytics.

Here’s how a typical affiliate (a.k.a. referral) program works: a partner/affiliate promotes a link to your website/product, and that link contains partner’s ID, e.g. https://www.mybusiness.com/?affiliate_id=12345abc. Whenever someone lands on a page with that URL and makes a purchase, the partner receives a commision.

Usually, when a partner’s referred visitor lands, a cookie with that affiliate ID is stored on the visitor’s browser. Thanks to it, a sale can be attributed to the correct affiliate.

There are three main ways how this tracking can be implemented:

  • Everything is done by the developer. When the URL of the landing page contains an affiliate_id parameter, then the cookie (with that affiliate ID) is stored in the browser. If a visitor completes a purchase and has an affiliate cookie, the value of the cookie is fetched and stored in the database. At the end of a month (or a quarter), you (or your developer) checks and calculates how much each affiliate earned.
  • Using a ready-made 3rd party solution which needs to be integrated with your website/online store.
  • The tracking is implemented via GTM with Google Analytics. When a URL contains affiliate_id, a cookie will be stored with GTM (which contains that affiliate ID) and custom dimension (session scope) will be passed to Google Analytics. When a visitor completes a purchase, it will be attributed to that affiliate_id. Later, and in GA reports you will be able to see which affiliates contributed to your sales the most.

Before we continue, keep in mind that the first two solutions are more robust and will not be blocked by particular extensions (most probably), while, on the other hand, Google Tag Manager and Google Analytics might be blocked by extensions, such as Ghostery. Anyway, if you’re not ready to invest a lot (for now), continue reading this guide and you’ll learn something new.

This guide is pretty long, so feel free to bookmark it for the future.

 

 

#1. The plan

Here’s what we’re going to do in order to track affiliate sales with Google Tag Manager and Google Analytics:

  1. We’ll check the URL of every page and if at any moment it contains an affiliate ID, we’ll fetch it and store in the cookie.
  2. After that, we’ll push cookie’s value to Google Analytics as a session scoped Custom Dimension.
  3. Track a successful purchase. If affiliate ID was set during that session, it will be linked to that purchase.
  4. See how the affiliate ID is displayed in the custom report within Google Analytics.

 

#2. Getting Things Done

First, you need to decide what kind of query parameter will you be using to differentiate affiliate traffic. In this example, I’llbe using affiliate_id and the sample URL will look like this https://mywebsite.com/?affiliate_id=12345abc.

In order to store the value 12345abc in a cookie, we’ll need to complete 3 steps within GTM:

  • A URL variable which fetches the value of an affiliate_id;
  • A Custom HTML tag which stores that value in a cookie;
  • A trigger which fires that tag.

 

#2.1. URL variable

If you’re new to URL variable, read this guide where I explain ins and outs of parsing URLs (in plain English). In Google Tag Manager, go to Variables > User Defined Variables and create a new variable with the following settings:

url - affiliate id

If the URL that the visitor is currently on contains a parameter affiliate_id, this variable will return its value.

 

#2.2. Custom HTML Tag that sets the cookie

If you haven’t yet, read this guide which explains the friendship of GTM and cookies more in-depth.

<script>
 var cookieName = "affiliate_id"; 
 var cookieValue = "{{URL - affiliate_id}}"; // Insert the afforementioned URL variable surrounded by curly braces
 var expirationTime = 2592000; // One month in seconds. Feel free to change the time
 expirationTime = expirationTime * 1000;
 var date = new Date(); 
 var dateTimeNow = date.getTime(); 

 date.setTime(dateTimeNow + expirationTime);
 var expirationTime = date.toUTCString();
 document.cookie = cookieName+"="+cookieValue+"; expires="+expirationTime+"; path=/; domain=." + location.hostname.replace(/^www\./i, ""); // Sets cookie for all subdomains
</script>

Cookie’s name will be affiliate_id ((line 2) and its value will be inserted with help of the URL – affiliate_id variable (line 3).

Important: this tag must be fired before the Google Analytics Pageview tag so make sure that you set a higher Tag firing priority value in the Custom HTML tag.

Tag Firing Priority in Custom HTML tag

 

#2.3. Trigger

Now, we do not want to have false positives and fire a cookie-setting tag even if there is no affiliate ID present in the URL, therefore a particular trigger is needed. In GTM, go to Triggers > New and create a Pageview-type trigger with the following rule:

Pageview - Affiliate ID

The condition of this trigger is: URL – affiliate_id variable does not match RegEx (ignore case) ^(undefined|null|0|false|NaN|)$ 

This means that if an affiliate_id parameter exists in the URL, this trigger will be activated.

Link this trigger to the Custom HTML tag which creates a cookie.

Google Tag Manager Ebook Bundle

#2.4. Test the cookie

Enable GTM Preview and Debug mode. Open any page of a website you’re currently working on, add the following query parameter to the URL: ?affiliate_id=12345abc, and hit ENTER. The page will refresh and a custom HTML tag will fire (you can check that in the Preview and Debug console).

Now, let’s check whether a cookie is set correctly. There are two main ways to check cookies – browser’s built-in feature (developer tools) or a plugin.

Personally, I am using Chrome plugin called EditThisCookie (also available for Opera users). This really simple and intuitive extension enables me to quickly check which cookies are currently in use, what data do they contain, when do they expire, etc.

If you haven’t already installed, download it here. If you’re using a different browser, here are some similar plugins:

  • Firefox – Cookies Manager+
  • For Internet Explorer users, it’s recommended to use built-in features of developer tools.

Anyway, let’s get back to EditThisCookie. Once you have installed this extension, a cookie icon will appear next to the Menu icon (in Chrome).

EditThisCookie icon

Go to the website you’re currently working on, click EditThisCookie icon and you’ll see an expanded list of all cookies that are currently in use on that website. Look for a cookie named affiliate_id. This little piece of data will help us do some magic.

affiliate id cookie

 

#3. Create a custom dimension in Google Analytics

In order to track affiliate sales with Google Tag Manager and GA, we need to create a custom dimension Affiliate ID which will be later linked to a visitor session. Log in to your Google Analytics account, go to the Admin section, and in the Property level go to Custom Definitions > Custom Dimensions.

Custom Dimensions

Once you see a list with a large red button NEW CUSTOM DIMENSION, click it and create the following dimension:

Custom Dimension - Affiliate ID

Hit Create button and you’ll see a page with some codes. Memorize the number next to the “dimension”. In the screenshot below, that number is 1.

dimension 1 in Google Analytics

 

#4. Let’s read a cookie

GTM has a pretty easy feature which enables you to read cookies, 1st-party cookie variable. In order to make it work, all you have to do is set cookie’s name, like this:

cookie variable - affiliate id

 

#5. Update Google Analytics Settings Variable

If you still haven’t started using Google Analytics Settings Variable, you should. It’s a real time-saver. Instead of having to modify multiple tags, you just can edit one GA variable which is used in all GA tags.

In your GTM container, locate Google Analytics Settings Variable and edit it. What we’ll do here is add the custom dimension we’ve created a couple of chapters ago. If the affiliate_id cookie contains any value, it will be passed to Google Analytics. If it’s undefined, Google will handle that and automatically skip such values, so no additional configuration is needed.

Remember how I told you to memorize the number of the dimension in the chapter #3 of this guide? Time to shine. Enter that number in the Index field of GA Settings Variable.

GA Settings Variable

 

#6. Checkpoint

Let’s do a quick summary of what we’ve done so far in order to track affiliate sales with Google Tag Manager and GA:

  • First, we created a URL variable affiliate_id which fetches the value of the URL query parameter with a similar name (for those who don’t know, query parameters can be spotted in the web address after the question mark, e.g. https://www.mywebsite.com/?affiliate_id=12345abc).
  • Then we took the value of URL variable and stored it in the cookie, thanks to a Custom HTML tag.
  • In order to read the value of that cookie, we created a 1st-party cookie variable. It’ll be needed in the next bullet point.
  • In Google Analytics, we created a Custom Dimension Affiliate ID and entered its index in the Google Analytics Settings Variable. Also, inserted the aforementioned 1st-party cookie there.

 

 

To sum up, when a visitor lands on a page of your website and the URL contains affiliate_id, GTM will fetch its value and store it in the cookie. Immediately after that, the value of that cookie is inserted in the GA Settings Variable as a custom dimension, so when a visitor will complete a purchase during that session, it will be attributed to the particular affiliate partner.

If a visitor leaves the site without a purchase and returns later (say, after a day) with the same device and browser, a cookie will still be active, therefore its value will be pushed to GA Settings Variable again, therefore Google Analytics sessions will get the Affiliate ID once again.

 

#7. Sales Tracking: General Stuff

When someone is talking about sales tracking in Google Analytics, they have Ecommerce reports in mind. There are two options how you can implement them:

  • With Standard Ecommerce reports
  • Or Enhanced Ecommerce reports

If you want to track just sales, products purchased, and all other data that is related to the final stage of purchase, then go with the Standard Ecommerce tracking (I’ll explain it a bit in this guide).

If you want to track the entire visitor’s journey toward the purchase, including stages like Added to cart, Initiated Checkout, etc., go with the Enhanced Ecommerce functionality. You can read more about the implementation here (prepare LOTS of coffee for this one).

Just remember, the more data you want to track, the more time you (or your developer) will have to invest. No wonder that the implementation of Enhanced Ecommerce is considered as one of the most difficult GA integrations.

Google Tag Manager Ebook Bundle

#8. Standard Ecommerce Tracking

Let’s assume that all we want to see is the Affiliate ID and how much orders did it generate for us. Standard Ecommerce tracking is perfect for this task.

In order to make this tracking work, we have to complete the following steps:

  1. Enable this feature in Google Analytics reports.
  2. Define the exact moment when the purchase is complete.
  3. Ask a developer to send the transaction data to the Data Layer.
  4. We’ll create a Google Analytics Transaction tag which fetches the information from the Data Layer and sends it to Google’s servers.

 

#8.1. Enable Ecommerce Reports in GA

I won’t go much into details. Just follow this guide.

 

#8.2. Define the moment of a purchase

By saying “we need to define the moment of a purchase”, I mean that we need to create a trigger. Usually, after the order is complete, a customer is redirected to a Thank you page. In such case, a trigger should be of Page view type when URL contains /thank-you, /order-successful, or something similar. Read more about Thank you page tracking here.

If the page does not reload when the order is successfully completed, you should either try tracking an AJAX form or ask a developer to send a custom event to the Data Layer (with dataLayer.push) with purchase data (the latter option is recommended). You can read more about the Data Layer here and here.

#8.3. chapter of this guide is dedicated for those, who chose to go with developer’s help and dataLayer.push.

 

#8.3. Purchase data must be sent to the data layer

When the purchase data (order ID, total amount, etc.) is sent to the Data Layer, it is very important that the data structure is exactly as it is required by Google’s documentation. Names of all parameters must be exactly as Google requires it (e.g. transactionId cannot be renamed to orderID, etc.).

Here’s a sample code snippet taken from those docs:

<script>
window.dataLayer = window.dataLayer || [];
dataLayer.push({
 'event' : 'purchase',
 'transactionId': '1234', // the id 1234 should be dynamically replaced by the developer with actual order ID.
 'transactionAffiliation': 'Acme Clothing', //this should be replaced by the developer. The same applies to all other fields
 'transactionTotal': 38.26,
 'transactionTax': 1.29,
 'transactionShipping': 5,
 'transactionProducts': [{
   'sku': 'DD44',
   'name': 'T-Shirt',
   'category': 'Apparel',
   'price': 11.99,
   'quantity': 1
 },{
   'sku': 'AA1243544',
   'name': 'Socks',
   'category': 'Apparel',
   'price': 9.99,
   'quantity': 2
 }]
});
</script>

Your developer needs to push this code whenever a purchase is completed successfully. Of course, values (in your case) will be different, depending on the actual order, products, their price, etc.

If you’re thoroughly comparing the code above with Google’s documentation, you might have noticed one discrepancy, this line:

'event' : 'purchase',

I’ve added it intentionally. It will not break the implementation and, in addition to that, you’ll be able to create a trigger called “purchase” which will be used to fire our GA Transaction tag.

One more thing regarding that dataLayer.push with purchase information: not all fields are required. You can find a full list of requirements of Standard Ecommerce fields here. The smallest possible code snippet looks like this:

<script>
window.dataLayer = window.dataLayer || [];
dataLayer.push({
 'event' : 'purchase',
 'transactionId': '1234', // the id 1234 should be dynamically replaced by the developer with actual order ID.
 'transactionTotal': 38.26 // developer should also replace this price with the actual order total
});
</script>

What we’ve done so far is we “asked” a developer to push transaction data to the Data Layer when the order is actually completed.

Additionally, with that data, we’ll get a Data Layer event called “purchase” which will be used as a trigger to fire GA Transaction tag. I’ll explain that in the next chapter.

The best way to test if a developer has done everything correctly is to enable GTM Preview and Debug mode and complete a purchase. If everything was done properly by the developer, a purchase event should have appeared in the event stream.

purchase event in preview and debug mode

Click it and go to the Data Layer tab. With that event, a developer must pass the transaction data which should look like this:

purchase event in data layer

If the event did not appear, double check with developer whether he published the code to the public version of the website/online store.

 

#8.4. Trigger + Google Analytics Transaction Tag

A tag in Google Tag Manager fires only when a certain trigger is activated. And the best moment to fire transaction tag is to use the aforementioned purchase event. In order to do so, we’ll need to create a trigger of Custom Event type.

To to GTM > Triggers > New and choose type Custom. Enter the following settings:

Custom trigger - purchase

Keep in mind that event name is case-sensitive. If a developer pushed Purchase event to the Data Layer, then enter the same title (with uppercase P) in trigger’s settings, Purchase.

Now, let’s create a Google Analytics Transaction tag. Go to Tags > New > Universal Analytics and enter the following settings:

GA Transaction tag

When GA Tag’s tracking type is Transaction, it automatically checks the Data Layer and is looking for data, such as transactionId, transactionTotal, etc. That’s why a developer had to push the transcation data exactly as Google’s documentation required.

 

#8.4. Testing

Unfortunately, Google Analytics Real-time reports cannot help you debug Ecommerce tracking. But that’s not the end of the world as there are other options.

  1. Install GA debugger browser extension;
  2. Click its icon (it will start displaying ON);
  3. Go the page where you want to test Ecommerce tracking;
  4. Open browser’s JavaScript console. If you’re new to it, follow this tutorial;
  5. Refresh browser’s tab and complete a new purchase once again.

Once you complete these step the following data will be printed in the console (P.S. values might (and probably will) be different):

GA Debugger - Standard Ecommerce

If you also sent some product data, you’ll see even more lines in the console. I’ve marked the most important fields with blue rectangle:

  • hitType: the type of GA Tag
  • dimension1: that’s our Affiliate ID
  • ec:id: transaction ID
  • ec:revenue: transaction total
  • ec:tax: transaction tax.

 

#9. Building an affiliate Sales report in Google Analytics

The final step of affiliate sales tracking with Google Tag Manager is building a report. In Google Analytics, go to Customization > Custom Reports.

Custom reports in GA

Click NEW CUSTOM REPORT and choose the following metrics + dimension.

Custom Affiliate Report in GA

Click Save. In the report, you’ll be able to see which affiliates are driving the most sales and revenue.

Affiliate reports

 

#10. An alternative way to send Affiliate ID

There’s also another way how can you send the affiliate ID. But I chose the longer method in order to demonstrate the power of mixing cookies, custom dimensions, standard ecommerce, and custom reports.

Let’s go back to the Standard Ecommerce dataLayer.push snippet:

<script>
window.dataLayer = window.dataLayer || [];
dataLayer.push({
 'event' : 'purchase',
 'transactionId': '1234', // the id 1234 should be dynamically replaced by the developer with actual order ID.
 'transactionAffiliation': 'Acme Clothing', //this should be replaced by the developer. The same applies to all other fields
 'transactionTotal': 38.26,
 'transactionTax': 1.29,
 'transactionShipping': 5,
 'transactionProducts': [{
   'sku': 'DD44',
   'name': 'T-Shirt',
   'category': 'Apparel',
   'price': 11.99,
   'quantity': 1
 },{
   'sku': 'AA1243544',
   'name': 'Socks',
   'category': 'Apparel',
   'price': 9.99,
   'quantity': 2
 }]
});
</script>

See the transactionAffiliation field? You could have asked a developer to read the affiliate_id cookie that you previously stored and place that ID in the transactionAffiliation field whenever a push to the Data Layer is initiated.

That field will be transferred to Google Analytics and will become available in the Ecommerce reports. Sometimes businesses choose to pass a discount code or a store name in that field. If that’s the case, then the custom dimension is a way to go in order to pass the Affiliate ID.

 

Track Affiliate Sales with Google Tag Manager: final words

For me, this is an unexpectedly lengthy blog post. Originally, I was planning to publish totally another guide which would have also included the affiliate sales tracking with GTM, however, this chapter grew so big that it became a standalone blog post.

In this extended guide, I’ve shown you how to mix several tracking techniques into one solution:

  • When a visitor lands on a page and the URL contains an affiliate ID, that ID is fetched and stored in the cookie.
  • Value of that cookie is then fetched and passed to Google Analytics as a custom dimension (session scope). If the value of the dimension changes several times during a single session, the latest value will be applied.
  • Then, I’ve explained how to implement a Standard Ecommerce Tracking (Google Analytics) with help of developer and Data Layer.
  • When the purchase is successfully completed, a custom GTM trigger fires a Google Analytics Transaction.

So as long as a visitor has an affiliate cookie, its value is sent to Google Analytics, therefore you’ll be able to see which affiliates are driving the most sales. You can view that data with a simple custom report.

Got any ideas/suggestions regarding how to track affiliate sales with Google Tag Manager and Google Analytics? Let me know in the comments below.

Julius Fedorovicius
In Google Tag Manager Tips
55 COMMENTS
Zach Shearer
  • Apr 19 2018
  • Reply

Thanks for the great article! I was curious about you script to set the cookie. Forgive the lack of markup, I don't know how to make the code monospace in this chat window.

```
var expirationTime = 2592000; // One month in seconds. Feel free to change the time
expirationTime = expirationTime * 1000;
```

You originally set it for a month's time but then multiply it by 1000. Is this just you extending the time as you suggest is possible in your comment?

    Julius Fed
    • Apr 19 2018
    • Reply

    Hey, When you set time in JavaScript, you need to set it in milliseconds.
    That's why I multiplied it by 1000.

      Zach Shearer
      • Apr 19 2018
      • Reply

      Oh duh. Not sure why that escaped me. Thanks for the quick clarification!

Matthias Kupperschmidt
  • Apr 24 2018
  • Reply

Great article referencing a handful of different GTM techniques - definitely worth a bookmark! :-) - Also great you lined out that the URL parameter logic should preferably be coded into the site itself to enhance data quality. Even though we all love to set up complicated solutions with our GTM master sword, it may not always be the best solution for our client, hence good selfreflection there :)

    Julius Fed
    • Apr 24 2018
    • Reply

    Thanks!

    Yes, indeed, various extensions like Ghostery may break GTM tracking, therefore, an affiliate sale will be never tracked. Not a common situation, but totally possible. Therefore a more quality data would be without GTM.

    Therefore, as you said, we love playing with GTM. It's my LEGO :)

Arundhati Kher
  • Jun 10 2018
  • Reply

Hi Julius,

Below are my 3 funnels steps:
Funnel 1: https://www.example.com/package/city-name.aspx
Funnel 2: https://www.example.com/example-package.aspx
Funnel 3: https://report.example.com/download.aspx

I would like to know, if it is possible to track the page before the referrer, i.e. previous to previous(i.e. Funnel 1) in GTM event? My trigger is set to fire on last URL(i.e. Funnel 3).

Now, I can track only previous URL(i.e. Funnel 2) in GTM by using 'Referrer/Referrer Page URL' variable.

Note: Only first URL is changing for all the different city pages, second and third URL is common, hence I want to track first URL(i.e. Funnel 1) in GTM event to know all the download actions done by users from which locations.

Could you provide any tips?

Thank you for your efforts and help!
Arundhati

    Julius Fed (Fedorovicius)
    • Jun 15 2018
    • Reply

    Sorry, no ready-made solution that I can think of. Probably you should consider storing that 2nd previous page in the cookie but that requires JavaScript knowledge.

Joost
  • Jul 19 2018
  • Reply

Nice post! Two questions:
1. Would it give any advantage to replace https://mywebsite.com/?affiliate_id=12345abc with an UTM i.e. with https://mywebsite.com/utm_medium=referral&utm_source=promo&utm_campaign=campaign2018. Would it still work?
2. Can you send this to mutiple GA-accounts so the affiliate can als keep a track of the conversion

Thank you in advance!
Joost

    Julius Fedorovicius
    • Jul 20 2018
    • Reply

    1. I'd actually use both. Affiliate_id is needed for conversion tracking while UTM data is useful in acquisition reports.
    2. I wouldn't send this to a separate GA property. Instead, I'd use UTMs as you have mentioned before and then create a separate GA for that affiliate. You can create views based on UTMs and even custom dimensions.

      Joost
      • Jul 20 2018
      • Reply

      Thanks! Blog

      Ad1. How do you combine an UTM with an Affiliate ID is the affiliate has one button with a link at the end of their Blog-post?

      Again, many thanks,

      Joost

        Julius Fedorovicius
        • Jul 22 2018
        • Reply

        If you really want to combine them, you can use utm_content for your affiliate ID.

mt
  • Aug 3 2018
  • Reply

How do you apply IP address deduplication to prevent click fraud against affiliate clicks using GTM + GA method?

Jacopo Orlando
  • Aug 20 2018
  • Reply

Great article, very useful. I have a question, why the affiliate tag has to fire before the GA pageview? Is it so important?

Thanks for your tips,

Jacopo

    Julius Fedorovicius
    • Aug 21 2018
    • Reply

    Hey, the faster you set the cookie, the faster its value will be inserted in the GA settings variable.

Visible One
  • Aug 21 2018
  • Reply

Great article!

Just a question though,
1. In GA custom reports, no data is showing even if i set the metric with Pageviews.

The cookie is working and followed all the steps in GTM but data is not showing in GA report.
The container in GTM is also Live (not in preview mode)

    Julius Fedorovicius
    • Aug 24 2018
    • Reply

    Hey, do you see that data at all? at least in the default reports.

      Visible One
      • Aug 28 2018
      • Reply

      Yes. We can see the data. but on custom reports, it is not showing

        Julius Fedorovicius
        • Aug 28 2018
        • Reply

        Sounds like an issue with custom dimension scopes. Are you sure you set the custom dimension to "session" scope?

Vinnie
  • Sep 13 2018
  • Reply

Thank you for the article! I noticed in #2.3 that the "does not match RegEx (ignore case)" condition appears to be case sensitive. Is that expected? Also in Chrome, the cookie is given an "undefined" value, which sounds like a browser specific issue. Any ideas on how to pass no value there?

    Julius Fedorovicius
    • Sep 14 2018
    • Reply

    Hey, that option is definitely not case sensitive :) Maybe you accidentally chose a regular "Regex" option (without "ignore case")?

    Cookie variable will return undefined until such cookie exists in the browser.

    What do you mean by saying "pass not value there"?

David Charitos
  • Sep 19 2018
  • Reply

Hi Julius,

Great Article!

Would you consider setting this up for me? My site is on WIX and i'm looking for a cost effective affiliate tracking solution.

Email me with costs/questions if this is something you would consider.

Thanks

David

    Julius Fedorovicius
    • Sep 21 2018
    • Reply

    Sure. Sent you an email.

      Leah W.
      • Sep 1 2019
      • Reply

      Would you mind helping me out with this as well?

      I have done everything except for the datalayer step as I dont have a developer and that is a little above my range of knowledge! My hosting site is SquareSpace.

      Let me know if you would be interested!

Deniz
  • Sep 30 2018
  • Reply

Hi Julius,

What a great article. Really great stuff.

Quick question. I get the following error message when I want to publish my workspace:

Unsupported reference to the variable, '{{ }}', in a comment.

I followed all the aforementioned steps (changing affiliate_id to a specific affiliate id)

- I set up an url variable called "shopback_id"
- I inserted the url variable into the HTML tag

Here the code:

var cookieName = "shopback_id";
var cookieValue = "{{shopback_id}}"; // Insert the afforementioned URL variable surrounded by {{ }}

    Deniz
    • Sep 30 2018
    • Reply

    Okay for all those who faced a similar issue here is what I found out: The error message came up because I did not delete the comment within the code:
    "// Insert the afforementioned URL variable surrounded by {{ }}"

    Apparently, Google Tag Manager made a reference to that empty variable ({{ }})

    Thanks again Julius for a great article :)

      Julius Fedorovicius
      • Sep 30 2018
      • Reply

      Yes, you are correct.

      If you surround something with {{ }}, GTM will be looking for the actual variable. It that variable does not exist, you won't be able to preview/publish container.

      Julius Fedorovicius
      • Oct 6 2018
      • Reply

      Sorry for late reply, Deniz. And thanks for the heads up!

Victor Vazquez
  • Oct 30 2018
  • Reply

Excelent post! I tried it and now i'm waiting for some results. Hope it will work.

Best regards!

Luis Miguel
  • Nov 6 2018
  • Reply

You are amazing. Thank you very much for share in that way that information.

I would like to know if its possible to send a second custom dimension by the cookie with GTM, or if it is recommended to do it within a second cookie. In any case, could I perform a custom report which combines the two dimensions?

    Julius Fedorovicius
    • Nov 11 2018
    • Reply

    Yes, you can send a second custom dimension too. You can do it both with a second cookie or parse the same cookie. If you're not very skilled with the GTM, creating a 2nd cookie for the 2nd custom dimension is easier.

Guilherme Takashi Yamamoto
  • Jan 23 2019
  • Reply

Is it possible to use custom dimension on product? lets say for brand of a given product? And if it is, Can I send in transactionProducts field for each product?

    Julius Fedorovicius
    • Jan 23 2019
    • Reply

    Yes, but only if you're using Enhanced Ecommerce tracking.

Kellyn
  • Feb 7 2019
  • Reply

Forgive me if this is basic - I'm really new to this - but how long will the cookie last? I'd like to be able to pass this info onto the affiliates...

Julius Fedorovicius
  • Feb 8 2019
  • Reply

In this blog post, cookie's duration is 30 days. But you can change its setting in the code (I've added a comment to the code where you can change it).

Every cookie can have a different lifespan depending what expiration date was set. It might be available from seconds till veeeeery long time.

    Kellyn
    • Feb 8 2019
    • Reply

    Great - thank you for the info!

Jesper
  • Feb 27 2019
  • Reply

Hi. Thanks for a nice post.

Is it possible to see the direct conversions in Analytics? What I means is without any other touchpoints/funnel. Only the direct conversions.

    Julius Fedorovicius
    • Mar 2 2019
    • Reply

    This still doesn't sound very clear. Could you elaborate?

    You can see how the (direct) traffic converts in your source/medium reports. I think I need more explanation about your situation to be able to help.

Jembatan Bahasa
  • Mar 13 2019
  • Reply

Hi Julius,
A complete beginner here. Where should I add the html tag? Should I copy it before the ? I am using WordPress. Thank you!

    Julius Fedorovicius
    • Mar 16 2019
    • Reply

    What html tag are you talking about?

Patrik
  • Mar 14 2019
  • Reply

Great post, just what I needed!

I do have a question since i can't seam to have any affiliate data pushed to GA.

Two things I can't control:
1. The GA script is loaded outside of GTM
2. Google Analytics Enhanced Ecommerce data is already pushed to GA via an event called "purchase". I can't control that data layer nor the naming of the properties in it. They are different from this post.

With that in mind I have set up this dataLayer:

<script>
window.dataLayer = window.dataLayer || [];
window.dataLayer.push({
'event' : 'amb-purchase',
'transactionId': '2356'
'transactionTotal': '123.56'
});
</script>

I was thinking that by doing it like this, this affiliate transaction will get associated with the sale registered by the built in GA ecommerce event (point 2 above) since it is the same transaction ID.

Will that work?

    Julius Fedorovicius
    • Mar 16 2019
    • Reply

    If you send this transaction as an additional one, you'll end up with having two transactions in GA. If you want to track affiliate information, you should send it with the purchase as a custom dimension.

Adrian
  • Mar 21 2019
  • Reply

Hi, good article.
I have question:
How to get affilate from parters domain. (this tutorial works when everythink is done in one domain, but if affilate code is on domain2.pl/referer?pid=1 how to get "1" as variable?

Julius Fedorovicius
  • Mar 21 2019
  • Reply

Cookies cannot be shared between different domains.

In that case, you could do something like here https://www.analyticsmania.com/post/transfer-utm-parameters-google-tag-manager/

If a visitor lands on a page and contains the affiliate ID cookie, you could use the script that is provided in this guide https://www.analyticsmania.com/post/transfer-utm-parameters-google-tag-manager/ and decorate all links with an affiliate ID (instead of UTMs).

And then on the domain2.pl you should once again read the URL and store the affiliate ID in the cookie.

Adrian
  • Mar 22 2019
  • Reply

Thanks for very fast replay. Is it only way to do this, looks very complicated.
I try to describe it:

- Parters have landing pages where put links to from my affilate program (links looks like domain2.pl/refer.apx?pid=111?bid=211) where pid=111 is affilate number.

- I want to track "111" to the end of payment in my shop

Is it easiest way to do this?

Jack Trider
  • Apr 22 2019
  • Reply

Hey there,

Amazing article! I just have one question.

What if there's a zero in the revenue value of one of the affiliates? Why might cause that error? and how could I solve it?

Pukar Niraula
  • Jul 30 2019
  • Reply

Is it possible to track cpa campaigns (i am an affiliate) sell in adword using similar steps

James Costansin
  • Aug 23 2019
  • Reply

I have the same issue as the above commentator - I can see the event being sent via Tag Manager. Also, from the GA Debugger Debug extension, I can see dimension, id and revenue pushed to the data layer.

However the report looks empty. By any chance, is it real time or it should take some time?

    Julius Fedorovicius
    • Aug 23 2019
    • Reply

    The report is definitely not real-time. You need to wait up to 24 hours.

luqman m saad
  • Sep 11 2019
  • Reply

how can I put the cookie value in URL?

domain.com/{{affiliate_id}}

it work like this?

britt
  • Dec 8 2019
  • Reply

Thanks for all the detailed step, for this part do I need to add in my URL?

var cookieValue = "{{URL - affiliate_id}}"; // Insert the afforementioned URL variable surrounded by {{ }}

Everything is firing correctly but it just not tracking in analytics

Furkan
  • Apr 5 2020
  • Reply

Great post. Thx for sharing.

Do you think that i can apply this for my promo site?

Erwin
  • Apr 29 2020
  • Reply

Hi, thank you for this post. We have an ID to track subscribers that came from other organisations. These organisations use a link to our subscription form each with a unique id: "www.ourdomain.be/subscribe?recruiting_organisation_id=xxxx".

I would like to make a report where I can see the number of subscribers (goal completions) linked to the ID. So for example. Two new subscribers came from id value:xxx, and three new subscribers came from id value:yyy.

I have followed your instructions step by step, until you came to the e-commerce stuff. I'm not tracking sales, so I don't have e-commerce activated.

I tried to make a custom report with the newly created custom dimension (the recruiting id) and our goal completion (new subscribers). But the report stays empty.

Is there something I'm forgetting to do?

Regards,
Erwin

Paweł
  • May 31 2020
  • Reply

I have just read it. Nice!

McCall Bliss
  • Jun 11 2020
  • Reply

Hey thank you so much for this article! It was extremely helpful in getting my site setup with GTM and being able to pick up the affiliate_id from the query and set it as a cookie on my site. Unfortunately, however, I still can't get my affiliate id to link with the conversion when I'm looking at the tracking data / generating a report. I had to do a lot of customization since the site is based on Squarespace in order to get GTM working on the commerce page (https://forum.squarespace.com/topic/145832-squarespace-ecommerce-tracking-via-google-tag-manager/). Would love any help you can offer for making sure conversions are associated with the correct affiliate id.

eduardo cabrera
  • Nov 15 2021
  • Reply

Amazing as usual mate, your site is better that Google's to implement tags and track users.
I have a question now. I added the custom tag to track Affiliates, now the question is: besides adding the www.whatever.com/?affiliate_id=12345abc
can I add another segmentation like campaign? Medium? in the same URL?

Leave a comment Cancel reply

Your email address will not be published. Required fields are marked *

 

Hi, I'm Julius Fedorovicius and I'm here to help you learn Google Tag Manager and Google Analytics. Join thousands of other digital marketers and digital analysts in this exciting journey. Read more
Analytics Mania
  • Google Tag Manager Courses
  • Google Tag Manager Recipes
  • Google Tag Manager Resources
  • Google Tag Manager Community
  • Login to courses
Follow Analytics Mania
  • Subscribe to newsletter
Recent Posts
  • Google Analytics Client ID: What You Need to Know
  • Duplicate Events in Google Analytics 4 and How to Fix them
  • Track Videos with Google Analytics 4 and Google Tag Manager
Analytics Mania - Google Tag Manager and Google Analytics Blog | Privacy Policy
Manage Cookie Settings