顯示具有 Measurement Protocol 標籤的文章。 顯示所有文章
顯示具有 Measurement Protocol 標籤的文章。 顯示所有文章

2022年7月20日 星期三

PHP 開發筆記 - 使用 Google Analytic (GA4) Measurement Protocol

使用 GA Measurement Protocol 大概也有超過五年了 XD 最近一直收到通報,說舊版 GA Measurement Protocol 即將在 2023.07.01 不在接收資料處理,簡稱看不到報表。

建立一個 GA4 專案後,發現要在使用 Measurement Protocol 的難度有稍微增加。包括測試也有點卡卡 XD 最近就記錄一下筆記:
首先,想要模擬個 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"
  } ]
}

2019年9月18日 星期三

iOS 開發筆記 - 使用 Swift 完成 GA Measurement Protocol 實作

大概去年夏天,偶爾會寫一點 Swift 程式,雖然對 Objective c 比較熟,但時勢變遷就該順應潮流。那時採用 GoogleAnalytics 套件,但 Google Analytics for App 要在今年秋天下線了,Google一直要大家改用 Firebase ,且 Google 牌 cocoapods GoogleAnalytics 也的確幾年沒更新了。只是 Firebase 就明顯要人多花錢,例如要先把 Firebase 的數據匯入到 GA 上免錢,但有些查詢又要搞到 BigQuery 才行,雖然 BigQuery 有免費額度 啦 XD 因此趁 GA Measurement Protocol 還沒下線前,多用用他吧!把以前是 App Screen 就設法轉成 Web Pageview 吧,唯一的缺點是 Session 這類,若要硬做也是一招啦,在此就都不管了。

在此只包裝成 3 個函式供人使用即可,分別是取得 clientID、回報 pageview、回報 event 既可:

override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.

GAEvent(trackingID: "UA-########-#", clientID: getClientID(), eventCategory: "TestEC", eventAction: "TestEA", eventLabel: "TestEL", eventValue: 0)

GAPageView(trackingID: "UA-########-#", clientID: getClientID(), path:"/")
}

func getClientID() -> String {
// example
return UUID().uuidString
}

func GAPageView(trackingID:String, clientID:String, path:String ) {
var url = URLComponents(string: "https://www.google-analytics.com/collect")!
if trackingID.isEmpty || clientID.isEmpty || path.isEmpty {
return
}
url.queryItems = [
URLQueryItem(name: "v", value: "1"),
URLQueryItem(name: "tid", value: trackingID),
URLQueryItem(name: "cid", value: clientID),
URLQueryItem(name: "t", value: "pageview"),
URLQueryItem(name: "dh", value: "example.com"),
URLQueryItem(name: "dp", value: path),
]
//#if DEBUG
//url.queryItems?.append(URLQueryItem(name: "cd1", value: "DEBUG"))
//#endif
//if let appVersion = Bundle.main.infoDictionary?["CFBundleShortVersionString"] as? String, appVersion.isEmpty {
//    url.queryItems?.append(URLQueryItem(name: "cd2", value: appVersion))
//}

let request = URLRequest(url: url.url!)
let task = URLSession.shared.dataTask(with: request) {(data, response, error) in
//guard let data = data else { return }
//print(String(data: data, encoding: .utf8)!)
if let httpResponse = response as? HTTPURLResponse {
print("GAPageView: \(httpResponse.statusCode)" )
}
}
task.resume()
}

func GAEvent(trackingID:String, clientID:String, eventCategory:String, eventAction:String, eventLabel:String, eventValue:Int) {
var url = URLComponents(string: "https://www.google-analytics.com/collect")!
if trackingID.isEmpty || clientID.isEmpty || path.isEmpty {
return
}

url.queryItems = [
URLQueryItem(name: "v", value: "1"),
URLQueryItem(name: "tid", value: trackingID),
URLQueryItem(name: "cid", value: clientID),
URLQueryItem(name: "t", value: "event"),
URLQueryItem(name: "ec", value: eventCategory),
]
//#if DEBUG
//url.queryItems?.append(URLQueryItem(name: "cd1", value: "DEBUG"))
//#endif
//if let appVersion = Bundle.main.infoDictionary?["CFBundleShortVersionString"] as? String, appVersion.isEmpty {
//    url.queryItems?.append(URLQueryItem(name: "cd2", value: appVersion))
//}

if !eventAction.isEmpty {
url.queryItems?.append(URLQueryItem(name: "ea", value: eventAction))
if !eventLabel.isEmpty {
url.queryItems?.append(URLQueryItem(name: "el", value: eventAction))
if eventValue >= 0 {
url.queryItems?.append(URLQueryItem(name: "ev", value: "\(eventValue)"))
}
}
}

let request = URLRequest(url: url.url!)
let task = URLSession.shared.dataTask(with: request) {(data, response, error) in
//guard let data = data else { return }
//print(String(data: data, encoding: .utf8)!)
if let httpResponse = response as? HTTPURLResponse {
print("GAEvent: \(httpResponse.statusCode)" )
}
}
task.resume()
}


其中 getClientID() 只是個示意,因為每次呼叫 UUID().uuidString 都會產生一組新的,可以把它存起來使用,或是針對某些情境設計規劃,像是服務有提供登入機制時,就改用從 user id 計算得出等那類即可。