php - Can I get the Google Analytics 4 Data Stream URL instead of Name?
one text
GA4 will track just about anything that has an active tracking code on it regardless if the app/domain is a registered stream or not. So this means dev/staging environments will also get tracked in the production property which is of course undesirable unless the code is removed when migrating from prod to dev.
To prevent this issue from occurring when I migrate between environments I want to add a mechanism to check if the $_SERVER['HTTP_HOST'] is equal to the Stream URL setting in GA4. Using the PHP API lib provided by Google, I can get as close as the Stream Name using the runReport method, but this would not necessarily always be equal to the URL. I'm hoping for another method that can return config settings rather than a report.
I am wondering if it's possible to get the STREAM URL value instead of STREAM NAME. This is as close as I've gotten.
function ga4_streams() {
init_ga4(); // This function authenticates
$client = new BetaAnalyticsDataClient();
$response = $client->runReport([
'property' => 'properties/' . GA4_PROPERTY_ID,
'dateRanges' => [
new DateRange([
'start_date' => '2022-01-01',
'end_date' => 'today',
]),
],
'dimensions' => [new Dimension(
[
'name' => 'streamName',
]
),
],
]);
$streams = array();
foreach ($response->getRows() as $row) {
$streams[] = $row->getDimensionValues()[0]->getValue();
}
return $streams;
}
$streams = ga4_streams();
if ( in_array($_SERVER['HTTP_HOST'], $streams ) ) {
// GA4 Tracking stuff here
}
Source