Google analytics
Google analytics, (*1)
Installation
The preferred way to install this extension is through composer., (*2)
Either run, (*3)
php composer.phar require --prefer-dist infoweb-internet-solutions/yii2-cms-analytics "*"
or add, (*4)
"infoweb-internet-solutions/yii2-cms-analytics": "*"
to the require section of your composer.json
file., (*5)
Go to the Google developers console, (*6)
Create a new project (or use an existing project), (*7)
Open the project, (*8)
Go to 'API & Auth -> API's' and enable the 'Analytics API', (*9)
Go to 'API & Auth -> Credentials' and under 'OAuth' click 'Create new Client ID', (*10)
Choose 'Service account' and click 'Create client id', (*11)
Save the certificate to 'backend\assets\certificate\certificate.p12' (don't forget to rename the file), (*12)
Write down the 'private key's password' somewhere, (*13)
Add the credentials to your backend params, (*14)
return [
...
'analytics' => [
'developerKey' => '', // Public key fingerprints
'serviceAccountName' => 'xxx@developer.gserviceaccount.com', // Email address
'clientId' => 'xxx.apps.googleusercontent.com', // Client ID
],
];
Go to Google analytics, open your property and get your 'Profile ID', (*15)
(It is the number at the end of the URL starting with p: https://www.google.com/analytics/web/#home/a11345062w43527078pXXXXXXXX/), (*16)
Add the 'Profile ID' to your params, (*17)
return [
...
'analytics' => [
...
'analyticsId' => 'ga:XXXXXXXX',
],
];
Add the serviceAccountName (xxx@developer.gserviceaccount.com) as a new user to your Analyics property, (*18)
Create the alias '@google/api' in the bootstrap file in common/config like so:, (*19)
Yii::setAlias('google/api', dirname(dirname(__DIR__)) . '/vendor/google/apiclient/src');
Import the translations and use category 'infoweb/analytics':, (*20)
yii i18n/import @infoweb/analytics/messages
If you can't access the /tmp
folder on your server (shared hosting), change line 94 in vendor\google\apiclient\src\Google\
, (*21)
'directory' => dirname(Yii::getAlias('@webroot')) . '/runtime/Google_Client'
Usage
Once the extension is installed, replace the contents of backend/views/site/index.php
with the following:, (*22)
title = Yii::$app->name;
?>
= Analytics::widget(['dataType' => Analytics::TOTAl_SESSIONS]); ?>
= Analytics::widget(['dataType' => Analytics::TOTAL_USERS]); ?>
= Analytics::widget(['dataType' => Analytics::TOTAL_PAGE_VIEWS]); ?>
= Analytics::widget(['dataType' => Analytics::AVERAGE_SESSION_LENGTH]); ?>
= Analytics::widget(['dataType' => Analytics::SESSIONS]); ?>
= Analytics::widget(['dataType' => Analytics::VISITORS]); ?>
= Analytics::widget(['dataType' => Analytics::COUNTRIES]); ?>
Useful links
Google Analytics Query Explorer 2
Google API Php Client
Developer Documentation
Google Charts, (*23)