使用新的 Google Analytics 4 (GA4) 服务器端进行跟踪

Tracking with the new Google Analytics 4 (GA4) server-side

Google Analytics 4 (GA4) 最近发布,并成为 Google Analytics 仪表板上新媒体资源的默认设置。我正在检查它,它看起来很棒。我们通过 Node.js 服务器向 Google Analytics 报告大量数据,而不是在客户端使用名为 universal-analytics (https://www.npmjs.com/package/universal-analytics) 的库,后者运行良好。

我们想尽快开始使用 GA4,但找不到任何关于如何将事件发送到 GA4 属性 服务器端的文档。只有客户端示例,而且这些示例在服务器上似乎根本不起作用。

简单地说,服务器端的以下等价物是什么?

<!-- Global site tag (gtag.js) - Google Analytics -->
<script async src="https://www.googletagmanager.com/gtag/js?id=G-ABC123ABC123"></script>
<script>
  window.dataLayer = window.dataLayer || [];
  function gtag(){dataLayer.push(arguments);}
  gtag('js', new Date());

  gtag('config', 'G-ABC123ABC123');
</script>

有人成功过吗?

您可以尝试使用测量协议 v2:https://developers.google.com/analytics/devguides/collection/protocol/ga4/sending-events?client_type=gtag#send_an_event

不过,目前是alpha版本。

运行良好

const measurementId = `G-XXXXXXXXXX`;
const apiSecret = `<secret_value>`;

fetch(`https://www.google-analytics.com/mp/collect?measurement_id=${measurementId}&api_secret=${apiSecret}`, {
  method: "POST",
  body: JSON.stringify({
    "client_id": "client_id",
    "events": [{
      "name": "add_payment_info",
      "params": {
        "currency": "USD",
        "value": 7.77,
        "coupon": "SUMMER_FUN",
        "payment_type": "Credit Card",
        "items": [
          {
            "item_id": "SKU_12345",
            "item_name": "Stan and Friends Tee",
            "affiliation": "Google Merchandise Store",
            "coupon": "SUMMER_FUN",
            "currency": "USD",
            "discount": 2.22,
            "index": 0,
            "item_brand": "Google",
            "item_category": "Apparel",
            "item_list_id": "related_products",
            "item_list_name": "Related Products",
            "item_variant": "green",
            "location_id": "L_12345",
            "price": 9.99,
            "quantity": 1
          }
        ]
      }
    }]
  })
});