google analytics API implementation for tracking a specific user activities in php

懵懂的女人 提交于 2019-12-25 08:22:14

问题


I'm developing an e-commerce student project using php (laravel framework), I have found lots of tutorials about using google analytics, but very rarely about how to retrieve data to my web site using APIs. I have the following questions:

  1. how to retrieve all data from google analytics to my web site using API.
  2. how to retrieve all data of UserID view? because I want to get all data about a specific user to know what is he/she (browser, language, country, Os .... etc) to use it to personalize my web site.

please any idea or help will be appreciated, I'm run out of time, people help

below is my API code that I'm using :

<?php
    namespace App\Http\Controllers;
    use Illuminate\Http\Request;
    use App\Http\Controllers\Controller;


    class HomeController extends Controller
    {
       public function getAnalyticsSummary(Request $request){
            $from_date = date("Y-m-d", strtotime($request->get('from_date',"7 days ago")));
            $to_date = date("Y-m-d",strtotime($request->get('to_date',$request->get('from_date','today')))) ; 
            $gAData = $this->gASummary($from_date,$to_date) ;
            return $gAData;
        }
             //to get the summary of google analytics.
        private function gASummary($date_from,$date_to) {
            $service_account_email = 'get-data-analytics@analytics-api-project-148820.iam.gserviceaccount.com';       
            // Create and configure a new client object.
            $client = new \Google_Client();
            $client->setApplicationName("any name");
            $analytics = new \Google_Service_Analytics($client);
            $cred = new \Google_Auth_AssertionCredentials(
                $service_account_email,
                array(\Google_Service_Analytics::ANALYTICS_READONLY),
                  "-----BEGIN PRIVATE KEY-----\nMIIEvQIBADANBgkqhkiG9w0BAQEFAASCBKcwggSjAgEAAoIBAQCrzw1R6ca16zYQ\n3ozuTlNVbvNWDPODW6NVrnny08V4ycd/ugvTQeU3EKno6mJ8iXNJ/3GXOz52iaRd\nGRKbfrPomK7gt6+F7EHVdpTfbc/u7TIJi5NbYzXS4jIXhIJhB4bGjzsnTGTY/6pF\nFmW/wgX2Y6n31EWyz2q5MiZDC5lEPrmNk/gOgWOyRHCVNHtBcyFdA3+w2or6ix5l\nrKlCwUkkzKAPb4OSvfDMz8o+h6r433E4+6MMHE/mf53CkX1DbDZIlZbUntYLoh19\n0oxKCufjfFEKqzxgTZxIbG5rK7jdrOFLuQwnaoKkUT0HAQTGnGoYrABo9HGjlgwg\n7rHzh+OzAgMBAAECggEBAKcRq8E41Ft4w1V6JI9jqRON1aCa7X2R8e3SwZFJL2C6\nzn28+9zN2khGswLkUSsLOgn+FYZbPO1mAWfqhragafBH8N5ioJNZX9dk/XWbQjTz\ngNHZYUzf16oe/VjzKRmTiRKym3ImjnaZfwi5s+3ZjZS/67ssNy6fFgfK5XwS3lKG\nFzAZYgCMyJIz8Cz9mHAHKmQELH29xiPNDSSCuAbScptOdNJvBB9Vvpu5b+/LtdWI\naBYLuZgMOSNgJiQFBjj/+RY5yBi9pL5aHYGHJJZnWp1CbxRQIN+xe5jBbpHZ6PWH\nUjoCfMkM+IWBNjlKOWCC/APFpGuDqYMRuHfakPvWIXECgYEA4otETO0hR00SceKt\nGXYtIX6ZfdK6K87EPTFofMXAvcH7CWU3Tr2+3pI/DWUD1pPEEfsOZpaS5Ry37IrQ\nVmhkS2j5QxYJ+NfEvjc17rdJuuwJeCeELDFNxsTvhk7yK6y75F7BFQH/dIcc7MYg\nTL11B340TpPlJtulnxLTW7G3nFkCgYEAwiXfGnpmuPE1yyGdux4mY1Eyp6ZmxC0o\nb+DIBqRRlwY23m7pv3g7a0GAqLIFaW7c/1iVlyoDg24eZ8YtSehtR0B5LEiExBaY\n7UpkqHosvCqgCH94O/Mas+DUv9Sfqy82geEagB65Cf+uLr/ixNbKiK12G29O/V7M\nCar/=========================================================================================================================================================================================================================================x/NCNpGaW7zKvAoGAffG7PqgXYNtqQ3MavgLF\nKtQFMzT65kI5AfXPpyzgBDKr84lhvdUddvK/FZg/mIuoLRLSgnYPnAv3s5yhleZ5\n7LGyo5fXXH7XUm2nNt+XZoV1rt6y+WgZi103M+fuv3GXYBdbOonPHopRzw3uzLIA\n9ovyAV95jOu9ybk4YgQXm5I=\n-----END PRIVATE KEY-----\n"
            );     
            $client->setAssertionCredentials($cred);
            if($client->getAuth()->isAccessTokenExpired()) {
                $client->getAuth()->refreshTokenWithAssertion($cred);
            }

            $optParams = [
                'dimensions' => 'ga:date',
                'sort'=>'-ga:date'
            ] ; 

            $results = $analytics->data_ga->get(
               'ga:133119102', 
               $date_from,
               $date_to,
               /*'ga:sessions,ga:users,ga:pageviews,ga:bounceRate,ga:hits,ga:avgSessionDuration',*/
               'ga:bounceRate',
               $optParams
               );

                $rows = $results->getRows();
                $rows_re_align = [] ;
                foreach($rows as $key=>$row) {
                    foreach($row as $k=>$d) {
                        $rows_re_align[$k][$key] = $d ;
                    }
                }           
                $optParams = array(
                            'dimensions' => 'rt:medium'
                    );



                try {
                  $results1 = $analytics->data_realtime->get(
                      'ga:132964552',
                      'rt:activeUsers',
                      $optParams);
                  // Success. 
                } catch (apiServiceException $e) {
                  // Handle API service exceptions.
                  $error = $e->getMessage();
                }

                $active_users = $results1->totalsForAllResults ;



                return view('myGoogle.getGoogle', [

                    'data'=> $rows_re_align ,
                   /* 'summary'=>$results->getTotalsForAllResults(),*/
                   /* 'active_users'=>$active_users['rt:activeUsers']*/
                    ]) ;
        }
    }

回答1:


User id is used for internal processing of users across multiple seasons. Example you have a user who uses your website and your moblie application this would technically be two sessions. However if you pass the User id you have for this user when they are logged into there account on your system. You are telling Google analytics this is the same person.

User Id is not something however that you can extract out of the API its used mainly for internal processing. Assuming that your user id is a non user specific value you can also set it as a custom dimension which you can then extract out using the API.



来源:https://stackoverflow.com/questions/40952378/google-analytics-api-implementation-for-tracking-a-specific-user-activities-in-p

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!