composer require alexwestergaard/php-ga4
歐盟已通知 Google Analytics 預設不遵守 GDPR。這是因為前端用戶端會透過事件發送訪客詳細訊息,例如 IP 位址和裝置資訊。透過歐洲區域內的中間人伺服器可以避免這種情況。
設定需要Measurement ID和API Secret 。前往管理員(左下角)-> 帳戶 -> 資料流 -> {您的流}。在這裡,您應該在頂部找到“Measurement ID”,在頁面下方找到“測量協議的 Api Secrets”,您可以在其中為自己建立一個API secret
。
前往Administrator
(左下角),然後選擇您的Account
-> Data Streams
-> 您的串流。
在這裡,您可以Api Secrets for Measurement Protocol
頂部和下方找到Measurement-ID
,您可以在其中為自己建立一個API Secret
。
獲得憑證後,您可以像這樣初始化 Analytics:
use AlexWestergaard PhpGa4 Analytics ;
$ analytics = Analytics:: new (
measurement_id: ' G-XXXXXXXX ' ,
api_secret: ' xYzzX_xYzzXzxyZxX ' ,
debug: true | false #Default: False
);
伺服器端標記不應取代前端客戶端,會話啟動應透過gtag.js
客戶端進行。預設流程應該如下發生:
_ga
和_gid
cookie 傳回 Client/GTAG.js_ga
(或_gid
)發送/填充事件注意:完全可以在不從 Google Analytics 取得會話 cookie 的情況下將事件推送到後端;但是,如果您不知道如何透過後端推送該訊息,您將丟失GTAG.js
請求中捆綁的資訊。您可以將_ga
和_gid
會話替換為您自己產生的唯一 ID。
所有請求都應遵循此結構,並至少包含 1 個事件供 Google Analytics 接受。
Analytics [
Events [
Event {
Parameters
? Items [
Item Parameters
]
}
]
User Properties [
Properties {
Key: Value
}
]
? Consent {
Key: Value
}
? User Data {
Key: Value
}
]
這是文件中所示的預先建置事件清單。所有事件都有以下參數來定位每個事件的觸發位置。
// Manual setting of each event
$ event -> setLanguage (string $ var );
$ event -> setPageLocation (string $ var );
$ event -> setPageReferrer (string $ var );
$ event -> setPageTitle (string $ var );
$ event -> setScreenResolution (string $ var );
// Fillable for multiple events
$ eventPage = AlexWestergaard PhpGa4 Helper EventParamsHelper ();
$ event -> setEventPage ( $ eventPage );
該程式庫是為後端伺服器端追蹤而建立的,但您可能會使用 Javascript 或 Websockets 透過前端觸發大多數事件。將有 2 個範例,一個作為記錄/排隊事件的純後端,另一個用於前端到後端的通訊。
use AlexWestergaard PhpGa4 Exception ;
use AlexWestergaard PhpGa4 Analytics ;
use AlexWestergaard PhpGa4 Event ;
use AlexWestergaard PhpGa4 Item ;
// require vendor/autoload.php
$ visitors = getVisitorsAndEvents (); // pseudo function, make your own logic here
foreach ( $ visitors as $ collection ) {
// Group of events, perhaps need logic to change from json or array to event objects
// Maybe its formatted well for the > ConvertHelper::parseEvents([...]) < helper
$ groups = $ collection [ ' events ' ];
// If gtag.js, this can be the _ga or _gid cookie
// This can be any kind of session identifier
// Usually derives from $_COOKIE['_ga'] or $_COOKIE['_gid'] set by GTAG.js
$ visitor = $ collection [ ' session_id ' ];
// load logged in user/visitor
// This can be any kind of unique identifier, readable is easier for you
// Just be wary not to use GDPR sensitive information
$ user = $ collection [ ' user_id ' ];
// Render events grouped on time (max offset is 3 days from NOW)
foreach ( $ groups as $ time => $ data ) {
try {
$ analytics = Analytics:: new ( $ measurementId , $ apiSecret )
-> setClientId ( $ visitor )
-> setTimestampMicros ( $ time );
if ( $ user !== null ) {
$ analytics -> setUserId ( $ user );
}
$ analytics -> addUserParameter (... $ data [ ' userParameters ' ]); // pseudo logic for adding user parameters
$ analytics -> addEvent (... $ data [ ' events ' ]); // pseudo logic for adding events
$ analytics -> post (); // send events to Google Analytics
} catch ( Exception Ga4Exception $ exception ) {
// Handle exception
// Exceptions might be stacked, check: $exception->getPrevious();
}
}
}
// array< array< eventName, array<eventParams> > >
axios . post ( "/your-api-endpoint/ga4-event-receiver" , [
// Note each event is its own object inside an array as
// this allows to pass the same event type multiple times
{
addToCart : {
currency : "EUR" ,
value : 13.37 ,
items : [
{
item_id : 1 ,
item_name : "Cup" ,
price : 13.37 ,
quantity : 1 ,
} ,
] ,
} ,
} ,
] ) ;
use AlexWestergaard PhpGa4 Helper ConvertHelper ;
use AlexWestergaard PhpGa4 Exception ;
use AlexWestergaard PhpGa4 Analytics ;
use AlexWestergaard PhpGa4 Event ;
// require vendor/autoload.php
try {
$ events = ConvertHelper:: parseEvents ( $ _POST );
Analytics:: new ( $ measurementId , $ apiSecret )
-> addEvent (... $ events )
-> post ();
} catch ( Exception Ga4Exception $ exception ) {
// Handle exception
// Exceptions might be stacked, check: $exception->getPrevious();
}
您可以建立自己的自訂事件。您所需要的只是實作並填入AlexWestergaardPhpGa4FacadeTypeEventType
外觀/介面。如果您想要輕鬆的生活功能,那麼您可以從AlexWestergaardPhpGa4HelperEventHelper
擴展您的事件,並根據您的需求進行覆蓋。
// EventHelper implements AlexWestergaardPhpGa4FacadeTypeEventType
class ExampleEvent extends AlexWestergaard PhpGa4 Helper EventHelper
{
// variables should be nullable as unset() will set variable as null
protected null | mixed $ my_variable ;
protected null | mixed $ my_required_variable ;
// Arrays should always be instanciated empty
protected array $ my_array = [];
public function getName (): string
{
return ' example_event ' ;
}
public function getParams (): array
{
return [
' my_variable ' ,
' my_array ' ,
];
}
public function getRequiredParams (): array
{
return [
' my_required_variable ' ,
];
}
public function setMyVariable ( string $ value )
{
$ this -> my_variable = $ value ;
return $ this ; // Allows chained events
}
public function setMyRequiredVariable ( string $ value )
{
$ this -> my_required_variable = $ value ;
return $ this ; // Allows chained events
}
}
GA4 的測量協定具有調試功能,可使用 Analytics 建構函數中的debug
參數啟用此功能。
$ analytics = Analytics:: new (
measurement_id: ' G-XXXXXXXX ' ,
api_secret: ' xYzzX_xYzzXzxyZxX ' ,
debug: true // default: false
);
啟用Debug
後,事件將發送至https://www.google-analytics.com/debug/mp/collect
,其中問題將被 GA4Exception 捕獲(注意$exception->getPrevious()
堆疊);這樣的響應將如下所示:
{
"validationMessages" : [
{
"fieldPath" : " events " ,
"description" : " Event at index: [0] has invalid name [_badEventName]. Names must start with an alphabetic character. " ,
"validationCode" : " NAME_INVALID "
}
]
}
注意:此庫已經驗證事件在新增至分析時格式是否正確( $analytics->addEvent(...)
)。
兩個要點:
debugView
中。 page_view
事件有效,但官方文件中沒有記錄它,因此不要依賴它。