measurement_id = $measurement_id; $this->api_secret = $api_secret; $this->firebase_app_id = $firebase_app_id; } /** * 发送事件到GA4 * * @param string $client_id 客户端ID (通常是UUID) * @param string $event_name 事件名称 * @param array $event_params 事件参数(键值对) * @param int|null $timestamp_ms 自定义时间戳(可选) * * @return bool 返回true表示发送成功,false表示失败 */ public function sendEvent($client_id, $event_name, $event_params = [], $timestamp_ms = null) { $payload = [ 'client_id' => $client_id, 'events' => [ [ 'name' => $event_name, 'params' => $event_params ] ] ]; if ($timestamp_ms) { $payload['events'][0]['timestamp_micros'] = $timestamp_ms * 1000; // 转换为微秒 } $url = $this->endpoint . '?measurement_id=' . $this->measurement_id . '&api_secret=' . $this->api_secret; $response = $this->postRequest($url, $payload); if ($response !== false) { // GA4的响应状态码 $http_code = $response['http_code']; return in_array($http_code, [200, 204]); } return false; } /** * 发送POST请求 * * @param string $url 请求URL * @param array $data 请求数据 * * @return array|false 返回包含响应的数组,或者false失败 */ private function postRequest($url, $data) { $ch = curl_init($url); $payload = json_encode($data); curl_setopt($ch, CURLOPT_POST, true); curl_setopt($ch, CURLOPT_POSTFIELDS, $payload); curl_setopt($ch, CURLOPT_HTTPHEADER, [ 'Content-Type: application/json', 'Content-Length: ' . strlen($payload) ]); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, true); // 确保SSL安全 $response = curl_exec($ch); $http_code = curl_getinfo($ch, CURLINFO_HTTP_CODE); if ($response === false) { error_log('cURL error: ' . curl_error($ch)); curl_close($ch); return false; } curl_close($ch); return [ 'body' => $response, 'http_code' => $http_code ]; } }