Search code examples
phpgoogle-analyticsgoogle-analytics-api

Google Analytics PHP5 Interface always fails to show result


I was trying to get pageviews and visits from my Google Analytics account, so I set an example like this: https://code.google.com/p/gapi-google-analytics-php-interface/ on my localhost, but somehow it isn't returning nothing... it always fails.

This is my code(password and email omitted on purpose):

<?php 
    require 'gapi.class.php';

    $gaEmail = 'email';
    $gaPassword = 'pass';
    $profileId = 'UA-37213064-1';

    $dimensions = array('pagePath','country', 'region', 'city'); 
    $metrics = array('visits');
    $sortMetric=null;
    $filter=null;
    $startDate='2011-02-01';
    $endDate='2015-01-30';
    $startIndex=1;
    $maxResults=10000;

    $ga = new gapi($gaEmail, $gaPassword);

    $ga->requestReportData($profileId, $dimensions, $metrics, $sortMetric, $filter,        $startDate, $endDate, $startIndex, $maxResults);

    $totalPageviews = $ga->getPageviews();

    foreach ($ga->getResults() as $result) {
       $visits = $result->getVists();
       print $visits; 
    }

?>

It always fails here:

$ga = new gapi($gaEmail, $gaPassword);

ERROR:

PHP Fatal error:  Uncaught exception 'Exception' with message 'GAPI: Failed to authenticate user. Error: "Error=BadAuthentication
Url=https://www.google.com/accounts/ContinueSignIn?sarp=1&scc=1&plt=AKgnsbttRRxx9DCBil669sL7kLRdff3nkCIN2ZZVwbU8erUozRAS9AUbn2wk7Rzjcotu7d3Hb7t3ihTxae_QFryWhZfF7uDfZDAL8GfF0w8CY8IopMZs9FEsmlkMlXczOKJ3QKLtEBGtPwCrjW69cI5U7NDe_WiPTWIZhXhf3znQjRU8TMrsNB6NNDMA_5zCwCMtTBYNB-tukpyRoFd3YS2HZfh4fJyDYA
Info=WebLoginRequired
"' in /Volumes/Macintosh Work/www/playground/gapi-1.3/gapi.class.php:418
Stack trace:
#0 /Volumes/Macintosh Work/www/playground/gapi-1.3/gapi.class.php(62): gapi->authenticateUser('Email...', 'password')
#1 /Volumes/Macintosh Work/www/playground/gapi-1.3/teste.php(17): gapi->__construct('EMAIL...', 'password')
#2 {main}
  thrown in /Volumes/Macintosh Work/www/playground/gapi-1.3/gapi.class.php on line 418

Solution

  • I am almost 100% sure that that is not going to work anymore. If you check you can see that the project hasn't been developed on since 2009 it allows you to login using a Login and password. Client login doesn't work with the current versions of Google analytics you must use Open Authentication.

    It depends upon what you are doing but you could look into useing the Php client library. https://github.com/google/google-api-php-client this will allow you to select your Google Analytics Data out using the Google Analytics API. You can find a tutorial here

    You could also consider using the Embeded API this will allow you to display fancy graphics and its JavaScript based.