Using a custom Google Analytics code with Buy Button

RTOP_Developer
Shopify Partner
13 0 2

Saw something similar here: https://ecommerce.shopify.com/c/ecommerce-marketing/t/buy-button-google-analytics-sales-tracking-327...

but the answer doesn't actually give any information.

My question is, can one add custom GA code to the checkout page that customers a directed to when you use the 'buy button' method of selling on shopify? The second link from the answer to the above question does contain some info about linking accounts cross-domain, but says nothing about getting the GA code into the shopify checkout page. What I'm looking for is something analagous to the 'Google Analytics' section of the Preferences tab on the 'Online Store' section of a shopify admin, but in the 'Buy Button' section instead.

Is it possible to get some custom GA code onto the buy button checkout page?

Replies 32 (32)
Josh_Uebergang
Shopify Expert
853 30 213

You can as normal (Google Analytics section of Shopify or even a GTM tag that triggers the event on a URL) just like if you weren't using the Buy Button. One problem you should be aware of is the Buy Button doesn't permit cross-domain tracking due to iframe issues not transferring cookies. 

Run Google Shopping ads? Get the free definitive guide to Google Shopping for Shopify (no optin required): https://www.digitaldarts.com.au/google-shopping
rd1
New Member
4 0 0

Awesome reply Joshua. Thanks!  A couple follow up questions:

1. So, if you use your GA code on shopify in the anatyics section, will it be used in the cart/ checkout pages? How does this look from an analytics point of view? Is it like the main store page is a referrer to the shopify cart?  What if you used the same GA code?

2. If someone bought something from a buy button and didn't interact with the site in any other way, would it be considered a bounce, since the button is part of an iframe?

Thanks!

RTOP_Developer
Shopify Partner
13 0 2

So the suggested answer isn't accurate because there isn't any Google Analytics section in the 'buy button' section of the admin (which was really my original question).

I did find a way to do it, however, using the 'Additional Scripts' section (Settings -> Checkout -> Order Processing -> Additional Scripts). This section lets you add any JS you want to run on the Thank You page. Due to cross-origin stuffs with sensitive data on the actual checkout page, you cannot put custom code there. BUT. Our saving grace is that the Shopify object is accessable from the thank you page, and it still has all of the cart data.

Thus, my solution:

 

<script>
    (function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){
            (i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),
        m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)
    })(window,document,'script','https://www.google-analytics.com/analytics.js','ga');

    // your GA code replaces 'UA-XXXXXXXX-X'
    ga('create', 'UA-XXXXXXXX-X', 'auto', {'allowLinker': true});
    ga('require', 'linker');
    // your domain replaces 'domain.com'
    ga('linker:autoLink', ['domain.com'] );
    ga('send', 'pageview');

    ga('require', 'ecommerce');

    var checkoutObj = window.Shopify.checkout,
        lineItems = checkoutObj.line_items

    if (checkoutObj)
        // I'm using the checkout object to pull order-wide data.
        // (you can find other available params in the Shopify JS API)
        ga('ecommerce:addTransaction', {
          'id': checkoutObj.order_id,
          'affiliation': '',
          'revenue': checkoutObj.subtotal_price,
          'shipping': checkoutObj.shipping_rate.price,
          'tax': checkoutObj.total_tax
        })

    if (lineItems)
      for (var i = 0; i < lineItems.length; i++){
          var line_item = lineItems[i]
          // and I'm using the lineItem objects to get individual item data
          // (you can find other available params in the Shopify JS API)
          ga('ecommerce:addItem', {
              'id': line_item.product_id,
              'name': line_item.title,
              'sku': line_item.sku,
              'category': '',
              'price': line_item.price,
              'quantity': line_item.quantity
          });
      }

    // ayy, send the data we we're trying to get!
    ga('ecommerce:send');
</script>

 

I'll answer these questions to the best of my knowledge:

"So, if you use your GA code on shopify in the anatyics section, will it be used in the cart/ checkout pages? "

No, the custom code you add to shopify will only be run on the Thank You page, the one after the user has completed check out. This is for security reasons, so you're not running malicious code on pages with sensitive data.

"If someone bought something from a buy button and didn't interact with the site in any other way, would it be considered a bounce, since the button is part of an iframe?"

