DateRanges for Google Analytics Data API - php

I have been successfully running a runRealtimeReport function from Google Analytics Data API, but I am currently struggling to run a runReport function.
Here is my code which I try to use:
$client->runReport([
'entity' => ['property_Id' => config('app.ga.propertyID')],
'dateRanges' => [new DateRange(['startDate' => '28daysago']),
new DateRange(['endDate' => 'today'])],
'dimensions' => [new Dimension([
'name' => 'sessionSource'
])
],
'metrics' =>[
[new Metric([
'name' => 'activeUsers'
])],
[new Metric([
'name' => 'sessions'
])],
[new Metric([
'name' => 'engagedSessions'
])],
[new Metric([
'name' => 'userEngagementDuration'
])],
[new Metric([
'name' => 'eventsPerSession'
])],
[new Metric([
'name' => 'engagementRate'
])]
]]);
No matter how I try to pass the values for DateRange, the API constantly fails and throws the following error:
Invalid message property: startDate
I am using an idiomatic PHP client for this

You need to specify both the startDate and endDate in one Date Range. As written, you've specified the startDate and endDate in two separate date ranges. Please update to:
'dateRanges' => [new DateRange(['start_date' => '28daysago',
'end_date' => 'today'])],

Related

Getting Empty Rows in Google Analytics Data API

Having difficulty getting empty rows from the Analytics Data API (GA4) BETA. I'm pulling simple traffic by date array but any dates that have zero traffic are not returned - I would prefer it to give me the date and zero.
I believe there should be a KEEPEMPTYROWS parameter but this doesn't seem to work - it took me so long to get the ORDERBY working that I thought I'd check here first to see if anyone else has got this working lol. I know I can fill in the missing dates using PHP code but I'd prefer to get it from the query. Here's the PHP for my JSON query:
$response = $client->runReport([
'property' => 'properties/' . $_SESSION["gaid"],
'dateRanges' => [
new DateRange([
'start_date' => $mstartdate,
'end_date' => $menddate,
]),
],
'dimensions' => [new Dimension(
[
'name' => 'date',
]
),
],
'metrics' => [new Metric(
[
'name' => 'activeUsers',
'name' => 'sessions',
]
)
],
'orderBys' => [
new OrderBy([
'dimension' => new OrderBy\DimensionOrderBy([
'dimension_name' => 'date',
'order_type' => OrderBy\DimensionOrderBy\OrderType::ALPHANUMERIC
]),
'desc' => false,
])],
'keepEmptyRows'=>"1"
]);
Thanks in advance :)

How to return metric totals in GA4 using the PHP client library?

When using php-data-analytics, if I call getTotals() on the runReport() response, I get a "RepeatedField" object:
$params = [
"property" => "properties/{$property_id}",
"dateRanges" => [
new DateRange([
'start_date' => '7daysAgo',
'end_date' => 'yesterday',
]),
new DateRange([
'start_date' => '14daysAgo',
'end_date' => '8daysAgo',
])
],
"dimensions" => [
new Dimension([ 'name' => 'nthDay' ])
],
"metrics" => [
new Metric([ 'name' => 'activeUsers' ])
],
"orderBys" => [
new OrderBy([
'desc' => false,
'dimension' => new OrderBy\DimensionOrderBy([
"dimension_name" => 'nthDay',
"order_type" => OrderBy\DimensionOrderBy\OrderType::NUMERIC
])
])
],
"keepEmptyRows" => true
];
$report = $client->runReport($params);
$totals = $report->getTotals();
$totals is returned as the following object:
Google\Protobuf\Internal\RepeatedField Object
(
[container:Google\Protobuf\Internal\RepeatedField:private] => Array
(
)
[type:Google\Protobuf\Internal\RepeatedField:private] => 11
[klass:Google\Protobuf\Internal\RepeatedField:private] => Google\Analytics\Data\V1beta\Row
[legacy_klass:Google\Protobuf\Internal\RepeatedField:private] => Google\Analytics\Data\V1beta\Row
)
How do I use the GA4 PHP client library to return the totals for each of my metrics? According to the official documentation, this should return a Row object?
The RepeatedField result returned from calling Google\Analytics\Data\V1beta\RunReportResponse::getTotals() can be iterated.
You must request a metric aggregation when you run the report to retrieve totals.
use Google\Analytics\Data\V1beta\BetaAnalyticsDataClient;
use Google\Analytics\Data\V1beta\DateRange;
use Google\Analytics\Data\V1beta\Dimension;
use Google\Analytics\Data\V1beta\Metric;
use Google\Analytics\Data\V1beta\MetricAggregation;
use Google\Analytics\Data\V1beta\OrderBy;
use Google\Analytics\Data\V1beta\OrderBy\DimensionOrderBy;
use Google\Analytics\Data\V1beta\OrderBy\DimensionOrderBy\OrderType;
$property_id = '314116996';
$client = new BetaAnalyticsDataClient();
$params = [
'property' => "properties/{$property_id}",
'dateRanges' => [
new DateRange([
'start_date' => '7daysAgo',
'end_date' => 'yesterday',
]),
new DateRange([
'start_date' => '14daysAgo',
'end_date' => '8daysAgo',
]),
],
'dimensions' => [
new Dimension(['name' => 'nthDay']),
],
'metrics' => [
new Metric(['name' => 'activeUsers']),
],
'orderBys' => [
new OrderBy([
'desc' => false,
'dimension' => new DimensionOrderBy([
'dimension_name' => 'nthDay',
'order_type' => OrderType::NUMERIC,
]),
]),
],
'keepEmptyRows' => true,
'metricAggregations' => [
MetricAggregation::TOTAL,
],
];
$response = $client->runReport($params);
$totals = $response->getTotals();
foreach ($totals as $row) {
foreach ($row->getMetricValues() as $metricValue) {
echo 'Metric Value: '.$metricValue->getValue().PHP_EOL;
}
}
There's a GA4 Dimensions & Metrics Explorer, which can be used to build requests.
When having a request which yields results, it's not so difficult to port it to PHP then.
Dimension name nthDay may actually be ga:nthDay (at least for UA).

