Create a new override file to add the google tag manager partial into the main spree_application layout
app/overrides/spree/layouts/spree_application/add_google_tag_manager.html.erb.deface
<!-- insert_after '.container' -->
<%= render :partial => 'spree/shared/google_tag_manager'%>
app/views/spree/shared/google_tag_manager.html.erb
And add the following code inside that partial:
<!-- Google Tag Manager -->
<noscript>
<iframe src="//www.googletagmanager.com/ns.html?id=<%= ENV['GOOGLE_TAG_MANAGER'] %>"
height="0" width="0" style="display:none;visibility:hidden">
</iframe>
</noscript>
<script>
dataLayer = [];
(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=
'//www.googletagmanager.com/gtm.js?id='+i+dl;f.parentNode.insertBefore(j,f);
})(window,document,'script','dataLayer','<%= ENV['GOOGLE_TAG_MANAGER'] %>');
</script>
<!-- End Google Tag Manager -->
<%= javascript_tag do %>
<% if @order.present? and @order.email.present? %>
dataLayer.push({'transactionEmail': '<%= @order.email %>'});
<% end %>
<% if @order.present? and @order.user.present? %>
dataLayer.push({'userid': '<%= @order.user.id %>'});
<% end %>
<% if flash[:commerce_tracking] and @order.present? %>
dataLayer.push({
'transactionId': '<%= @order.number %>',
'transactionAffiliation': 'Yourcompanyname',
'transactionTotal': <%= @order.total %>,
'transactionTax': <%= @order.adjustments.tax.sum(:amount) %>,
'transactionShipping': <%= @order.adjustments.shipping.sum(:amount) %>,
'transactionCity': '<%= @order.bill_address.city %>',
'transactionState': '<%= @order.bill_address.state_text %>',
'transactionZip': '<%= @order.bill_address.zipcode %>',
'transactionEmail': '<%= @order.email %>',
'transactionProducts': [
<%=raw @order.line_items.map { |line_item| "{ 'sku': '#{h line_item.variant.sku}',
'name': '#{h line_item.variant.product.name}',
'category': '',
'price': #{h line_item.price},
'quantity': #{h line_item.quantity}}" } .join(",") %>
]
});
<% if @order.user.present? and @order.user.orders.complete.count==1 %>
dataLayer.push({
'event': 'first_time_user_conversion'
});
<% end %>
<% end %>
<% end %>
Last thing to do is about exporting your environment variable "GOOGLE_TAG_MANAGER" or add it to your application.yml if you are using something like Figaro gem for managing your environment variables. Thanks to https://gist.github.com/neddenriep for the reference code :)