Haha reading this makes me hope I'm not just confused about what's what in shopify. I can only speak to my own implementation, but the buy button isn't an actual iframe, it's more of an API interaction. You build whatever button you want in your site, and when clicked, you make the proper API call. Then, when the user goes to checkout, they are taken off of your own domain and onto the shopify domain to handle credit card stuff. So you would put a GA event on that button click and log it yourself, then let shopify handle it's part, and then you can do something like my code above outlines to get more GA data.

 

rd1
New Member
4 0 0

Wow. THANK YOU.

And then I need to alter the original ga code on the main domain right? Per this article?

https://support.google.com/analytics/answer/1034342?hl=en

Do you know about the answer to my other question about bounces? Set up as is, would GA consider a click on the button as an event, or would GA not be able to see that "event" because it's in an iframe?

 


 

RTOP_Developer
Shopify Partner
13 0 2

No problem, I couldn't find how to do this documented anywhere so I hope others can speed thru it with this.

And, correct, follow that article to set things up on your main domain.

I edited my question with an answer about bounces, but take it with a grain of salt as I'm learning this as I go haha.

 

rd1
New Member
4 0 0

Grain of salt taken. Thanks so much!

So does that bit of JS appear on the thank you page for every button from the shopify store? Or can you make it appear on the thank you for only 1 button. The main shopify sells a number of products, but this domain only markets one of them. Will that screw things up?

Thomas_Lesenech
Shopify Partner
4 0 1

Hello, 

Just a quick question regarding the cross domain tracking : on the main domain, should the code be : 

<script>

(function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){ (i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o), m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m) })(window,document,'script','//www.google-analytics.com/analytics.js','ga');

ga('create', ''UA-XXXXXXX-Y'', 'auto', {'allowLinker': true});
ga('require', 'linker');
ga('linker:autoLink', ['checkout.shopify.com'] );
ga('send', 'pageview');

</script>

 

I am not sure of the "ga('linker:autoLink', ['checkout.shopify.com'] );"

 

Thanks

Simon48
New Member
3 0 0

Hello Leseneachal,

you weren't sure about the correctness of your code. Did it eventually work out fine? 

How can one test if it does and what would happen if that code doesn't work while the one inside the shopify additional script section does?

you can also e-mail me (simon.sparber@gmail.com) for an answer. This is pretty urgent and I am a very beginner...!

Simon48
New Member
3 0 0

Hello Joshua,

here is Simon. Could you help me out with adding the right GA tracking both in the additional scripts section (as I am only using shopify lite version/ buy button) and on my squarespcace website? 

Just e-mail me (simon.sparber@gmail.com) for the details. Ready to pay you for this.

RTOP_Developer
Shopify Partner
13 0 2

Hi,

Yes the code chunk you pasted is the correct code for the main page. You have to replace the code

UA-XXXXXXX-Y

with your own GA tracking code. The line

ga('linker:autoLink', ['checkout.shopify.com'] );

can be left as is. It tells the GA account to link to the shopify checkout domain (I assume it whitelists checkout.shopify.com so that when the code you placed on that page calls this domain, it is allowed).

 

wow 5 months late haha sorry I missed it at the time.

psj0000000000
New Member
1 0 0

Thank you so much for such a thoughtful post! This was a huge win for me. However, I'm running into one problem: it doesn't appear as the though cross-domain tracking aspect is working. I think it's because we can't append the linker paramater to the "thank you" confirmation URL...? 

I've recorded the tag flow, and run the debugger and it's overwriting the source/medium as "direct" on the final purchase conformation page, as well as starting a google analytics new session, and assigning a new client ID. Any ideas? Thanks so much!

Ron_Lubin
New Member
2 0 2

I've been working on trying to get this to work as well. Once I set up cross-domain tracking, I used this script in my Checkout additional scripts section:

<script async src="https://www.googletagmanager.com/gtag/js?id=UA-XXXXXXXXX-X"></script>
<script>
window.dataLayer = window.dataLayer || [];
function gtag(){dataLayer.push(arguments);}
gtag('set', 'linker', {'domains': ['mainwebsite.com']});
gtag('js', new Date());

