使用 GA Measurement Protocol 大概也有超過五年了 XD 最近一直收到通報,說舊版 GA Measurement Protocol 即將在 2023.07.01 不在接收資料處理,簡稱看不到報表。
建立一個 GA4 專案後,發現要在使用 Measurement Protocol 的難度有稍微增加。包括測試也有點卡卡 XD 最近就記錄一下筆記:
- https://developers.google.com/analytics/devguides/collection/protocol/ga4
- 使用 https://ga-dev-tools.web.app/ga4/event-builder/ 來實驗想發送的資料是否正確
- 使用 https://www.google-analytics.com/debug/mp/collect 可以收到GA4驗證內容
- 快速查詢 GA4 可使用屬性 https://support.google.com/analytics/answer/9143382
- 使用 PHP Code 來運行
首先,想要模擬個 page_view 時,才發現官方文件沒有多提,後來大概是組出這樣:
{"client_id":"00000000","non_personalized_ads":true,"events":[{"name":"page_view","params":{"page_title":"hello","page_location":"blog.changyy.org"}}]}
而 PHP Code:
function _GA4_($api_secret, $measurement_id, $deviceId, $deviceIP, $events = array()) {$query_string = array('measurement_id' => $measurement_id,'api_secret' => $api_secret,);if (!empty($deviceIP)) {// https://support.google.com/analytics/answer/9143382// https://github.com/dataunlocker/save-analytics-from-content-blockers/issues/25$query_string['uip'] = $deviceIP;$query_string['_uip'] = $deviceIP;}$url = 'https://www.google-analytics.com/mp/collect?'.http_build_query($query_string);//$url = 'https://www.google-analytics.com/debug/mp/collect?'.http_build_query($query_string);// post without libcurl// https://ga-dev-tools.web.app/ga4/event-builder/$payload = array('client_id' => $deviceId,'non_personalized_ads' => true,//'timestamp_micros' => "".floor(microtime(true) * 1000)."000",'events' => $events,);//if (isset($_SERVER) && isset($_SERVER['COUNTRY_CODE']) && !empty($_SERVER['COUNTRY_CODE']) ) {// if (!isset($payload['user_properties']))// $payload['user_properties'] = array();// $payload['user_properties']['country_code'] = array(// 'value' => $_SERVER['COUNTRY_CODE'],// );//}$POST_DATA = json_encode($payload);$options = array('http' => array('header' => implode("\r\n", array("Content-Type: application/json",//"Content-Length: ".strlen($POST_DATA),)),'method' => 'POST','content' => $POST_DATA,));$context = @stream_context_create($options);$result = @file_get_contents($url, false, $context);//echo "result:[$result]\n$POST_DATA\n".print_r($options)."\n";exit;}
如此,就可以用以下完成事件回報了:
_GA4_($api_secret, $measurement_id, $deviceId, $deviceIP, array(array('name' => 'page_view','params' => array('page_title' => 'Hello','page_location' => 'https://blog.changyy.org/',),));
而使用 https://www.google-analytics.com/debug/mp/collect 驗證時,有錯誤可以在 http response body 看到資料,例如:
{"validationMessages": [ {"description": "Unable to parse Measurement Protocol JSON payload. : invalid value Cannot bind a list to map for field 'user_properties'. for type Map","validationCode": "VALUE_INVALID"} ]}
沒有留言:
張貼留言