Coder Social home page Coder Social logo

mediafigaro / google-analytics-api-symfony Goto Github PK

View Code? Open in Web Editor NEW
46.0 6.0 16.0 168 KB

Google Analytics API Symfony Bundle

Home Page: https://mediafigaro.github.io

License: MIT License

PHP 95.66% HTML 4.34%
symfony symfony-bundle google google-analytics analytics api

google-analytics-api-symfony's Introduction

Google Analytics API v4 Symfony bundle

SensioLabsInsight

Latest Stable Version Total Downloads Latest Unstable Version License Monthly Downloads Daily Downloads composer.lock

Use

At MEDIA.figaro http://media.figaro.fr, the advertising department of the french newspaper Le Figaro and part of the Figaro Group (CCM Benchmark), we use this bundle to monitor our digital platforms with Google Analytics.

It's a simple package that wraps the Google Analytics API version 4, and that gives you all the information to go straight to the point of getting some main metrics from GA.

Development by Kendrick https://github.com/kendrick-k.

To be able to use it, you have to setup a project on Google Console for Google Analytics, get the json key, then configure this package by setting the path for it. You'll have to add the developer email defined into the Google Console to the GA views to authorize it, otherwise the view won't be accessible through the API.

You can use the debug routes to go live and test a profile (ex id : 111111111, here with Docker) :

http://symfony.dev/app_dev.php/analytics-api/111111111

debug

Installation

composer require mediafigaro/google-analytics-api-symfony

without Flex, add to /app/AppKernel.php :

$bundles = [
    ...
    new MediaFigaro\GoogleAnalyticsApi\GoogleAnalyticsApi(),
];

Versions

1.2

Adding filterMetric and filterDimension to getDataDateRangeMetricsDimensions method which is a simple wrapper to Google Api Client ex :

$analyticsService = $this->get('google_analytics_api.api');

$data = $analyticsService->getDataDateRangeMetricsDimensions(
    'myanalyticsviewid',    // viewid
    '2018-01-01',   // date start
    'today',        // date end
    ['sessions','users','percentNewSessions','bounceRate'],             // metric
    ['source','campaign','fullReferrer','sourceMedium','pagePath'],     // dimension
    [   // order metric and/or dimension
        'fields'    =>  ['sessions'],
        'order'     =>  'descending'
    ],
    [   // metric
        'metric_name'       =>  'sessions',
        'operator'          =>  'LESS_THAN',
        'comparison_value'  =>  '100'
    ],
    [   // dimension
        'dimension_name'    =>  'sourceMedium',
        'operator'          =>  'EXACT',
        'expressions'       =>  [
            'trading / native'
        ]
    ]
);

1.1

Symfony 4 simple adaptation with a public service and a new public method that takes in charge metrics and dimensions with sorting options :

getDataDateRangeMetricsDimensions($viewId,$dateStart,$dateEnd,$metrics='sessions',$dimensions=null,$sorting=null)

Query explorer https://ga-dev-tools.appspot.com/query-explorer/ to build your query.

$viewId : https://developers.google.com/analytics/devguides/reporting/core/v3/reference#ids

$dateStart : https://developers.google.com/analytics/devguides/reporting/core/v3/reference#startDate

$dateEnd: https://developers.google.com/analytics/devguides/reporting/core/v3/reference#endDate

$metrics: https://developers.google.com/analytics/devguides/reporting/core/v3/reference#metrics (without the 'ga:', array or string)

$dimensions: https://developers.google.com/analytics/devguides/reporting/core/v3/reference#dimensions (without the 'ga:', array or string)

$sorting: https://developers.google.com/analytics/devguides/reporting/core/v3/reference#sort

without the 'ga:', array or string, eg. :

[
    'fields'    =>  ['pagePath','sessions'], // or : 'sessions'
    'order'     =>  'descending'
]

example :

$analyticsService = $this->get('google_analytics_api.api');

