/** * Initializes an Analytics Reporting API V4 service object. * * @return An authorized Analytics Reporting API V4 service object. */ function initializeAnalytics() {
// Use the developers console and download your service account // credentials in JSON format. Place them in this directory or // change the key file location if necessary. $KEY_FILE_LOCATION = __DIR__ . '/service-account-credentials.json';
// Create and configure a new client object. $client = new Google_Client(); $client->setApplicationName("Hello Analytics Reporting"); $client->setAuthConfig($KEY_FILE_LOCATION); $client->setScopes(['https://www.googleapis.com/auth/analytics.readonly']); $analytics = new Google_Service_AnalyticsReporting($client);
return $analytics; }
/** * Queries the Analytics Reporting API V4. * * @param service An authorized Analytics Reporting API V4 service object. * @return The Analytics Reporting API V4 response. */ function getReport($analytics) {
// Replace with your view ID, for example XXXX. $VIEW_ID = "<REPLACE_WITH_VIEW_ID>";
// Create the DateRange object. $dateRange = new Google_Service_AnalyticsReporting_DateRange(); $dateRange->setStartDate("7daysAgo"); $dateRange->setEndDate("today");
// Create the Metrics object. $sessions = new Google_Service_AnalyticsReporting_Metric(); $sessions->setExpression("ga:sessions"); $sessions->setAlias("sessions");
// Create the ReportRequest object. $request = new Google_Service_AnalyticsReporting_ReportRequest(); $request->setViewId($VIEW_ID); $request->setDateRanges($dateRange); $request->setMetrics(array($sessions));