gtag('config', 'UA-XXXXXXXXX-X');
gtag('event', 'purchase', {transaction_id: {{checkout.order_number}}, value: {{checkout.subtotal_price}}, shipping: {{checkout.shipping_price}}});
</script>

When using Tag Assistant, I can see that it is pulling the order id #, the subtotal price, and shipping price. However, it is pulling it without the decimal, i.e. a $30.00 order is showing as $3000. Also, cannot get it to be able to pull a list of the line items. Attached is what the tag manager assistant is showing (was for order #1016, for an item at $30 and shipping at $4.95). Hoping someone will be able to modify this to make it work perfectly.

 

Improving_CVR
Shopify Partner
25 0 13

That thread seems to be the only information on the internet to track sales with Shopify Buy Button, so first of all: BIG THANKS!!

 

Any luck with tweaking it Ron?

levyelectric
New Member
5 0 0

Hey there - did you every figure this out?   I'm trying to use a similar code snipped as you.  It would be awesome if you could share how you have things set up in Google Tag Manager to enable this to work correctly.

Improving_CVR
Shopify Partner
25 0 13
Hi!

Yes the only thing we did was so simple it blew my mind.

In the css code of the Shopify button (you know, the code you paste on
whatever page you want the buy button), we replaced the domain
mystore-myshopify.com by our domain mystore.com.

That’s it, nothing else. And now google analytics tracks correctly.

It’s insane that every google rep and Shopify rep had absolutely no answer
to that problem when the answer is that easy. It tells a lot about the
level of training those guys have...

I hope you get to implement it quick!
Josh_Uebergang
Shopify Expert
853 30 213

@Improving_CVR Cool to hear that works. With Shopify's new buy button, this is likely possible and works because the person stays on the same domain (your shop's primary custom domain) rather than being taken to the myshopify.com version of the domain upon checking out from the Buy Button.

Run Google Shopping ads? Get the free definitive guide to Google Shopping for Shopify (no optin required): https://www.digitaldarts.com.au/google-shopping
levyelectric
New Member
5 0 0

Hi @Josh_Uebergang @Improving_CVR - any chance you'd be willing to share the code snippet you used here to get it to work?  Mine is below, but I'm running into two issues still:

 

  • Orders values coming over without decimals (two extra "0s" that shouldn't be in the total purchase amount)
  • Some orders not getting tracked all together. 

 

Screen Shot 2019-10-07 at 3.03.47 PM.pngScreen Shot 2019-10-07 at 3.03.40 PM.png

 

 

 

 

<script async src="https://www.googletagmanager.com/gtag/js?id=UA-129291129-1"></script>
<script>
window.dataLayer = window.dataLayer || [];
function gtag(){dataLayer.push(arguments);}
gtag('set', 'linker', {'domains': ['levyelectric.com']});
gtag('js', new Date());

gtag('config', 'UA-129291129-1');
gtag('event', 'purchase', {transactionId: {{checkout.order_number}}, transactionTotal: {{checkout.total_price}};
</script>

<script>
window.dataLayer = window.dataLayer || [];
dataLayer.push({
 'event': 'purchase',
 'transactionId': '{{checkout.order_number}}',
 'transactionTotal': {{checkout.total_price}},
});
</script>

<!-- Google Tag Manager -->
<script>(function(w,d,s,l,i){w[l]=w[l]||[];w[l].push({'gtm.start':
new Date().getTime(),event:'gtm.js'});var f=d.getElementsByTagName(s)[0],
j=d.createElement(s),dl=l!='dataLayer'?'&l='+l:'';j.async=true;j.src='https://www.googletagmanager.com/gtm.js?id='+i+dl;f.parentNode.insertBefore(j,f);
})(window,document,'script','dataLayer','GTM-MB23D4D');</script>
<!-- End Google Tag Manager -->

 

AtlasWebmaster
Tourist
8 0 7

Here's instructions for how to easily feed the referrer URL to Google Analytics every time the Buy Button is clicked and the cart opens. Enjoy!

 

https://community.shopify.com/c/Ecommerce-Marketing/HOW-TO-GUIDE-Track-Referrer-URL-with-Google-Anal...

ristobrand
New Member
2 0 0

Did you ever figure this out? What was the solution?