$data = $analyticsService->getDataDateRangeMetricsDimensions(
    'myanalyticsviewid',
    '30daysAgo',
    'today',
    ['sessions','users','percentNewSessions','bounceRate'],
    ['source','campaign','fullReferrer','sourceMedium','pagePath'],
    [
        'fields'    =>  ['pagePath','sessions'],
        'order'     =>  'descending'
    ]
)

$data :

array(329) {
  [0]=>
  array(2) {
    ["metrics"]=>
    array(4) {
      ["sessions"]=>
      string(5) "16738"
      ["users"]=>
      string(5) "15602"
      ["percentNewSessions"]=>
      string(17) "88.39168359421676"
      ["bounceRate"]=>
      string(17) "83.95268251881946"
    }
    ["dimensions"]=>
    array(5) {
      ["source"]=>
      string(7) "trading"
      ["campaign"]=>
      string(7) "my-campaign"
      ["fullReferrer"]=>
      string(7) "trading"
      ["sourceMedium"]=>
      string(16) "trading / native"
      ["pagePath"]=>
      string(50) "/my-url"
    }
  }
  [1]=>
  array(2) {
    ["metrics"]=>
    array(4) {
      ["sessions"]=>
      string(4) "6506"
      ["users"]=>
      string(4) "6200"
      ["percentNewSessions"]=>
      string(17) "87.05810021518599"
      ["bounceRate"]=>
      string(17) "87.74976944359054"
    }
    ["dimensions"]=>
    array(5) {
      ["source"]=>
      string(7) "trading"
      ["campaign"]=>
      string(7) "my-campaign-2"
      ["fullReferrer"]=>
      string(7) "trading"
      ["sourceMedium"]=>
      string(19) "trading / 320x480-1"
      ["pagePath"]=>
      string(50) "/my-url-2"
    }
  }
  [2]=>
  ...

Session - Dimensions & Metrics Explorer : https://developers.google.com/analytics/devguides/reporting/core/dimsmets

1.0

First version with a quick connector to consume Google Analytics v4 with Google API client with getDataDateRange private method (that handles only metrics), wrapped with some public methods to get a quick access to main metrics such as sessions (eg. getBounceRateDateRange($viewId,$dateStart,$dateEnd)), bounce rate, average time on page, page view per session, new visits, page views and average page load time. Debug route included for a simple setup and test.

Configuration

google_analytics_api.google_analytics_json_key

Set the relative path for your json key (set it on your server, better not into your repository) from execution path, ex: /data/analytics/analytics-27cef1a4c0fd.json.

/app/config/parameters.yml

google_analytics_json_key: "../data/analytics/analytics-27cef1a4c0fd.json"

/app/config/config.yml

google_analytics_api:
    google_analytics_json_key: "%google_analytics_json_key%"

Google API key

Generate the json file from https://console.developers.google.com/start/api?id=analyticsreporting.googleapis.com&credential=client_key by creating a project, check the documentation : https://developers.google.com/analytics/devguides/reporting/core/v4/quickstart/service-php.

Google Analytics API v4

List of metrics for report building with search engine : https://developers.google.com/analytics/devguides/reporting/core/dimsmets eg. ga:sessions, ga:visits, ga:bounceRate ...

Objects : https://github.com/google/google-api-php-client-services/tree/master/AnalyticsReporting

(example : ReportData object : https://github.com/google/google-api-php-client-services/blob/master/AnalyticsReporting/ReportData.php)

Samples : https://developers.google.com/analytics/devguides/reporting/core/v4/samples

Debug

Add the debug routes for development purposes :

/app/config/routing_dev.yml

_google_analytics_api:
    resource: "@GoogleAnalyticsApi/Resources/config/routing_dev.yml"

http://symfony.dev/app_dev.php/analytics-api/000000000

000000000 = profile id that you can find in the analytics URL, p000000000 :

https://analytics.google.com/analytics/web/?hl=en&pli=1#management/Settings/a222222222w1111111111p000000000/%3Fm.page%3DPropertySettings/

Result of this debug page :

debug

Errors

In that 403 error case, follow the link and authorize the API v4.

...
    "message": "Google Analytics Reporting API has not been used in project xxxxxx-xxxxxx-000000 
    before or it is disabled. Enable it by visiting 
    https://console.developers.google.com/apis/api/analyticsreporting.googleapis.com/overview?project=xxxxxx-xxxxxx-000000 
    then retry. If you enabled this API recently, wait a few minutes for the action to propagate 
    to our systems and retry.",
    "domain": "global",
    "reason": "forbidden"
}
],
"status": "PERMISSION_DENIED"