Google Calendar API - Create Events to Send Updates

I am trying to add a few 'flags' to my Google Calendar Event. I am using the PHP API. Most specifically I am trying to set the ['sendUpdates'=>'all'] flag, so that whenever the event is modified, all those on the attendees list will get notified. I have tried to add this parameter upon inserting/creating the event. I have also tried using patch. But it does not seem to be working.
Here is some sample code:
$opts = [
'start' => [
'date' => '2021-10-11',
'timeZone' => 'US/Pacific'
],
'end' => [
'date' => '2021-10-11',
'timeZone' => 'US/Pacific'
],
'summary' => 'TEST EVENT',
'description' => 'Test description',
'attendees' => [['email'=>'test#test.com']],
'guestsCanModify' => false,
'guestsCanInviteOthers' => true,
'guestsCanSeeOtherGuests' => true,
'reminders' => [
'useDefault' => true,
],
'sendUpdates' => 'all',
];
$event = new \Google_Service_Calendar_Event($opts);
$new_event = $service->events->insert($calendar_id, $event);
Then after this didn't work, I just tried to 'patch' the event with the following:
$service->events->patch($calendar_id, $new_event['id'], $new_event, ['sendUpdates'=>'all']);
None of this is working to properly set the 'sendUpdates' flag. It DOES create the event. Pretty much ran out of options on how to fix this. Documentation is pretty unclear about how to do this, and can't find much on Stack Overflow or anywhere else.
Anyone have any suggestions?
You are very close to setting the sendUpdates parameter to all. Beforehand you have to keep in mind that sendUpdates is a parameter, not a property. Therefore you should set it in the method, not in the request body. So you only have to modify the script to look like this:
$opts = [
'start' => [
'date' => '2021-10-11',
'timeZone' => 'US/Pacific'
],
'end' => [
'date' => '2021-10-11',
'timeZone' => 'US/Pacific'
],
'summary' => 'TEST EVENT',
'description' => 'Test description',
'attendees' => [['email'=>'test#test.com']],
'guestsCanModify' => false,
'guestsCanInviteOthers' => true,
'guestsCanSeeOtherGuests' => true,
'reminders' => [
'useDefault' => true,
],
];
$optionalParameters = array(
"sendUpdates" => "all"
);
$event = new \Google_Service_Calendar_Event($opts);
$new_event = $service->events->insert($calendar_id, $event, $optionalParameters);

time does not match the format laravel

In my application, I get a validation error when selecting a time from 1 to 9, which is one digit.
The source code is:
$validator = Validator::make($request->all(), [
'service_id' => 'required|integer|exists:services,id',
'origin' => 'required|string|latlng',
'destination' => 'required|string|latlng',
'date' => 'required|date_format:Y-m-d|after_or_equal:today',
'time' => 'required_with:date|date_format:H:i'.($request->get('date') == Carbon::today()->format('Y-m-d') ? '|after:'.Carbon::now()->format('H:i') : '')
]);
and i get this error
{time: {The time does not match the format H:i.]}
Try this
$validator = Validator::make($request->all(), [
'service_id' => 'required|integer|exists:services,id',
'origin' => 'required|string|latlng',
'destination' => 'required|string|latlng',
'date' => 'required|date_format:Y-m-d|after_or_equal:today',
'time' => 'required|date_format:H:i'
]);
I hope this works!

How can I send custom payload paramter with the NotificationPusher component to apple devices?

I am struggling with the usage of the NotificationPusher component and the possibility to send custom parameters within the payload to apple products.
I've tried the following, since I've found this annotation within the docs on github.
$message = new Message("Hello there", [
'message' => [
'sound' => 'default'
],
'custom' => [
'lat' => 123,
'lon' => 321,
'radius' => 32,
'date' => date('Y-m-d H:i:s'),
'action' => 'update'
]
]);
This syntax sadly didn't led to the expected result. The apple devices wouldn't receive these parameters.
I've also tried this, but this also failed.
$message = new Message("Hello there", [
'message' => [
'sound' => 'default',
'custom_lat' => 123,
'custom_lon' => 321,
'custom_radius' => 32,
'custom_date' => date('Y-m-d H:i:s'),
'custom_action' => 'update'
]
]);
What is the exact syntax so send custom parameters within the payload to apple devices with a push message?
I've dug trough the source code on github and have found out, that the 'custom' key of the array wasn't extracted by the ASPN Adapter.
But I've found a piece of code that extracted the complete 'message' array, so my guess was to add the 'custom' array within the 'message' part, what then also was the solution for my problem.
$message = new Message("Hello there", [
'message' => [
'sound' => 'default',
'custom' => [
'lat' => 123,
'lon' => 321,
'radius' => 32,
'date' => date('Y-m-d H:i:s'),
'action' => 'update'
]
]
]);
I faced the same need. Started debugging and found that KhorneHoly is right: You need to send the payload under custom key. The array format is a little bit different, though:
$message = new Message('This is the message', [
'custom'=> [
'payloadKey' => 'payloadContent'
]
]);
I'm using "sly/notification-pusher": "^2.3"
Hope it helps =)

Categories