I'm trying to automatise the Google analytics report of our app websites, something like 55 or so.
What I need is:
avg time
users new/returning
direct/referral/search
users per day (based on 1st of the month to the last day)
I'm using the guide from Google
https://developers.google.com/analytics/devguides/reporting/core/v4/quickstart/web-php
my function for the report is something like this:
function getReport($analytics) {
// Replace with your view ID, for example XXXX.
$VIEW_ID = "XXXX";
// Create the DateRange object.
$dateRange = new Google_Service_AnalyticsReporting_DateRange();
$dateRange->setStartDate("2019-05-01");
$dateRange->setEndDate("2019-05-31");
// Create the Metrics object.
$sessions = new Google_Service_AnalyticsReporting_Metric();
$sessions->setExpression("ga:sessions");
$sessions->setAlias("sessions");
$users = new Google_Service_AnalyticsReporting_Metric();
$users->setExpression("ga:users");
$users->setAlias("users");
$newSessions = new Google_Service_AnalyticsReporting_Metric();
$newSessions->setExpression("ga:percentNewSessions");
$newSessions->setAlias("newSessions");
// Create the ReportRequest object.
$request = new Google_Service_AnalyticsReporting_ReportRequest();
$request->setViewId($VIEW_ID);
$request->setDateRanges($dateRange);
$request->setMetrics(array($sessions,$users,$newSessions));
$body = new Google_Service_AnalyticsReporting_GetReportsRequest();
$body->setReportRequests( array( $request) );
return $analytics->reports->batchGet( $body );
}
Of course is not the definitely one I'm just experimenting with some metrics.
I was trying to get back the users per day like this
$monthusers = new Google_Service_AnalyticsReporting_Metric();
$monthusers->setExpression("ga:30dayUsers");
$monthusers->setAlias("monthusers");
and then in the request
$request->setMetrics(array($sessions,$users,$newSessions,$monthusers));
but it throw a 500 error, any idea on how to get back the users per day? and based on the:
$dateRange->setStartDate("2019-05-01");
$dateRange->setEndDate("2019-05-31");
As per mentioned in the Dimensions & Metrics Explorer for the metric "ga:30dayUsers":
At least one of ga:nthDay, ga:date, or ga:day must be specified as a
dimension to query this metric.
You could use the ga:day dimension into your report request to solve the issue:
$day = new Google_Service_AnalyticsReporting_Dimension();
$day->setName("ga:day");
$request->setDimensions(array($day));
Related
How can I get locations list in Google My Business API. Where I retrieved account list but I can't figure out how to retrieve location.
Here is my code where I am getting accounts list
define('GOOGLE_CLIENT_ID', 'XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX');
define('GOOGLE_CLIENT_SECRET', 'XXXXXXXXXXXXX');
// Create Client Request to access Google API
$client = new Client();
$client->setApplicationName('my-app');
$client->setClientId(GOOGLE_CLIENT_ID);
$client->setClientSecret(GOOGLE_CLIENT_SECRET);
$client->setRedirectUri('https://example.com/callback');
$client->addScope('https://www.googleapis.com/auth/userinfo.profile https://www.googleapis.com/auth/business.manage');
$client->setAccessType('offline'); // offline access
$client->setIncludeGrantedScopes(true); // incremental auth
$client->setAccessToken($accessToken);
$service = new \Google_Service_MyBusinessAccountManagement($client);
$accounts = $service->accounts->listAccounts()->getAccounts(); // get accounts
To get google locations,
you can use this PHP My Business file to make things little easier.
First change you scope to ttps://www.googleapis.com/auth/plus.business.manage then include the file and create a object of Google_Service_MyBusiness with you client and then do like this.
$mybusinessService = new Google_Service_MyBusiness($client);
// Get the first account in the accounts array
$accounts = $mybusinessService->accounts;
$accountsList = $accounts->listAccounts()->getAccounts();
$account = $accountsList[0];
// Get the first location in the locations array
$locations = $mybusinessService->accounts_locations;
$locationsList = $locations->listAccountsLocations($account->name)->getLocations();
$location = $locationsList[0];
var_export($location);
With this process you can also able to get google reviews.
For more details check this Google Business API documentation.
Hope it can help
"It's correct!!!
I increase this at my code:
$optParams = array(
'readMask' => 'name',
);
$list_accounts_response = $my_business_account->accounts_locations->listAccountsLocations("accounts/114893266195214446586", $optParams);
var_dump($list_accounts_response);
Thank you.."
source : https://github.com/googleapis/google-api-php-client/issues/2213#issuecomment-1042785983
I'm currently trying to obtain a list of the three most read articles on my site, using the Google Analytics Reporting API v4.
Currently, I have been able to request a list of all pages with the number of pageviews each one got in the past 30 days, and filter them by pageview.
But now I'm stuck (after browsing for answers for multiple hours) to filter so only pagepaths that include /artikels/ are shown, and limit the list to 3 results.
My current code:
function getReport($analytics) {
// Replace with your view ID, for example XXXX.
$VIEW_ID = "XXXXXXX";
// Create the DateRange object.
$dateRange = new Google_Service_AnalyticsReporting_DateRange();
$dateRange->setStartDate("30daysAgo");
$dateRange->setEndDate("today");
// Create the Metrics object.
$sessions = new Google_Service_AnalyticsReporting_Metric();
$sessions->setExpression("ga:pageviews");
$sessions->setAlias("sessions");
//Create the Dimensions object.
$pagepath = new Google_Service_AnalyticsReporting_Dimension();
$pagepath->setName("ga:pagePath");
$ordering = new Google_Service_AnalyticsReporting_OrderBy();
$ordering->setOrderType("VALUE");
$ordering->setFieldName("ga:pageviews");
$ordering->setSortOrder("DESCENDING");
// Create the ReportRequest object.
$request = new Google_Service_AnalyticsReporting_ReportRequest();
$request->setViewId($VIEW_ID);
$request->setDateRanges($dateRange);
$request->setDimensions(array($pagepath));
$request->setOrderBys($ordering);
$request->setMetrics(array($sessions));
$body = new Google_Service_AnalyticsReporting_GetReportsRequest();
$body->setReportRequests( array( $request) );
return $analytics->reports->batchGet( $body );
}
Could anyone please help? There is a ton of information about v3, but can't seem to find enough information about v4.
Thank you!
Very "green" when dealing with the AdWords API. Could someone assist in how to use ORDER BY .. specifically ORDER BY 'Month'?
public static function runExample(AdWordsServices $adWordsServices,
AdWordsSessionBuilder $sessionBuilder, $reportDir) {
// Construct an API session for the client customer ID specified in the
// configuration file.
$session = $sessionBuilder->build();
// Create selector.
$selector = new Selector();
$selector->setFields(['Month', 'Impressions', 'Clicks', 'Ctr', 'AverageCpc', 'AveragePosition', 'Cost', 'Conversions', 'CostPerConversion', 'ConversionRate', 'SearchImpressionShare']);
$From = date('Ym01', strtotime("-5 months"));
$To = date('Ymt', strtotime("-0 months"));
$selector->setDateRange(new DateRange($From, $To));
// Use a predicate to filter out paused criteria (this is optional).
//$selector->setPredicates([
//new Predicate('Impressions', PredicateOperator::GREATER_THAN, [1000]),
//new Predicate('CampaignName', PredicateOperator::CONTAINS, ['Branded'])
//]);
// Create report definition.
$reportDefinition = new ReportDefinition();
$reportDefinition->setSelector($selector);
$reportDefinition->setReportName('MOM ACCOUNT_PERFORMANCE_REPORT');
$reportDefinition->setDateRangeType(
ReportDefinitionDateRangeType::CUSTOM_DATE);
$reportDefinition->setReportType(
ReportDefinitionReportType::ACCOUNT_PERFORMANCE_REPORT);
$reportDefinition->setDownloadFormat(DownloadFormat::CSV);
$customerIds = self::getAllManagedCustomerIds($adWordsServices, $session);
printf("Downloading reports for %d managed customers.\n",
count($customerIds));
I am assuming ORDER BY goes inside of the selector?
I was helped on another forum....see below.
use Google\AdsApi\AdWords\v201705\cm\SortOrder;
use Google\AdsApi\AdWords\v201705\cm\OrderBy;
.
.
$selector->setOrdering([new OrderBy('Name', SortOrder::ASCENDING)]); //sort by
Name
I am working on an application that in which I need to integrate google analytics API with PHP.
Here's the link for the API documentation Google Analytics Core Reporting API, currently I'm facing an overload issue.
At our application we need to form a graph for selected daterange. For example session count. API has option for parameters like start & end data but in response it only provides average / total of session counts / page load time. But for generating graph we do need data of each day in the given date range. e.g. 1 jan to 30th jan of 2015, for this case we have to send 30 requests for individual day & get the data for the graph with this method. Is there any possible way in which we can reduce request count or get data in date format?
We are collecting many metrics like Average page load time, Organic Sessions etc. which is making it 180-210 request on page load to google API itself & sometimes it throws an error that too much utilization of resources from google.
You can add the ga:date dimension. It will break out the value for each metric for every date within the date range:
In JSON
{
"reportRequests":
[
{
"dimensions":
[
{
"name": "ga:date"
}
],
"metrics":
[
{
"expression": "ga:sessions"
},
{
"expression": "ga:avgpageloadtime"
}
],
"viewId": "XXXX",
"dateRanges":
[
{
"startDate": "7daysAgo",
"endDate": "yesterday"
}
]
}
]
}
In PHP
// Create the DateRange object.
$dateRange = new Google_Service_Analyticsreporting_DateRange();
$dateRange->setStartDate("7DaysAgo");
$dateRange->setEndDate("yesterday");
// Create the Metrics objects.
$sessions = new Google_Service_Analyticsreporting_Metric();
$sessions->setExpression("ga:sessions");
$avgpageloadtime = new Google_Service_Analyticsreporting_Metric();
$avgpageloadtime->setExpression("ga:avgpageloadtime");
//Create the Dimensions object.
$date = new Google_Service_Analyticsreporting_Dimension();
$date->setName("ga:date");
// Create the ReportRequest object.
$request = new Google_Service_Analyticsreporting_ReportRequest();
$request->setViewId("XXXX");
$request->setDateRanges($dateRange);
$request->setDimensions(array($date));
$request->setMetrics(array($sessions, $avgpageloadtime));
$body = new Google_Service_Analyticsreporting_GetReportsRequest();
$body->setReportRequests( array( $request) );
return $analyticsreporting->reports->batchGet( $body );
We have a PHP application and when we create an event in Google Calendar using de API, this event is generated without Hangout Link, but if we create the event manually, the event is created with the Hangout Link. The option to create automatically hangouts when we create an event is checked.
The code is:
$event = new Google_Service_Calendar_Event();
$event->setSummary($summary);
$event->setLocation('hangout');
$start = new Google_Service_Calendar_EventDateTime();
$start->setDateTime($startDate->format(\DateTime::ISO8601));
$event->setStart($start);
$end = new Google_Service_Calendar_EventDateTime();
$end->setDateTime($endDate->format(\DateTime::ISO8601));
$event->setEnd($end);
$attendee1 = new Google_Service_Calendar_EventAttendee();
$attendee1->setEmail($this->masterAccount);
$attendees= [];
$attendees[] = $attendee1;
foreach($company->getUsers()->toArray() as $user){
$attendee1 = new Google_Service_Calendar_EventAttendee();
$attendee1->setEmail($user->getEmail());
$attendees[] = $attendee1;
}
$event->attendees = $attendees;
$createdEvent = $this->google_calendar_service->events->insert($company->getCalendar()->getCalendarId(), $event);
If we use the form https://developers.google.com/google-apps/calendar/v3/reference/events/insert#try-it to create de Event, the hangout link is created without problems.
Any solutions?
Thanks :)
I know this topic is a bit old, but there are many people still struggling with making Calendar API work. After countless forums visited, hours of reading documentation and hitting my head against the wall I finally figured out, the key element is to set requestId.
In the time i've implemented this, this parameter wasn't mandatory and i skipped it.
Thats being said, my request looks like this:
$event = new Google_Service_Calendar_Event(); //creating empty event
$event->setSummary("Staff meeting"); //title
$event->setLocation("Room 101"); //location
$event->setDescription("We will talk about salary raise!"); //description
$event->setColorId(9); //make it shine by setting color
$start = new Google_Service_Calendar_EventDateTime();
$start->setDateTime($startDate->format(DateTime::ISO8601));
$start->setTimeZone('Europe/Warsaw');
$event->setStart($start); //set start
$end = new Google_Service_Calendar_EventDateTime();
$end->setDateTime($endDate->format(DateTime::ISO8601));
$end->setTimeZone('Europe/Warsaw');
$event->setEnd($end); //set end
$event->setGuestsCanSeeOtherGuests(false); //I dont want others to see who's invited
$event->setGuestsCanModify(false); //I dont want others to modify event
$event->setGuestsCanInviteOthers(false); //I dont want others to invite
$event->setAnyoneCanAddSelf(false); //I allow only people invited by me, not some strangers walking by
//this part should be executed in loop, for every guest
$attendee = new Google_Service_Calendar_EventAttendee();
$attendee->setEmail("staffmeber1#mywebsite.com");
$attendee->setResponseStatus('accepted');
$attendees[] = $attendee;
//When the list is completed, set guests in event
$event->setAttendees($attendees);
//The most important part about creating hangout
$conferenceData = new Google_Service_Calendar_ConferenceData(); //defining we have conference
$req = new Google_Service_Calendar_CreateConferenceRequest(); //requesting google to create video meeting
$req->setRequestId("req_".time()); //some random string/number changed every call. according to docs subsequent calls with the same request id are ignored
$conferenceData->setCreateRequest($req); //set request for videoconference in conference data
$event->setConferenceData($conferenceData); //set conference data in out event
$creator = new Google_Service_Calendar_EventCreator();
$creator->setDisplayName("Big boss");
$creator->setEmail('boss#mywebsite.com');
$event->setCreator($creator);
$event->setStatus('confirmed'); //lets say everyone is attending :D
$result = $this->calendarClient->events->insert($this->calendarObject->getId(), $event, ['conferenceDataVersion' => 1, 'sendUpdates' => "none"]); //dont forget about conferenceDataVersion or every conference data will be ignored
Working with Python here also faced issue, of events not being created with Hangouts. It seems settings can not be changed from program, but as SGC pointed out, I just changed google calendar settings from UI to add hangouts on every event created.