Example

Call the service :

$analyticsService = $this->get('google_analytics_api.api');
$analytics = $analyticsService->getAnalytics();

Use the method helpers to get the main metrics within a date range :

$viewId = '000000000'; // set your view id

// get some metrics (last 30 days, date format is yyyy-mm-dd)
$sessions = $analyticsService->getSessionsDateRange($viewId,'30daysAgo','today');
$bounceRate = $analyticsService->getBounceRateDateRange($viewId,'30daysAgo','today');
$avgTimeOnPage = $analyticsService->getAvgTimeOnPageDateRange($viewId,'30daysAgo','today');
$pageViewsPerSession = $analyticsService->getPageviewsPerSessionDateRange($viewId,'30daysAgo','today');
$percentNewVisits = $analyticsService->getPercentNewVisitsDateRange($viewId,'30daysAgo','today');
$pageViews = $analyticsService->getPageViewsDateRange($viewId,'30daysAgo','today');
$avgPageLoadTime = $analyticsService->getAvgPageLoadTimeDateRange($viewId,'30daysAgo','today');

Contribution

You are welcome to contribute to this small Google Analytics v4 wrapper, to create more helpers or more.

More tools

Try the Symfony Debug Toolbar Git : https://github.com/kendrick-k/symfony-debug-toolbar-git and the docker Service Oriented Architecture for Symfony : https://github.com/mediafigaro/docker-symfony.

Tutorial

French tutorial by Jérémy PERCHE, SUPINFO student.

google-analytics-api-symfony's People

Contributors

kendrick-k avatar mediafigaro avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar

google-analytics-api-symfony's Issues

Install via composer

Hello, I am installing the bundle via composer, and I get this error:

`iMac-de-dedioweb:dedioweb.com dedioweb$ php composer require mediafigaro/google-analytics-api-symfony
Using version ^1.0 for mediafigaro/google-analytics-api-symfony
./composer.json has been updated
Loading composer repositories with package information
Updating dependencies (including require-dev)
Your requirements could not be resolved to an installable set of packages.

Problem 1
- google/apiclient v2.2.1 requires php >=5.4 -> your PHP version (7.1.7) overridden by "config.platform.php" version (5.3.9) does not satisfy that requirement.
- google/apiclient v2.2.0 requires php >=5.4 -> your PHP version (7.1.7) overridden by "config.platform.php" version (5.3.9) does not satisfy that requirement.
- google/apiclient v2.1.3 requires php >=5.4 -> your PHP version (7.1.7) overridden by "config.platform.php" version (5.3.9) does not satisfy that requirement.
- google/apiclient v2.1.2 requires php >=5.4 -> your PHP version (7.1.7) overridden by "config.platform.php" version (5.3.9) does not satisfy that requirement.
- google/apiclient v2.1.1 requires php >=5.4 -> your PHP version (7.1.7) overridden by "config.platform.php" version (5.3.9) does not satisfy that requirement.
- google/apiclient v2.1.0 requires php >=5.4 -> your PHP version (7.1.7) overridden by "config.platform.php" version (5.3.9) does not satisfy that requirement.
- google/apiclient v2.0.3 requires php >=5.4 -> your PHP version (7.1.7) overridden by "config.platform.php" version (5.3.9) does not satisfy that requirement.
- google/apiclient v2.0.2 requires php >=5.4 -> your PHP version (7.1.7) overridden by "config.platform.php" version (5.3.9) does not satisfy that requirement.
- google/apiclient v2.0.1 requires php >=5.4 -> your PHP version (7.1.7) overridden by "config.platform.php" version (5.3.9) does not satisfy that requirement.
- google/apiclient v2.0.0 requires php >=5.4 -> your PHP version (7.1.7) overridden by "config.platform.php" version (5.3.9) does not satisfy that requirement.
- mediafigaro/google-analytics-api-symfony 1.0 requires google/apiclient ^2.0 -> satisfiable by google/apiclient[v2.0.0, v2.0.1, v2.0.2, v2.0.3, v2.1.0, v2.1.1, v2.1.2, v2.1.3, v2.2.0, v2.2.1].
- Installation request for mediafigaro/google-analytics-api-symfony ^1.0 -> satisfiable by mediafigaro/google-analytics-api-symfony[1.0].

Installation failed, reverting ./composer.json to its original content.`
how to solve this?
thank you in advance

