Customer Event(Google ads) - No sent Data

Good afternoon, I have a problem with this script that I added to my customer events to track purchases. In my Additional scripts it worked like this:

<script>
var enhanced_conversion_data = {
"first_name": "{{ checkout.billing_address.first_name }}",
"last_name": "{{ checkout.billing_address.last_name }}",
"home_address": {
"street": "{{ checkout.billing_address.street }}",
"city": "{{ checkout.billing_address.city }}",
"region": "{{ checkout.billing_address.province }}",
"postal_code": "{{ checkout.billing_address.zip }}",
"country": "{{ checkout.billing_address.country_code }}"
}
}
if("{{ checkout.email }}"){
enhanced_conversion_data.email = "{{ checkout.email }}";
}
if("{{ checkout.billing_address.phone }}"){
enhanced_conversion_data.phone_number = "{{ checkout.billing_address.phone }}";
}
</script>
<!-- Global site tag (gtag.js) -->
<script async src="https://www.googletagmanager.com/gtag/js?id=AW-NUMBER"></script>
<script>
window.dataLayer = window.dataLayer || [];
function gtag(){dataLayer.push(arguments);}
gtag('js', new Date());
gtag('config', 'AW-NUMBER', {'allow_enhanced_conversions': true});
</script>
<!-- added 5/16/2022 per Google; replaces GTM Ads Conversion -->
<script>
gtag('event', 'conversion', {
'send_to': 'AW-NUMBER/NUMBER',
'value': {{ checkout.total_price | divided_by: 100.0 }},
'currency': '{{ currency }}',
'transaction_id': '{{ order_number }}',
});
</script>

This worked correctly. Now, when moving it to my customer events, it looks like this:

function loadExternalScript(src) {
  return new Promise((resolve, reject) => {
    const script = document.createElement('script');
    script.src=src;
    script.async = true;
    script.onload = () => resolve(script);
    script.onerror = () => reject(new Error('Script loading failed: ' + src));
    document.head.appendChild(script);
  });
}

analytics.subscribe('checkout_completed', (event) => {
  // Enhanced Conversion - Google Ads
  const checkout = event.data.checkout;
  const address1 = checkout.billingAddress.address1 || '';
  const address2 = checkout.billingAddress.address2 || '';
  const street = address1 + (address1 && address2 ? ' ' : '') + address2;

  const enhanced_conversion_data = {
    first_name: checkout.billingAddress.firstName,
    last_name: checkout.billingAddress.lastName,
    home_address: {
      street: street,
      city: checkout.billingAddress.city,
      region: checkout.billingAddress.province,
      postal_code: checkout.billingAddress.zip,
      country: checkout.billingAddress.countryCode
    }
  };

  if (checkout.email) {
    enhanced_conversion_data.email = checkout.email;
  }
  if (checkout.billingAddress.phone) {
    enhanced_conversion_data.phone_number = checkout.billingAddress.phone;
  }
  // End Enhanced Conversion - Google Ads

  loadExternalScript('https://www.googletagmanager.com/gtag/js?id=AW-NUMBER')
    .then(() => {
      console.log('success script');
      window.dataLayer = window.dataLayer || [];
      function gtag(){ dataLayer.push(arguments); }
      gtag('js', new Date());
      gtag('config', 'AW-NUMBER', {'allow_enhanced_conversions': true});
      gtag('event', 'conversion', {
        'send_to': 'AW-NUMBER/NUMBER',
        'value': checkout.totalPrice.amount,
        'currency': checkout.totalPrice.currencyCode,
        'transaction_id': checkout.order.id
      });
    })
    .catch(error => {
      console.error('Error loading script:', error);
    });
});

I reach console.log(‘success script’) when making a purchase, it means it connects to the script, but it is not sending the information.

Hello,

I am San from MS Web Designer.

You should add only google site tag code and conversion code that’s enough to track the customer events.

Regards,

San

Hello,

You may try this data layer for purchase

const event_prefix = ‘’;
const formattedItemId = true;
const GTM_container_url = ‘https://www.googletagmanager.com’;
const GTM_container_id = ‘GTM-00000’;

