如何在没有登录的情况下使用谷歌api获取分析数据?

时间:2021-08-20 15:14:31

I am using php and mysql. I have to get anlytics data of different sites using google sdk api and most important thing is that I need not to login in api. without login I need go get analytics data.
please have a look below code where I am able to get 'Google_AnalyticsService' object and facing error while getting data.It is saying Login Required...

我用的是php和mysql。我需要使用谷歌sdk api获取不同站点的anlytics数据,最重要的是我不需要登录api。没有登录,我需要去获取分析数据。请查看下面的代码,我可以在获取数据时获得'Google_AnalyticsService'对象并面临错误。它是说登录需要……

require 'apigp/Google_Client.php';
require 'apigp/contrib/Google_PlusService.php';
require 'apigp/contrib/Google_AnalyticsService.php';

date_default_timezone_set('UTC');
$date_beforeonemoth = date("Y-m-d", mktime(0,0,0,date("m"),date("d")-30,date("Y")));
$date_today = date("Y-m-d", mktime(0,0,0,date("m"),date("d"),date("Y")));

$google = new Google_Client();
$google->setDeveloperKey('Google AppKey here');
$google->setClientSecret('Google ClientSecretKey here');
$google->setClientId('Google ClientID here');
$analytics = new Google_AnalyticsService($google);

$profileURL="";
$pageName="";
$brandId="";
$sql="select * from profiles where APIType='Google Plus'";
$result=mysql_query($sql);
while($rs = mysql_fetch_assoc($result))
{
    $profileURL='https://plus.google.com/105932700878744xxxxxx';
    $brandId=4;
    $pageName=basename($profileURL);

    $accounts = $analytics->management_accounts->listManagementAccounts();
    if(isset($accounts['totalResults'])){
        if($accounts['totalResults']>0){
            $firstAccountId = $accounts['items'][0]['id'];
 $webproperties = $analytics->management_webproperties->listManagementWebproperties($firstAccountId);
                if(count($webproperties['items'])>0){
                     $firstWebpropertyId = $webproperties['items'][0]['id'];
$profiles = $analytics->management_profiles->listManagementProfiles($firstAccountId, $firstWebpropertyId);

                     if (count($profiles['items']) > 0) {
                       $profileId = $profiles['items'][0]['id'];


        $profileId = $pageName;
        $results = $analytics->data_ga->get(
        'ga:' . $profileId,
        $date_beforeonemoth,
        $date_today,
       'ga:visits,ga:pageviews,ga:pageviewsPerVisit,ga:avgTimeOnPage,ga:visitBounceRate,ga:percentNewVisits,ga:uniquePageviews',
        array(
            'dimensions' => 'ga:source,ga:keyword,ga:browser,ga:date,ga:month,ga:day,ga:year',
            'sort' => '-ga:visits,ga:keyword',
           // 'filters' => 'ga:medium==organic',
            'max-results' => '25'));

                       $visits = "";
                       $unique_visitors = "";
                       $pageviews = "";
                       $pages_visit = "";
                       $avg_visit_duration = "";
                       $bounce_rate = "";
                       $new_visits = "";

                       echo "<br>".$visits = $results['totalsForAllResults']['ga:visits'];
                       echo "<br>".$unique_visitors = $results['totalsForAllResults']['ga:uniquePageviews'];
                       echo "<br>".$pageviews = $results['totalsForAllResults']['ga:pageviews'];
                       $pages_visit = $results['totalsForAllResults']['ga:pageviewsPerVisit'];
                       $avg_visit_duration = $results['totalsForAllResults']['ga:avgTimeOnPage'];
                       $bounce_rate = $results['totalsForAllResults']['ga:visitBounceRate'];
                       $new_visits = $results['totalsForAllResults']['ga:percentNewVisits'];

                       $profileName = $results['profileInfo']['profileName'];

                    }else{print"No profiles found for this user.";}

                    }else{print"No webproperties found for this user.";}  //close webproperties result if condition

                }else{print"No accounts found for this user.";} //close total result if condition   
}
}

Error:
Fatal error: Uncaught exception 'Google_ServiceException' with message 'Error calling GET https://www.googleapis.com/analytics/v3/management/accounts?key=AIzaSyBeh0Aevex7q3iRIY5bV3N9gx0WAkNBMi4: (401) Login Required' in E:\xampp\htdocs\DATAPOINTS\apigp\io\Google_REST.php:66 Stack trace: #0 E:\xampp\htdocs\DATAPOINTS\apigp\io\Google_REST.php(36): Google_REST::decodeHttpResponse(Object(Google_HttpRequest)) #1 E:\xampp\htdocs\DATAPOINTS\apigp\service\Google_ServiceResource.php(186): Google_REST::execute(Object(Google_HttpRequest)) #2 E:\xampp\htdocs\DATAPOINTS\apigp\contrib\Google_AnalyticsService.php(139): Google_ServiceResource->__call('list', Array) #3 E:\xampp\htdocs\DATAPOINTS\anatest.php(33): Google_ManagementAccountsServiceResource->listManagementAccounts() #4 {main} thrown in E:\xampp\htdocs\DATAPOINTS\apigp\io\Google_REST.php on line 66

错误:致命错误:未捕获的异常“Google_ServiceException”和消息“错误调用GET https://www.googleapis.com/analytics/v3/management/accounts?key=AIzaSyBeh0Aevex7q3iRIY5bV3N9gx0WAkNBMi4:(401)登录要求在E:\xampp\htdocs\DATAPOINTS\apigp\io\ io\Google_REST中。Google_ManagementAccountsServiceResource->listManagementAccounts() #4 {main}被扔进E:\xampp\htdocs\ datapots \apigp\io\Google_REST中。php在第66行

How to get analytics data without login in api ?

如何在没有登录api的情况下获取分析数据?

1 个解决方案

#1


2  

According to Google, you must send authorization credentials with each API request.

根据谷歌,您必须向每个API请求发送授权凭据。

See here: https://developers.google.com/analytics/devguides/reporting/core/v3/#user_reports

在这里看到的:https://developers.google.com/analytics/devguides/reporting/core/v3/ # user_reports

#1


2  

According to Google, you must send authorization credentials with each API request.

根据谷歌,您必须向每个API请求发送授权凭据。

See here: https://developers.google.com/analytics/devguides/reporting/core/v3/#user_reports

在这里看到的:https://developers.google.com/analytics/devguides/reporting/core/v3/ # user_reports