Can't load bundle from AppKernel

I have an issue with your bundle, It's impossible for me to load the bundle from AppKernel.

If I use the statement statued in the doc, new MediaFigaro\GoogleAnalyticsApi\GoogleAnalyticsApi(),
Firstly my IDE don't recognize the path and secondly Symfony returning this error :

The autoloader expected class "MediaFigaro\GoogleAnalyticsApi\GoogleAnalyticsApi" to be defined in file "C:\wamp64\www\leadingame\vendor\composer/../mediafigaro/google-analytics-api-symfony\GoogleAnalyticsApi.php". The file was found but the class was not in it, the class name or namespace probably has a typo.

And if I use the following statement, new MediaFigaro\Analytics\GoogleAnalyticsApi(),
My IDE recognize the path but Symfony returning an error too :

Attempted to load class "GoogleAnalyticsApi" from namespace "MediaFigaro\Analytics".
Did you forget a "use" statement for another namespace?

The problem seem to be really specific to this bundle, no problem with the others, so if anyone have a answer to this issue i'm taking it :)

Thanks per advance!
PokeRstarrr

Pull more than 1000 results

Hello, sorry if this is obvious, but I looked and couldn't find it. I need to pull more than 1000 results, which is all this function is giving me. Is there a function for paginating past 1000? Or is this a hard limit at this time? My code is pretty straight forward taken from the code samples.

        $data = $analyticsService->getDataDateRangeMetricsDimensions(
            '175227836',       // viewid
            $lastMonthStart,   // date start
            $lastMonthEnd,     // date end
            ['pageviews'],     // metric
            ['pagePath']       // dimension
            //[],              // sorting
            //[],              // filter metric
            //[]               // filter demension
        );

Thank you!

Implement Dimension

Hi all,
It will fine to get dimension service like metric.
I am just make a fork and i am introduce a new service to get dimensions like ga:browser / ga:user.
Would you like my codes ?
Bye

Filter expression or more than one filter, is possible?

Hi! Thanks for all the work.

Im using this Bundle and i don't know how to filter like the web query builder.
I want to filter url's by the word '/articulo/' and whitout the "#" symbol.

In the web query builder i can use a filter expression like this = "ga:pagePath=@/articulo/;ga:pagePath!@#"

Is possible to represent this with this bundle? or any tip on how to introduce this option in GoogleAnalyticsService?

Thanks, David.

Depracation of Sensio\Bundle\FrameworkExtraBundle

Hi! Your package is using Sensio\Bundle\FrameworkExtraBundle\Configuration\Route and Sensio\Bundle\FrameworkExtraBundle\Configuration\Template and it is now deprecated. You should change it to with Symfony\Component\Routing\Annotation\Route and Symfony\Component\Routing\Annotation\Template.

Get detailed data day per day

Hello,

I am trying to build a dashboard that display some graphs like these ones :

analytics

I looked at your DebugController to see how to use the bundle and I successfuly retrieved data between 2 dates. But I get the total, not the detailed data day per day that I can use to render my graphs. That's why I was wondering if there is a way to get the detailed data.

Thank you !

other data

The bundle is perfect, it works well.
I wish I could display other data than the default data present in the controller / Services.
Example, display the list of countries, display the map ... but I do not see how to proceed.
Can you explain it to us?
Thank you

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.