let storeCountryCode = window.localStorage.getItem(‘shopCountryCode’);
storeCountryCode = storeCountryCode || ‘US’;
window.dataLayer = window.dataLayer || ;
function gtag() {
dataLayer.push(arguments);
}

if (window.location.href.includes(‘/checkouts/’)) {
// tag manager
(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=GTM_container_url + ‘/gtm.js?id=’ + i + dl;
f.parentNode.insertBefore(j, f);
})(window, document, ‘script’, ‘dataLayer’, GTM_container_id);

analytics.subscribe(‘page_viewed’, (event) => {
window.dataLayer.push({
event: event_prefix + ‘page_view’,
page_location: event.context.document.location.href,
});
});
// end tag manger

// DataLayer Events
analytics.subscribe(‘payment_info_submitted’, (event) => ecommerceDataLayer(‘add_payment_info’, event));

analytics.subscribe(‘checkout_shipping_info_submitted’, (event) => ecommerceDataLayer(‘add_shipping_info’, event));

analytics.subscribe(‘checkout_completed’, (event) => ecommerceDataLayer(‘purchase’, event));

}

async function sha256Hash(value) {
const encoder = new TextEncoder();
const data = encoder.encode(value);

const hashBuffer = await crypto.subtle.digest(‘SHA-256’, data);

const hashArray = Array.from(new Uint8Array(hashBuffer));
const hashedValue = hashArray.map(byte => (‘00’ + byte.toString(16)).slice(-2)).join(‘’);
return hashedValue;
}

async function ecommerceDataLayer(gtm_event_name, event) {
let hash_email;
let hash_phone;
const phone = event.data?.checkout?.phone;
const email = event.data?.checkout?.email;

if (phone) {
hash_phone = await sha256Hash(phone);
}

if (email) {
hash_email = await sha256Hash(email);
}

const customerInfo = {
customer: {
first_name: event.data?.checkout?.billingAddress?.firstName || event.data?.checkout?.shippingAddress?.firstName,
last_name: event.data?.checkout?.billingAddress?.lastName || event.data?.checkout?.shippingAddress?.lastName,
email: email,
hash_email: hash_email,
phone: phone,
hash_phone: hash_phone,
address: event.data?.checkout?.shippingAddress
}
}
dataLayer.push(customerInfo);

const dataLayerInfo = {
event: event_prefix + gtm_event_name,
ecommerce: {
transaction_id: event.data?.checkout?.order?.id,
value: event.data?.checkout?.totalPrice?.amount,
tax: event.data?.checkout?.totalTax?.amount,
shipping: event.data?.checkout?.shippingLine?.price?.amount,
currency: event.data?.checkout?.currencyCode,
coupon: (event.data?.checkout?.discountApplications || ).map(discount => discount.title).join(‘,’),
items: (event.data?.checkout?.lineItems || ).map(item => ({
item_id: formattedItemId ? ‘shopify_’ + storeCountryCode + ‘’ + (item.variant?.product?.id || ‘’) + '’ + (item.variant?.id || ‘’) : item.variant?.product?.id,
product_id: item.variant?.product?.id,
variant_id: item.variant?.id,
item_name: item.title,
coupon: item.discountAllocations?.discountApplication?.title,
discount: item.discountAllocations?.amount?.amount,
item_variant: item.variant?.title,
price: item.variant?.price?.amount,
quantity: item.quantity,
item_brand: item.variant?.product?.vendor,
item_category: item.variant?.product?.type

}))
}
}

dataLayer.push({
ecommerce: null
});
dataLayer.push(dataLayerInfo);

const css1 = ‘background: red; color: #fff; font-size: normal; border-radius: 3px 0 0 3px; padding: 3px 4px;’;
const css2 = ‘background-color: blue; color: #fff; font-size: normal; border-radius: 0 3px 3px 0; padding: 3px 4px;’;

console.log(
‘%cGTM DataLayer Event:%c’ + event_prefix + gtm_event_name, css1, css2, Object.assign({}, dataLayerInfo, customerInfo)
);
}