在 api POST 响应成功后,如何通过 Google 跟踪代码管理器以编程方式衡量对 Google Analytics 的购买?

How do I programmatically measure a purchase to Google Analytics through Google Tag Manager after a successful api POST response?

查看 Google 标签管理器的文档,他们似乎建议通过确认页面浏览量来衡量购买。除非我误解了这一点,否则它可能由于重定向期间的失败或人为膨胀而变得不准确,因为稍后可以访问 link。

因此,我认为最好在我的购买 POST 请求得到成功响应后立即注册或衡量购买。像这样:

function purchase(data, form) {
  fetchHelper(url, {
    method: 'post',
    body: JSON.stringify(data),
  })
    .then(json => {
      // Send info to GTM that purchase was successful
      form.reset()
      window.location.href = `confirmation.html?booking=${json.booking_number}`;
    })
    .catch(error => {
      console.error('Error: ', error)
      swal('Oops', error.message, 'error');
    })
}

与其依靠页面访问来跟踪 conversions/purchases,我建议使用 Google 的 analytics.js 触发 GA 事件。根据 GA 中的事件数据,您可以创建一个 "goal",它应该为 purchase/conversion.

提供非常干净的数据

https://developers.google.com/analytics/devguides/collection/analyticsjs/events

在 GTM 中,您可能希望根据 Universal Analytics 类型设置代码。在选项中,您可以将 Track Type 设置为 Event,然后填写您的 Event Tracking Parameters。

要触发,您需要为自定义事件创建一个新的触发器。在此示例中,事件名称可能是 "purchase_complete"。然后你可以使用这个函数来触发触发器:

function fire(){
  var dataObject = {
    'event': 'purchase_complete',
    'category': 'click',
    'label': 'label_something'
  };
  if(typeof dataLayer != 'undefined'){
    dataLayer.push(dataObject);
  }
}

(来自 https://jonathanmh.com/custom-javascript-trigger-functions-google-tag-manager/

"Could be inaccurate"
确实这是一个普遍的问题。如果你想达到100%的可靠性,你可以依靠measurement protocol with server-side code. What you plan to do should get pretty close to that. Just push the purchase data to the dataLayer and make sure to send a hit after that (see below). One client-side solution to prevent duplicates is to save transaction IDs in a cookie and check that cookie for past transactions before tracking new ones

"Suggest measuring a purchase by confirmation page views"
你做什么并不重要,只要你使用 "hit" 将电子商务数据 ("payload") 发送到 GA,因为默认情况下电子商务数据只是位于客户端而不是发送到 GA。实际上,您有 2 个选择:综合浏览量或事件。通常,您倾向于看到通过综合浏览量发送的交易数据,因为传统上它是通过 server-side 代码插入到确认页面的数据,并且您看到 client-side 交互(例如添加到购物车)与事件一起发送,因为它是经过处理的在前端,但是发送所有 e-commerce 数据和事件是完全没问题的。