Google Analytics - 无需登录即可访问api

时间:2014-09-01 13:11:47

标签: google-analytics google-api google-analytics-api google-api-php-client

我已成功配置了google analytics api并获得了成功的数据。

我想在没有gmail登录的情况下访问analytics api。

即。我会硬编码登录的凭据,但如何用PHP做?

是否有任何api函数可以执行此任务(对于PHP)

谢谢!

4 个答案:

答案 0 :(得分:3)

Hello Analytics API: PHP Quickstart Guide for Service Accounts将引导您完成创建服务帐户并将其添加到现有Google Analytics帐户/媒体资源/视图所需的步骤。

下载后,从开发者控制台下载了php客户端库和p12文件,您可以创建一个授权的分析服务对象,如下所示:

// Creates and returns the Analytics service object.

// Load the Google API PHP Client Library.
require_once 'google-api-php-client/src/Google/autoload.php';

// Use the developers console and replace the values with your
// service account email, and relative location of your key file.
$service_account_email = '<Replace with your service account email address.>';
$key_file_location = '<Replace with /path/to/generated/client_secrets.p12>';

// Create and configure a new client object.
$client = new Google_Client();
$client->setApplicationName("HelloAnalytics");
$analytics = new Google_Service_Analytics($client);

// Read the generated client_secrets.p12 key.
$key = file_get_contents($key_file_location);
$cred = new Google_Auth_AssertionCredentials(
    $service_account_email,
    array(Google_Service_Analytics::ANALYTICS_READONLY),
    $key
);
$client->setAssertionCredentials($cred);
if($client->getAuth()->isAccessTokenExpired()) {
  $client->getAuth()->refreshTokenWithAssertion($cred);
}

return $analytics;

使用返回的服务对象,您现在可以调用Google AnalyticsAPI:

// Calls the Core Reporting API and queries for the number of sessions
// for the last seven days.
$analytics->data_ga->get(
   'ga:' . $profileId,
   '7daysAgo',
   'today',
   'ga:sessions');

答案 1 :(得分:0)

由于多种原因,Google AnalyticsAPI不适合您的需要。

  1. 安全即可。如果最终用户拥有您的凭据,他可以登录您的Google帐户并访问您的所有数据。
  2. 延迟即可。该API不适用于页面加载。如果页面加载依赖于它,则可能需要很长时间才能为用户加载。
  3. 配额即可。 API具有有限的配额,如果您在每次用户进入您的网站时进行查询,该配额将会快速消失。
  4. 设计即可。最终,API被设计为由您自己使用而不是由其他人实时提取数据。
  5. 如果您想向用户展示数据,请记住这些事项,您应该构建某种系统,下载要离线显示的正确数据,将其存储在数据库中并显示在页面上。这样,您可以查询一次数据并多次显示,而不会公开您的凭据。

    谷歌甚至发布了一个AppEngine应用程序。它可以查询数据并存储在数据库中,因此任何未经身份验证的用户都可以查看数据并且延迟时间最短,因为在查看时它只是从数据存储中检索到的。它被称为Google Analytics superProxy

    更新09/02

    在您的应用程序上执行请求时,您仍需要完成oAuth并且您希望它自动完成,您希望避免登录屏幕。有两个选项

    1. 使用oAuth for Installed Apps。手动完成登录屏幕并存储刷新令牌。每天您可以使用刷新令牌获取访问令牌和查询数据,无需人工干预。
    2. 使用Service Accounts。这些不需要手动批准登录屏幕,但您需要授予对Google Analytics帐户中服务帐户电子邮件的访问权限。服务帐户使用加密进行身份验证,因此您可能需要php的加密模块才能使用它。

答案 2 :(得分:0)

使用服务帐户: https://developers.google.com/api-client-library/php/auth/service-accounts https://developers.google.com/analytics/solutions/articles/hello-analytics-api#authorize_access

它需要google-api-php-client库,您可以在google开发者控制台中创建一个服务帐户,然后将此帐户中的电子邮件添加到您的Google Analytics(分析)配置文件&#39; User Management&#39;对于您要访问的配置文件。 按照上面链接中的代码,您应该能够在没有Goolge登录的情况下访问您的Google分析数据(因为您已经提供了严格的帐户电子邮件和p12密钥以进行授权)

答案 3 :(得分:0)

