Overview:
Sometimes you want to track some certain stats for your website i.e pageviews and user count, etc. integrated to your website for that Google Analytics provides a Reporting API to add this functionality to your website. So let’s see how to implement this first on PHP.
Prerequisite:
- Google Analytics View ID.
- Need a Google Developer Service Account to communicate with Google Analytics.
Creating a Service Account
- If you have a project then you can continue with that also or you can create a new project.
- We are creating a new project so click on Create Project.
- Enter Project Name and Organization Name.
- After the project is created, click on Create Service Account.
- Enter service account details and click on create.
- After that, select the service account permission according to your requirement. It is optional. You can just leave it blank.
- Once your service account is created then you have to create a private key for it. Go to the action option and select create key option and select the key format according to your requirement and click on create. (recommended type is JSON)
- After the key is created it is downloaded to your local machine. Store it in a separate folder.
- Now let’s search for “Google Analytics API” in the top search bar and enable it.
- Now Add service account to Google Analytics.
- Open the Google Analytics account and click on the Admin tab at the left bottom corner.
- Click on View User Management on the view panel.
- Click on the (+) icon and click on add users.
- Now you will be prompted to enter an email address, go to your service account, and copy your email from the newly created service account.
- Paste this email to the Google Analytics page and click on add from the top right corner.
EXECUTE THE CODE
- Modify the downloaded code and replace KEY_FILE_LOCATION with our json file name.
- Run the code file you will get the no. of sessions as a result.
- if you want start date and end date and other dimensions and metrics like pageviews, total user, and so on just modify the getResults() function or create your own function like this
function getResults($analytics, $profileId) { // Calls the Core Reporting API and queries for the number of sessions // for the last seven days. return $analytics->data_ga->get( 'ga:' . $profileId, '2019-12-31',// start date 'today',// end date 'ga:pageviews');// dimensions and metrics }
Navigate to this link for more information on Dimensions and Metrics.
NOTE: if you also get the warning like this
Warning: count(): Parameter must be an array or an object that implements Countable in C:\xampp\htdocs\User\Demo\GoogleAnalyticsDemo\vendor\guzzlehttp\guzzle\src\Handler\CurlFactory.php on line 67.
The problem for this warning is because PHP version 7.2 count() parameter can’t accept NULL. The warning gets displayed when $this->handles equals NULL.
you can turn off the warning message in your php file or you can replace line 67 in “vendor\guzzlehttp\guzzle\src\Handler\CurlFactory.php” with the following code:
if (($this->handles ? count($this->handles) : 0) >= $this->maxHandles) {
For more information on this warning, you can check the issue id #1392 on github.
LARAVEL
- Create a new service account. The steps to create a service account are covered above on #step1-on-PHP or you can use the same credentials.
- To implement google analytics on laravel you have to use the laravel package named spatie/laravel-analytics created by spatie or you can download it from composer:
composer require spatie/laravel-analytics - After installing the package publish the vendor folder:
php artisan vendor:publish –provider=”Spatie\Analytics\AnalyticsServiceProvider” - Set a new environment variable named ANALYTICS_VIEW_ID. You can find your Analytics View ID by visiting the Google Analytics admin tab and selecting the View Setting on the view panel.
- Create folder analytics inside “storage/app” and move your downloaded JSON file to it.
- Add these two namespaces where you want to call the analytics methods. We are using this directly from our web.php route file so we import these namespaces at top of web.php
use Spatie\Analytics\AnalyticsFacade as Analytics;
use Spatie\Analytics\Period; - Open a web.php route file and define one clouser function and write the method for retrieving the pageview.
Analytics::fetchVisitorsAndPageViews(Period::days(7)); - You can learn more about methods provided for analytics data by spatie.
Conclusion
I hope that you will find this blog helpful for implementing the google analytics data into your website.