11

I've been trying to get Google API to work on my website for days now, but not getting it to work. Everywhere I search I find outdated examples... I need it to work with codeigniter and all I want to do is to fetch data from Google Analytics to show in the admin dashboard on my codeigniter website.

I understand that I need a Service Account, if I don't want to be authenticating everytime I look at the dashboard(?)

Can anyone please help me with getting this to work? Thank you so much in advance!

What I want done is: Fetch data from google analytics, return that data as maybe json, then I guess I can make a chart out of it with a plugin (perhaps some jQuery plugin already exists, or can I use googles own chart drawers?) and show this to administrators. I just want really simple data, as for example, how many users the last month...

Aaron Belchamber
  • 1,480
  • 1
  • 16
  • 20
Michael
  • 833
  • 1
  • 6
  • 25
  • 1
    I don't understand why someone would downvote this, since more people are probably having this problem! I've tried the plugin for Sparks for Codeigniter, but that one is two years old, meaning the api is outdated, and all the naming conventions in the examples on googles website are wrong... – Michael Sep 04 '14 at 14:35

1 Answers1

24

After about a week - and of course, on the same day I post this question, I finally manage to fix this myself.

This is how I go about:

I downloaded the latest Google Client API (for php) from their github.

I added the Google folder (src) in my application/third_party folder.

Inside my controller I included the required files by doing:

require_once(BASEPATH . '../application/third_party/Google/Client.php');
require_once(BASEPATH . '../application/third_party/Google/Service/Analytics.php');

Then I added the following code below that for authorization with Service Account (which you get from the Google Console and selecting your project > APIs & auth > Credentials > Then create a new Client ID, select Service Account, when done, press "Generate new p12 key" and add that key to your third_party/Google folder:

session_start();

$client_id = '<YOUR_CLIENT_ID>'; //Client ID
$service_account_name = '<YOUR_CLIENT_EMAIL>'; //Email Address 
$key_file_location = BASEPATH . '../application/third_party/Google/<YOUR KEY.p12>'; //key.p12

$client = new Google_Client();
$client->setApplicationName("ApplicationName");
$service = new Google_Service_Analytics($client);

if (isset($_SESSION['service_token'])) {
  $client->setAccessToken($_SESSION['service_token']);
}

$key = file_get_contents($key_file_location);
$cred = new Google_Auth_AssertionCredentials(
    $service_account_name,
    array(
        'https://www.googleapis.com/auth/analytics',
    ),
    $key,
    'notasecret'
);
$client->setAssertionCredentials($cred);
if($client->getAuth()->isAccessTokenExpired()) {
  $client->getAuth()->refreshTokenWithAssertion($cred);
}
$_SESSION['service_token'] = $client->getAccessToken();

The code below is for getting sessions (page visits) from the last 31 days

$analytics = new Google_Service_Analytics($client);

$profileId = "ga:<YOUR_PROFILE_ID>";
$startDate = date('Y-m-d', strtotime('-31 days')); // 31 days from now
$endDate = date('Y-m-d'); // todays date

$metrics = "ga:sessions";

$optParams = array("dimensions" => "ga:date");
$results = $analytics->data_ga->get($profileId, $startDate, $endDate, $metrics, $optParams);

$data['report'] = $results->rows; //To send it to the view later

To get all the dimensions and metrics that you can use, use this link. Example on how to send it to the view:

$this->view->load('your_view', $data);

To write it out as a chart I just used Google charts, in the JS (in the view) I just looped the data from $data['report'] to draw a chart.

Hope this will help people with this problem in the future.

Michael
  • 833
  • 1
  • 6
  • 25
  • 2
    Thanks for your code ...I was in same mess as your qs ..Your ans showed me everything start to end :) – Penny Jan 28 '15 at 14:29
  • This is really helpful, thank you! Unfortunately though, I get the error "(403) User does not have any Google Analytics account."... is this something that you stumbled across? – Owain Reed Jul 10 '15 at 15:34
  • Nope, sorry, I haven't had this issue. – Michael Aug 24 '15 at 08:42
  • @Michael you have added code for authorization with Service Account we need to add that code in controller or in view we need to add that – user8001297 Aug 31 '17 at 07:13
  • 2
    The path you mentioned `require_once(BASEPATH . '../application/third_party/Google/Service/Analytics.php');` does not have the file `Analytics.php` there in the service folder. – atul Sep 12 '17 at 14:38
  • 1
    Got the Analytics.php file here `https://github.com/google/google-api-php-client-services/blob/master/src/Google/Service/Analytics.php` – atul Sep 12 '17 at 14:46
  • I will create a Service accounts. but i don't understand $client_id = ''; my project create key id .....Will I put key id in place of clint id ???? – Jamil Ahmed Jul 05 '20 at 08:35
  • $profileId = "ga:"; Doesn't create any of my profile ID – Jamil Ahmed Jul 05 '20 at 08:37