Hi Kiran,

  1. 服务帐户
    通过使用Google Python客户端API的服务器端授权,您可以使用此demo访问每个用户无需登录的Google搜索数据和图表。

  2. oAuth for Google APP
    另一种方法是使用oAuth。但在这种情况下,您需要付费的Google Apps for Work帐户Google Apps您可以阅读here如何在不登录的情况下将Apps和oAuth结合起来进行访问。

  3. 我在这里添加了新的(2016)Google客户端PHP API Beta的工作代码,用于使用json进行匿名访问 - 包括amChart。

    此外,json凭证文件的续订过程可以自动执行 - 这不是在此代码示例中完成的。 ClientLogin令牌可以在发布日期后持续2周,但此限制是特定于服务的,可以更短。您可以在Google_AssertionCredentials.php(24)中更改生命周期,但这会带来安全风险(对于您的资金 - 如果有人自动调用该网站,您将超出允许的免税量)

    class Google_AssertionCredentials {
      const MAX_TOKEN_LIFETIME_SECS = 360000;
    

    要使autoload.php正常工作,您必须通过composer.phar将客户端PHP API资源安装到htdocs(Apache)或wwwroot(IIS)中,并将此代码放在“vendor”文件夹中。

    我没有使用dataLoader并将其注释掉,因为amChart在我的环境中加载了。因此我使用了数据提供者,它可靠。

    /*
         "dataLoader": {
            "url": "data.php",
            "format": "json"
         },
         */
    
    
    
     <!DOCTYPE HTML>
    <html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
        <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1" />
        <title>Gimba - Google Analytics - GimbaChartAll</title>
        <script src="https://www.amcharts.com/lib/3/amcharts.js"></script>
        <script src="https://www.amcharts.com/lib/3/serial.js"></script>
        <script src="https://www.amcharts.com/lib/3/plugins/dataloader/dataloader.min.js"></script>
        <style>
        body, html {
          font-family: Verdana;
          font-size: 10px;
        }
        #chartdiv {
          width: 1100px;
          height: 700px;
          margin-left:auto;
          margin-right:auto;
        }
        </style>
        <script>
    
        var dataJS = <?php echo dataGA(); ?>;
        var chart = AmCharts.makeChart("chartdiv", {
            "type": "serial",
            "theme": "light",
         /*
         "dataLoader": {
            "url": "data.php",
            "format": "json"
         },
         */
    
         "dataProvider": dataJS  ,
         "categoryField": "country",
         "categoryAxis": {
           "gridColor": "#0000FF",
           "gridAlpha": 0.07,
           "title": "Country"
         },
         "creditsPosition": "top-right",
         "categoryField": "country",
         "categoryAxis": {
             "gridAlpha": 0.07,
             "gridPosition": "start",
             "tickPosition": "start",
             "title": "Country"
         },
         "valueAxes": [ {
             "id": "v1",
             "gridAlpha": 0.1,
             "axisColor": "#0000ff",
             "title": "Users/Sessions"
         }, {
             "id": "v2",
             "gridAlpha": 0,
             "axisColor": "#0000ff",
             "position": "right",
             "title": "Page views"
         } ],
         "graphs": [ {
             "startDuration": 3,
             "type": "column",
             "title": "Sessions",
             "valueField": "sessions",
             "fillColors": "#0000ff" ,
             "lineAlpha": 0,
             "fillAlphas": 0.6
         }, {
             "type": "column",
             "title": "Users",
             "valueField": "users",
             "fillColors": "#0000ff" ,
             "lineAlpha": 0,
             "fillAlphas": 0.2
         }, {
             "type": "line",
             "valueAxis": "v2",
             "title": "Page views",
             "valueField": "pageviews",
             "lineColor": "#0000ff" ,
             "lineThickness": 1,
             "bullet": "round"
         } ],
         "legend": {}
        } );
        </script>
    </head>
    
    <body>
        <div id="chartdiv"></div>
    </body>
    </html>
    
    
    
    <?php
    //dataGA();
    function dataGA()
    {
        require_once 'autoload.php';
        $google_account = array(
          'email'   => 'xxxxxxxxxxxxxxxxxxxxxx@xxxxxxxxxxxxxxxx.iam.gserviceaccount.com',
          'key'     => file_get_contents(__DIR__ . '/OAuthClientServiceAccount1.json'),
          'profile' => 'xxxxxxxxx'
        );
        // Creates and returns the Analytics service object.
        // Load the Google API PHP Client Library.
        // Create and configure a new client object.
        $client = new Google_Client();
        $client->setApplicationName( 'Gimba3' );
        $analytics = new Google_Service_Analytics($client);
        $scopes = array('https://www.googleapis.com/auth/analytics.readonly');
        $client->setScopes($scopes);
        try{
            $client->setAuthConfigFile(__DIR__ . '/OAuthClientServiceAccount1.json');
        }
        catch(Exception $e){
            echo "Key NOT OK<br>";
            echo $e->getMessage()."<br>";
        }
        try{
            if( $client->isAccessTokenExpired() ) {
                $client->refreshTokenWithAssertion($client->setAuthConfigFile(__DIR__ . '/OAuthClientServiceAccount2.json'));
            }
        }
        catch(Exception $e){
            echo "RefreshKey NOT OK<br>";
            echo $e->getMessage()."<br>";
        }
        $projectId = '123464155';
        $results = $analytics->data_ga->get(
                                            'ga:'.$projectId,
                                            '30daysAgo',
                                            'today',
                                            'ga:sessions,ga:users,ga:pageviews',
                                             array(
                                                'dimensions'  => 'ga:country',
                                                'sort'        => '-ga:sessions',
                                                'max-results' => 10
                                             ));
        $rows = $results->getRows();
        //var_dump($rows);
        $dataGA = array();
        foreach( $rows as $row ) {
            $dataGA[] = array(
              'country'   => $row[0],
              'sessions'  => $row[1],
              'users'     => $row[2],
              'pageviews' => $row[3]
            );
        }
        $res = json_encode($dataGA);
        return $res;
    }
    ?>
    

    祝你好运 Axel Arnold Bangert - Herzogenrath 2016