├── CHANGELOG.md ├── config └── analytics.php ├── src ├── Facades │ └── Analytics.php ├── Core │ ├── MaxResults.php │ ├── ReportRequest.php │ ├── Dimension.php │ ├── DateRange.php │ ├── Metric.php │ ├── Order.php │ ├── AnalyticsReporting.php │ ├── Client.php │ ├── DimensionFilter.php │ └── Renderable.php ├── Builder │ ├── GoogleAnalyticsBuilder.php │ ├── Director.php │ └── AnalyticsBuilder.php ├── Contracts │ └── Analytics.php ├── GoogleAnalyticsServiceProvider.php └── Analytics.php ├── composer.json ├── LICENSE └── README.md /CHANGELOG.md: -------------------------------------------------------------------------------- 1 | # Release Notes 2 | 3 | ## v1.0.0 (22/12/16) 4 | 5 | * First working release 6 | -------------------------------------------------------------------------------- /config/analytics.php: -------------------------------------------------------------------------------- 1 | env('GOOGLE_ANALYTICS_VIEW_ID'), 7 | 8 | 'credentials_json_file' => storage_path('app/google-analytics/service-account-credentials.json'), 9 | 10 | ]; 11 | -------------------------------------------------------------------------------- /src/Facades/Analytics.php: -------------------------------------------------------------------------------- 1 | set($maxResults, $request->get()); 10 | } 11 | 12 | private function set(int $maxResults, $request) 13 | { 14 | $request->setPageSize($maxResults); 15 | } 16 | } 17 | -------------------------------------------------------------------------------- /src/Core/ReportRequest.php: -------------------------------------------------------------------------------- 1 | create(); 14 | } 15 | 16 | private function create() 17 | { 18 | $this->request = new Google_Service_AnalyticsReporting_ReportRequest(); 19 | } 20 | 21 | public function get() 22 | { 23 | return $this->request; 24 | } 25 | } 26 | -------------------------------------------------------------------------------- /src/Core/Dimension.php: -------------------------------------------------------------------------------- 1 | create($dimension); 12 | $this->set($request->get()); 13 | } 14 | 15 | private function create(array $dimensions) 16 | { 17 | foreach ($dimensions as $dimension) { 18 | $this->dimension[]['name'] = $dimension; 19 | } 20 | } 21 | 22 | private function set($request) 23 | { 24 | $request->setDimensions($this->dimension); 25 | } 26 | } 27 | -------------------------------------------------------------------------------- /src/Core/DateRange.php: -------------------------------------------------------------------------------- 1 | create($dateRange); 14 | $this->set($request->get()); 15 | } 16 | 17 | private function create(array $dateRange) 18 | { 19 | $this->dateRange = new Google_Service_AnalyticsReporting_DateRange(); 20 | $this->dateRange->setStartDate($dateRange['startDate']); 21 | $this->dateRange->setEndDate($dateRange['endDate']); 22 | } 23 | 24 | private function set($request) 25 | { 26 | $request->setDateRanges($this->dateRange); 27 | } 28 | } 29 | -------------------------------------------------------------------------------- /src/Core/Metric.php: -------------------------------------------------------------------------------- 1 | create($metrics); 14 | $this->set($request->get()); 15 | } 16 | 17 | private function create(array $metrics) 18 | { 19 | foreach ($metrics as $index => $metric) { 20 | $session = new Google_Service_AnalyticsReporting_Metric(); 21 | $session->setExpression($metric); 22 | $this->metric[$index] = $session; 23 | } 24 | } 25 | 26 | private function set($request) 27 | { 28 | $request->setMetrics($this->metric); 29 | } 30 | } 31 | -------------------------------------------------------------------------------- /src/Builder/GoogleAnalyticsBuilder.php: -------------------------------------------------------------------------------- 1 | create($order); 14 | $this->set($request->get()); 15 | } 16 | 17 | public function create(array $order) 18 | { 19 | $this->ordering = new Google_Service_AnalyticsReporting_OrderBy(); 20 | $this->ordering->setFieldName($order['fieldName']); 21 | $this->ordering->setOrderType($order['orderType']); 22 | $this->ordering->setSortOrder($order['sortType']); 23 | } 24 | 25 | public function set($request) 26 | { 27 | $request->setOrderBys($this->ordering); 28 | } 29 | } 30 | -------------------------------------------------------------------------------- /src/GoogleAnalyticsServiceProvider.php: -------------------------------------------------------------------------------- 1 | publishes([ 17 | __DIR__.'/../config/analytics.php' => config_path('analytics.php'), 18 | ]); 19 | } 20 | 21 | /** 22 | * Register the application services. 23 | * 24 | * @return void 25 | */ 26 | public function register() 27 | { 28 | $this->app->bind('analytics', function ($app) { 29 | return new Analytics($app); 30 | }); 31 | 32 | $this->app->bind( 33 | 'Panakour\Analytics\Contracts\Analytics', 34 | 'Panakour\Analytics\Analytics' 35 | ); 36 | } 37 | } 38 | -------------------------------------------------------------------------------- /composer.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "panakour/analytics", 3 | "description": "Get whatever data you want from google analytics.", 4 | "keywords": ["laravel", "analytics"], 5 | "license": "MIT", 6 | "authors": [ 7 | { 8 | "name": "Panagiots Koursaris", 9 | "email": "panakourweb@gmail.com" 10 | } 11 | ], 12 | "require": { 13 | "php": ">=7.1", 14 | "illuminate/support": "~5.5.0|~5.6.0|~5.7.0|~5.8.0", 15 | "google/apiclient": "^2.1" 16 | }, 17 | "autoload": { 18 | "psr-4": { 19 | "Panakour\\Analytics\\": "src/" 20 | } 21 | }, 22 | "extra": { 23 | "laravel": { 24 | "providers": [ 25 | "Panakour\\Analytics\\GoogleAnalyticsServiceProvider" 26 | ], 27 | "aliases": { 28 | "Analytics": "Panakour\\Analytics\\Facades\\Analytics" 29 | } 30 | } 31 | } 32 | } 33 | -------------------------------------------------------------------------------- /src/Core/AnalyticsReporting.php: -------------------------------------------------------------------------------- 1 | params = $params; 17 | $this->create($client->get(), $request->get()); 18 | } 19 | 20 | private function create($client, $request) 21 | { 22 | $this->analytics = new Google_Service_AnalyticsReporting($client); 23 | $this->body = new Google_Service_AnalyticsReporting_GetReportsRequest(); 24 | $this->body->setReportRequests([$request]); 25 | } 26 | 27 | public function get() 28 | { 29 | return $this->analytics->reports->batchGet($this->body, $this->params); 30 | } 31 | } 32 | -------------------------------------------------------------------------------- /src/Core/Client.php: -------------------------------------------------------------------------------- 1 | config = $configFile; 15 | $this->create(); 16 | $this->setAuthConfig(); 17 | $this->setScopes(); 18 | $this->setViewId($request->get()); 19 | } 20 | 21 | private function create() 22 | { 23 | $this->client = new Google_Client(); 24 | } 25 | 26 | private function setAuthConfig() 27 | { 28 | $this->client->setAuthConfig($this->config['credentials_json_file']); 29 | } 30 | 31 | private function setScopes() 32 | { 33 | $this->client->setScopes(['https://www.googleapis.com/auth/analytics.readonly']); 34 | } 35 | 36 | private function setViewId($request) 37 | { 38 | $request->setViewId($this->config['view_id']); 39 | } 40 | 41 | public function get() 42 | { 43 | return $this->client; 44 | } 45 | } 46 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2016 Panagiotis Koursaris 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /src/Builder/Director.php: -------------------------------------------------------------------------------- 1 | builder = $builder; 12 | $this->build($analytics); 13 | } 14 | 15 | public function build($analytics) 16 | { 17 | $this->createBuilder(); 18 | $this->buildAnalytics($analytics); 19 | $this->buildReport(); 20 | } 21 | 22 | public function createBuilder() 23 | { 24 | $this->builder->create(); 25 | $this->builder->addRequest(); 26 | $this->builder->addClient(); 27 | } 28 | 29 | public function buildAnalytics($analytics) 30 | { 31 | foreach ($analytics as $analytic) { 32 | call_user_func([$this->builder, $analytic['method']], $analytic['parameters']); 33 | } 34 | } 35 | 36 | public function buildReport() 37 | { 38 | $this->builder->setAnalyticsData(); 39 | } 40 | 41 | public function get(): AnalyticsBuilder 42 | { 43 | return $this->builder->get(); 44 | } 45 | } 46 | -------------------------------------------------------------------------------- /src/Core/DimensionFilter.php: -------------------------------------------------------------------------------- 1 | create(); 16 | $this->setDimensionName($filter['dimensionName']); 17 | $this->setOperator($filter['operator']); 18 | $this->setExpression($filter['expression']); 19 | $this->setFilter(); 20 | $this->set($request->get()); 21 | } 22 | 23 | private function create() 24 | { 25 | $this->dimensionFilter = new Google_Service_AnalyticsReporting_DimensionFilter(); 26 | $this->filterClause = new Google_Service_AnalyticsReporting_DimensionFilterClause(); 27 | } 28 | 29 | private function setOperator(string $operator) 30 | { 31 | $this->dimensionFilter->setOperator($operator); 32 | } 33 | 34 | private function setDimensionName(string $dimensionName) 35 | { 36 | $this->dimensionFilter->setDimensionName($dimensionName); 37 | } 38 | 39 | private function setExpression($expression) 40 | { 41 | $this->dimensionFilter->setExpressions($expression); 42 | } 43 | 44 | private function setFilter() 45 | { 46 | $this->filterClause->setFilters($this->dimensionFilter); 47 | } 48 | 49 | private function set($request) 50 | { 51 | $request->setDimensionFilterClauses($this->filterClause); 52 | } 53 | } 54 | -------------------------------------------------------------------------------- /src/Core/Renderable.php: -------------------------------------------------------------------------------- 1 | reports = $reports->get(); 12 | } 13 | 14 | public function render(): array 15 | { 16 | $myReport = []; 17 | for ($reportIndex = 0; $reportIndex < count($this->reports); $reportIndex++) { 18 | $report = $this->reports[$reportIndex]; 19 | $header = $report->getColumnHeader(); 20 | $dimensionHeaders = $header->getDimensions(); 21 | $metricHeaders = $header->getMetricHeader()->getMetricHeaderEntries(); 22 | $rows = $report->getData()->getRows(); 23 | 24 | for ($rowIndex = 0; $rowIndex < count($rows); $rowIndex++) { 25 | $myReport[$rowIndex] = []; 26 | $row = $rows[$rowIndex]; 27 | $dimensions = $row->getDimensions(); 28 | $metrics = $row->getMetrics(); 29 | 30 | if($dimensionHeaders && count($dimensionHeaders)) { 31 | for ($i = 0; $i < count($dimensionHeaders) && $i < count($dimensions); $i++) { 32 | $dimensionName = $dimensionHeaders[$i]; 33 | $myReport[$rowIndex][$dimensionName] = $dimensions[$i]; 34 | } 35 | } 36 | 37 | for ($j = 0; $j < count($metricHeaders) && $j < count($metrics); $j++) { 38 | $values = $metrics[$j]; 39 | 40 | for ($valueIndex = 0; $valueIndex < count($values->getValues()); $valueIndex++) { 41 | $entry = $metricHeaders[$valueIndex]; 42 | $metricValue = $values->getValues()[$valueIndex]; 43 | $metricName = $entry->getName(); 44 | $myReport[$rowIndex][$metricName] = $metricValue; 45 | } 46 | } 47 | } 48 | } 49 | 50 | return $myReport; 51 | } 52 | } 53 | -------------------------------------------------------------------------------- /src/Analytics.php: -------------------------------------------------------------------------------- 1 | analytics); 15 | $analytics = $director->get(); 16 | 17 | return $analytics; 18 | } 19 | 20 | public function get(): array 21 | { 22 | return $this->buildData()->render; 23 | } 24 | 25 | public function getBuilder(): AnalyticsBuilder 26 | { 27 | return $this->buildData(); 28 | } 29 | 30 | public function setDateRange(string $startDate, string $endDate) 31 | { 32 | $this->analytics[] = [ 33 | 'method' => 'setDateRange', 34 | 'parameters' => ['startDate' => $startDate, 'endDate' => $endDate], 35 | ]; 36 | } 37 | 38 | public function setMaxResults(int $maxResults) 39 | { 40 | $this->analytics[] = [ 41 | 'method' => 'setMaxResults', 42 | 'parameters' => $maxResults, 43 | ]; 44 | } 45 | 46 | public function setMetrics(array $metric) 47 | { 48 | $this->analytics[] = [ 49 | 'method' => 'setMetric', 50 | 'parameters' => $metric, 51 | ]; 52 | } 53 | 54 | public function setDimension(array $dimension) 55 | { 56 | $this->analytics[] = [ 57 | 'method' => 'setDimension', 58 | 'parameters' => $dimension, 59 | ]; 60 | } 61 | 62 | public function setDimensionFilter(string $dimensionName, string $operator, $expression) 63 | { 64 | $this->analytics[] = [ 65 | 'method' => 'setDimensionFilter', 66 | 'parameters' => ['dimensionName' => $dimensionName, 'operator' => $operator, 'expression' => $expression], 67 | ]; 68 | } 69 | 70 | public function setOrder(string $fieldName, string $orderType, string $sortType) 71 | { 72 | $this->analytics[] = [ 73 | 'method' => 'setOrder', 74 | 'parameters' => ['fieldName' => $fieldName, 'orderType' => $orderType, 'sortType' => $sortType], 75 | ]; 76 | } 77 | 78 | public function setAnalyticsReporting(array $params) 79 | { 80 | $this->analytics[] = [ 81 | 'method' => 'setAnalyticsReporting', 82 | 'parameters' => $params, 83 | ]; 84 | } 85 | } 86 | -------------------------------------------------------------------------------- /src/Builder/AnalyticsBuilder.php: -------------------------------------------------------------------------------- 1 | analytics = new self(); 23 | } 24 | 25 | public function get(): self 26 | { 27 | return $this->analytics; 28 | } 29 | 30 | public function addRequest() 31 | { 32 | $this->analytics->request = new ReportRequest(); 33 | } 34 | 35 | public function addClient() 36 | { 37 | $this->analytics->client = new Client(config('analytics'), $this->analytics->request); 38 | } 39 | 40 | public function setDateRange(array $dateRange) 41 | { 42 | $this->analytics->dateRange = new DateRange($dateRange, $this->analytics->request); 43 | } 44 | 45 | public function setMaxResults(int $maxResults) 46 | { 47 | $this->analytics->maxResults = new MaxResults($maxResults, $this->analytics->request); 48 | } 49 | 50 | public function setMetric(array $metric) 51 | { 52 | $this->analytics->metric = new Metric($metric, $this->analytics->request); 53 | } 54 | 55 | public function setDimension(array $dimension) 56 | { 57 | $this->analytics->dimension = new Dimension($dimension, $this->analytics->request); 58 | } 59 | 60 | public function setDimensionFilter(array $filter) 61 | { 62 | $this->analytics->dimensionFilter = new DimensionFilter($filter, $this->analytics->request); 63 | } 64 | 65 | public function setOrder(array $order) 66 | { 67 | $this->analytics->order = new Order($order, $this->analytics->request); 68 | } 69 | 70 | public function setAnalyticsReporting(array $params = []) 71 | { 72 | $this->analytics->analyticsReporting = new AnalyticsReporting($this->analytics->client, $this->analytics->request, $params); 73 | } 74 | 75 | public function setAnalyticsData() 76 | { 77 | if (!property_exists($this->analytics, 'analyticsReporting')) { 78 | $this->setAnalyticsReporting(); 79 | } 80 | $this->analytics->render = (new Renderable($this->analytics->analyticsReporting))->render(); 81 | } 82 | } 83 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | [![StyleCI](https://styleci.io/repos/77175016/shield?branch=master)](https://styleci.io/repos/77175016) 2 | [![Latest Stable Version](https://poser.pugx.org/panakour/analytics/v/stable)](https://packagist.org/packages/panakour/analytics) 3 | [![Total Downloads](https://poser.pugx.org/panakour/analytics/downloads)](https://packagist.org/packages/panakour/analytics) 4 | [![License](https://poser.pugx.org/panakour/analytics/license)](https://packagist.org/packages/panakour/analytics) 5 | 6 | # Get easily whatever data you want from google analytics API V4 using laravel php framework. 7 | 8 | This package helps php developers to use Google Analytics API V4 with convenient way. 9 | The code is clean and was written with good OOP practices. 10 | Any help to improve this package would be appreciated. 11 | 12 | The package is compatible with laravel framework. 13 | 14 | 15 | ## Installation 16 | 17 | Install the package via composer: 18 | ``` shell 19 | composer require panakour/analytics 20 | ``` 21 | To use it with laravel add the GoogleAnalyticsServiceProvider to the `config/app.php`: 22 | ```php 23 | 'providers' => [ 24 | ... 25 | Panakour\Analytics\GoogleAnalyticsServiceProvider::class 26 | ] 27 | ``` 28 | 29 | If you want to use the facade of the package add it to the `config/app.php`: 30 | ```php 31 | 'aliases' => [ 32 | ... 33 | 'Analytics' => Panakour\Analytics\Facades\Analytics::class 34 | ] 35 | ``` 36 | Copy the analytics config file with the command: 37 | ``` shell 38 | php artisan vendor:publish --provider="Panakour\Analytics\GoogleAnalyticsServiceProvider" 39 | ``` 40 | For those who have a credential with google analytics api continue here otherwise look at [how to create credential with google analytics api](#create-credential-with-google-analytics-api-v4). 41 | 42 | Be sure that you have `service-account-credentials.json` file within `storage\app\google-analytics\`. 43 | 44 | Add the view id to `.env` file: 45 | ``` 46 | GOOGLE_ANALYTICS_VIEW_ID=324235464 47 | ``` 48 | 49 | ## Usage 50 | 51 | #### You can get analytics data simply using the facade 52 | `Panakour\Analytics\Facades\Analytics` 53 | 54 | ##### To get all sessions of the last week 55 | `Analytics::get();` 56 | 57 | ##### To get all sessions depends on the specific date range 58 | ```php 59 | Analytics::setDateRange('2016-10-01', '2016-11-25'); 60 | Analytics::get(); 61 | ``` 62 | 63 | ##### To get whatever data you want 64 | 65 | ```php 66 | Analytics::setDateRange('2016-10-01', '2016-11-25'); 67 | Analytics::setMaxResults(20); 68 | Analytics::setMetrics(['ga:entrances', 'ga:pageviews', 'ga:bounceRate']); 69 | Analytics::setDimension(['ga:pagePath', 'ga:pageTitle']); 70 | Analytics::setDimensionFilter('ga:pagePath', 'REGEXP', '/i-want-to-get-all-data-that-has-this-page-path'); 71 | Analytics::setOrder('ga:pageviews', 'VALUE', 'DESCENDING'); 72 | return Analytics::get(); 73 | ``` 74 | 75 | `setMetrics` and `setDimension` methods accept an array containing the wanted metrics and dimension. Available [metrics and dimensions](https://developers.google.com/analytics/devguides/reporting/core/dimsmets) 76 | 77 | `setDimensionFilter` accept 3 parameters. First parameter get the dimension name in which you want to filter analytics data. Second parameter get the [operator](https://developers.google.com/analytics/devguides/reporting/core/v4/rest/v4/reports/batchGet#operator) (REGEXP, BEGINS_WITH, ENDS_WITH and more) you want. Third parameter get the expression. For example if you want to get all analytics data in which the page path include `play` or `simple` words you can use: `Analytics::setDimensionFilter('ga:pagePath', 'REGEXP', '(\/play\/|\/simple\/)');` 78 | 79 | If you want to get analytics data for multiple pages in a single request by their exact paths, you can use the 'IN_LIST' operator and pass an array of paths as the third parameter. E.g. 80 | `Analytics::setDimensionFilter('ga:pagePath', 'IN_LIST', ['/i-want-data-for-this-path', '/and/this-path-too']);` 81 | 82 | `setOrder` method accept 3 parameters. First parameter get the name in which you want to order the data. Second get [OrderType](https://developers.google.com/analytics/devguides/reporting/core/v4/rest/v4/reports/batchGet#ordertype) usually `VALUE`. Third get the [SortOrder](https://developers.google.com/analytics/devguides/reporting/core/v4/rest/v4/reports/batchGet#sortorder) usually `ASCENDING` or `DESCENDING`. 83 | 84 | #### Get data using Analytics contract 85 | `Panakour\Analytics\Contracts\Analytics` 86 | 87 | Instead of facade you can get analytics data using the Analytics interface: 88 | ```php 89 | use Panakour\Analytics\Contracts\Analytics; 90 | 91 | class GoogleAnalyticsController 92 | { 93 | //inject analytics interface 94 | public function get(Analytics $analytics) 95 | { 96 | $analytics->setDateRange('2016-12-01', '2016-12-20'); 97 | $analytics->setMaxResults(11); 98 | $analytics->setMetrics(['ga:pageviews', 'ga:uniquePageviews', 'ga:avgTimeOnPage', 'ga:entrances', 'ga:bounceRate']); 99 | $analytics->setDimension(['ga:pagePath', 'ga:pageTitle']); 100 | $analytics->setDimensionFilter('ga:pagePath', 'REGEXP', '(\/this-value-in-path\/|\/or-this-value-in-path\/)'); 101 | $analytics->setOrder('ga:pageviews', 'VALUE', 'DESCENDING'); 102 | return $analytics->get(); 103 | } 104 | } 105 | ``` 106 | 107 | ## Create credential with google analytics api v4 108 | Guide from google analytics api v4: https://developers.google.com/analytics/devguides/reporting/core/v4/quickstart/service-php 109 | - Create a project using [Google API Console](https://console.developers.google.com/start/api?id=analyticsreporting.googleapis.com&credential=client_key): 110 | - Open the [Service accounts page](https://console.developers.google.com/permissions/serviceaccounts). If prompted, select your project that you have created and click open. 111 | - Click `Create service account`. 112 | - In the Create service account window, type a name for the service account, and select Furnish a new private key. In the key type select JSON and then click create. If you want to grant G Suite domain-wide authority to the service account, also select Enable G Suite Domain-wide Delegation. 113 | - Copy Service account ID you have created and then go to [google analytics admin panel](https://analytics.google.com/analytics/web/#management/Settings) select `User Management` and add the account you have copied with the permissions that you want. 114 | - Your new public/private key pair is generated and downloaded to your machine; it serves as the only copy of this key. You are responsible for storing it securely. 115 | - Rename the **json** file to `service-account-credentials.json`. 116 | - To get the **view id** you can use the [account explorer](https://ga-dev-tools.appspot.com/account-explorer/) or from google analytics `view settings` from [admin panel](https://analytics.google.com/analytics/web/#management/Settings). 117 | --------------------------------------------------------------------------------