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 :)
Related
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).
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);
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'])],
I'm trying to change a ranges colour via the Google Sheets API in PHP.
I have done around an hour of researchig. The code below is as far as I've got.
$requests = [
// Change the spreadsheet's title.
new Google_Service_Sheets_Request([
'updateSpreadsheetProperties' => [
'properties' => [
'title' => "The Title"
],
'fields' => 'title'
],
'UpdateCellsRequest' => [
'properties' => [
'range' => "Sheet1!A1",
'backgroundColor' => "#000"
],
'fields' => ''
]
])
];
// Add additional requests (operations) ...
$batchUpdateRequest = new Google_Service_Sheets_BatchUpdateSpreadsheetRequest([
'requests' => $requests
]);
$response = $GoogleSheetsAPIHandler->sheets->spreadsheets->batchUpdate("SHEETID", $batchUpdateRequest);
print_r($response);
If I take out this:
'UpdateCellsRequest' => [
'properties' => [
'range' => "Sheet1!A1",
'backgroundColor' => "#000"
],
'fields' => ''
]
Then the code works to update the sheets title. However, I can't seem to update a ranges colour.
Any advice would be greatly appreciated!
I believe your goal and situation as follows.
You want to change the background color of cells using googleapis for php.
You have already been able to get and put values for Google Spreadsheet using Sheets API.
Modification points:
When you want to use the batchUpdate method of Sheets API, please put each request to each element of the array of requests.
I think that the request body of UpdateCellsRequest in your script is not correct.
From your question of I'm trying to change a ranges colour via the Google Sheets API in PHP., when you want to change the background color of several cells with one color, I think that RepeatCellRequest might be suitable.
In this answer, I would like to propose a modified script for changing the several cells using one color. When your script is modified, it becomes as follows.
Modified script:
Before you use this, please set the sheet ID.
$requests = [
new Google_Service_Sheets_Request([
'updateSpreadsheetProperties' => [
'properties' => [
'title' => "The Title"
],
'fields' => 'title'
]
]),
new Google_Service_Sheets_Request([
'repeatCell' => [
'cell' => [
'userEnteredFormat' => [
'backgroundColor' => [
'red' => 1,
'green' => 0,
'blue' => 0
]
]
],
'range' => [
'sheetId' => $sheetId, // <--- Please set the sheet ID.
'startRowIndex' => 0,
'endRowIndex' => 3,
'startColumnIndex' => 0,
'endColumnIndex' => 2
],
'fields' => 'userEnteredFormat'
]
])
];
When above request body is used for the batchUpdate method of Sheets API, the title of Spreadsheet is changed and the background color of the cells "A1:B3" changed to the red color.
Wne you want to use UpdateCellsRequest, you can use the following request body. At the following request body, the background colors of cells "A1:B1" are changed to red and green colors, respectively. When UpdateCellsRequest is used, each cell can be updated. About the detail information of UpdateCellsRequest, please check the official document. Ref
$requests = [
new Google_Service_Sheets_Request([
'updateCells' => [
'rows' => array([
'values' => array(
['userEnteredFormat' => [
'backgroundColor' => [
'red' => 1,
'green' => 0,
'blue' => 0
]
]],
['userEnteredFormat' => [
'backgroundColor' => [
'red' => 0,
'green' => 1,
'blue' => 0
]
]]
)
]),
'range' => [
'sheetId' => $sheetId, // <--- Please set the sheet ID.
'startRowIndex' => 0,
'startColumnIndex' => 0,
],
'fields' => 'userEnteredFormat'
]
])
];
References:
UpdateCellsRequest
RepeatCellRequest
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 =)