Skip to content

Commit

Permalink
Merge pull request #4 from wintercms/wip/ga4-support
Browse files Browse the repository at this point in the history
Add Google Analytics 4 support
  • Loading branch information
bennothommo committed Nov 30, 2022
2 parents 2355d53 + 79746a9 commit 0ff0d09
Show file tree
Hide file tree
Showing 26 changed files with 593 additions and 155 deletions.
14 changes: 14 additions & 0 deletions assets/css/placeholder.css
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
img.placeholder {
width: 100%;
height: 100%;
animation: placeholderFade 750ms infinite linear alternate;
}

@keyframes placeholderFade {
0% {
opacity: 0.25;
}
100% {
opacity: 0.85;
}
}
28 changes: 28 additions & 0 deletions assets/images/bar-graph-placeholder.svg
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
12 changes: 12 additions & 0 deletions assets/images/goal-placeholder.svg
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
36 changes: 36 additions & 0 deletions assets/images/line-graph-placeholder.svg
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
22 changes: 22 additions & 0 deletions assets/images/pie-graph-placeholder.svg
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
27 changes: 27 additions & 0 deletions assets/images/table-placeholder.svg
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
23 changes: 10 additions & 13 deletions classes/Analytics.php
Original file line number Diff line number Diff line change
@@ -1,25 +1,22 @@
<?php namespace Winter\GoogleAnalytics\Classes;

use App;
use Config;
use Google_Client;
use Google_Cache_File;
use Google_Service_Analytics;
use Google_Auth_AssertionCredentials;
use ApplicationException;
use Google\Client;
use Google\Service\AnalyticsData;
use Winter\GoogleAnalytics\Models\Settings;

class Analytics
{
use \Winter\Storm\Support\Traits\Singleton;

/**
* @var Google_Client Google API client
* @var \Google\Client Google API client
*/
public $client;

/**
* @var Google_Service_Analytics Google API analytics service
* @var \Google\Service\AnalyticsData Google API analytics service
*/
public $service;

Expand All @@ -39,7 +36,7 @@ protected function init()
throw new ApplicationException(trans('winter.googleanalytics::lang.strings.keynotuploaded'));
}

$client = new Google_Client();
$client = new Client();

/*
* Set caching
Expand All @@ -52,14 +49,14 @@ protected function init()
*/
$auth = json_decode($settings->gapi_key->getContents(), true);
$client->setAuthConfig($auth);
$client->addScope(Google_Service_Analytics::ANALYTICS_READONLY);
$client->addScope(AnalyticsData::ANALYTICS_READONLY);

if ($client->isAccessTokenExpired()) {
$client->refreshTokenWithAssertion();
$client->fetchAccessTokenWithAssertion();
}

$this->client = $client;
$this->service = new Google_Service_Analytics($client);
$this->viewId = 'ga:'.$settings->profile_id;
$this->service = new AnalyticsData($client);
$this->viewId = 'properties/' . $settings->profile_id;
}
}
}
17 changes: 16 additions & 1 deletion lang/en/lang.php
Original file line number Diff line number Diff line change
Expand Up @@ -16,14 +16,20 @@
'traffic_goal_goal_validation' => 'Please specify the traffic goal as an integer value.',
'title_traffic_overview' => 'Traffic overview',
'title_traffic_sources' => 'Traffic Sources',
'description_traffic_sources' => 'The traffic sources report displays the source of referrals to your website.',
'description_traffic_sources' => 'The traffic sources report displays the source from where visitors entered the site.',
'traffic_sources_report_size' => 'Chart radius',
'traffic_sources_report_size_validation' => 'Please specify the chart size as an integer value',
'traffic_sources_center' => 'Center the chart',
'traffic_sources_number' => 'Number of sources to display',
'display_description' => 'Display the report description',
'days' => 'Number of days to display data for',
'legend_as_table' => 'Display legend as a table',
'metrics' => 'Metrics',
'metric_sessions' => 'Sessions',
'metric_activeUsers' => 'Users',
'metric_screenPageViews' => 'Page views',
'device_split' => 'Split by device',
'device_split_description' => 'If ticked, visits will also be split by device type, such as desktop, mobile or tablet.',
],
'permissions' => [
'tab' => 'Google Analytics Plugin',
Expand All @@ -40,8 +46,10 @@
'settings_desc' => 'Configure Google Analytics API code and tracking options.',
'page_url' => 'Page URL',
'pageviews' => 'Pageviews',
'users' => 'Users',
'current' => 'Current',
'goal' => 'Goal',
'engagement' => 'Engagement',
],
'settings' => [
'project_name' => 'Google API Project name',
Expand All @@ -63,4 +71,11 @@
'force_ssl' => 'Force SSL',
'force_ssl_comment' => 'Always use SSL to send data to Google',
],
'mediums' => [
'organic' => 'Search engines',
'cpc' => 'Paid search click-throughs',
'direct' => 'Direct traffic',
'referral' => 'External sites',
'unknown' => 'Unknown',
],
];
4 changes: 2 additions & 2 deletions readme.md
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
# Google Analytics V3 integration plugin
# Google Analytics V4 integration plugin

This plugin adds Google Analytics tracking and reporting features to the [Winter CMS](https://wintercms.com).

> **Note**: This plugin does not support GAv4. If you are having issues creating an account, use the **Show advanced options** link in the GA Account creation and the **Create a Universal Analytics property** switch.
> **Note**: The v3.x series of this plugin only supports Google Analytics v4 (GA4) as GA3 / UA [are being retired](https://support.google.com/analytics/answer/11583528?hl=en). If you wish to use this plugin for GA3 / UA, you must roll back to v2.0.2 of this plugin.
## Configuration

Expand Down
92 changes: 79 additions & 13 deletions reportwidgets/Browsers.php
Original file line number Diff line number Diff line change
@@ -1,9 +1,17 @@
<?php namespace Winter\GoogleAnalytics\ReportWidgets;

use Exception;
use Backend\Classes\ReportWidgetBase;
use Google\Service\AnalyticsData\ConcatenateExpression;
use Google\Service\AnalyticsData\DateRange;
use Google\Service\AnalyticsData\Dimension;
use Google\Service\AnalyticsData\DimensionExpression;
use Google\Service\AnalyticsData\Metric;
use Google\Service\AnalyticsData\MetricOrderBy;
use Google\Service\AnalyticsData\OrderBy;
use Google\Service\AnalyticsData\RunReportRequest;
use Winter\GoogleAnalytics\Classes\Analytics;
use ApplicationException;
use Exception;
use Winter\Storm\Argon\Argon;

/**
* Google Analytics browsers overview widget.
Expand All @@ -17,15 +25,23 @@ class Browsers extends ReportWidgetBase
* Renders the widget.
*/
public function render()
{
$this->addCss('/plugins/winter/googleanalytics/assets/css/placeholder.css', 'Winter.GoogleAnalytics');

return $this->makePartial('widget');
}

public function onLoad()
{
try {
$this->loadData();
}
catch (Exception $ex) {
} catch (Exception $ex) {
$this->vars['error'] = $ex->getMessage();
}

return $this->makePartial('widget');
return [
'#' . $this->alias => $this->makePartial('report')
];
}

public function defineProperties()
Expand All @@ -52,26 +68,76 @@ public function defineProperties()
],
'days' => [
'title' => 'winter.googleanalytics::lang.widgets.days',
'default' => '7',
'default' => '30',
'type' => 'string',
'validationPattern' => '^[0-9]+$'
],
'displayDescription' => [
'title' => 'winter.googleanalytics::lang.widgets.display_description',
'type' => 'checkbox',
'default' => 1
]
],
'deviceSplit' => [
'title' => 'winter.googleanalytics::lang.widgets.device_split',
'description' => 'winter.googleanalytics::lang.widgets.device_split_description',
'type' => 'checkbox',
'default' => 0
],
];
}

protected function loadData()
{
$days = $this->property('days');
if (!$days)
throw new ApplicationException('Invalid days value: '.$days);
$analytics = Analytics::instance();

$days = $this->property('days', 30);

// Formulate data request
$request = new RunReportRequest();
$now = Argon::now()->toImmutable();
if (boolval($this->property('deviceSplit', 0)) === true) {
$request->setDimensions([
new Dimension([
'name' => 'browserDevice',
'dimensionExpression' => new DimensionExpression([
'concatenate' => new ConcatenateExpression([
'delimiter' => ' - ',
'dimensionNames' => [
'browser',
'deviceCategory',
],
]),
]),
]),
]);
} else {
$request->setDimensions([
new Dimension(['name' => 'browser']),
]);
}
$request->setMetrics([
new Metric(['name' => 'sessions']),
]);
$request->setDateRanges([
new DateRange([
'startDate' => $now->subDays($days)->format('Y-m-d'),
'endDate' => $now->format('Y-m-d')
])
]);
$request->setOrderBys([
new OrderBy([
'desc' => true,
'metric' => new MetricOrderBy([
'metricName' => 'sessions',
])
]),
]);

$data = $analytics->service->properties->runReport(
$analytics->viewId,
$request,
);

$obj = Analytics::instance();
$data = $obj->service->data_ga->get($obj->viewId, $days.'daysAgo', 'today', 'ga:visits', ['dimensions'=>'ga:browser', 'sort'=>'-ga:visits']);
$this->vars['rows'] = $data->getRows();
$this->vars['rows'] = $data->getRows() ?: [];
}
}
Loading

0 comments on commit 0ff0d09

Please sign in to comment.