首页 > 解决方案 > 是否可以从 GA 获取链接的当前访问次数?

问题描述

我有一个仪表板、CMS,并且客户希望查看十几个链接的当前视图数量。所以,我想知道我是否可以从谷歌分析中得到它。我发送带有链接的请求,GA 只返回数字,每个用户都必须看到这些数字,即使他们不是这个页面的 GA 管理员。

先感谢您。

标签: javascriptphpjqueryajaxgoogle-analytics

解决方案


因此,对于任何有相同/类似问题的人:

  1. 检查此链接:如何在不登录的情况下访问 cron 作业中的谷歌分析数据?
  2. 创建连接到您在进程中创建的服务帐户的 .p12 文件
  3. 您更改参数,以便获得实时

您可以查看我的代码以供参考(这只是测试代码):

 require_once 'Google/autoload.php';
   session_start();
/************************************************
 The following 3 values an befound in the setting
 for the application you created on Google
 Developers console.         Developers console.
 The Key file should be placed in a location
 that is not accessable from the web. outside of
 web root.       web root.

 In order to access your GA account you must
 Add the Email address as a user at the
 ACCOUNT Level in the GA admin.
 ************************************************/
    $client_id = '[your_service_account_id]';
    $Email_address = '[your_service_email_account]';
    $key_file_location = '[.p12_file_location]'
    $client = new Google_Client();
    $client->setApplicationName("Client_Library_Examples");
    $key = file_get_contents($key_file_location);

    // seproate additional scopes with a comma
    $scopes ="https://www.googleapis.com/auth/analytics.readonly";

    $cred = new Google_Auth_AssertionCredentials($Email_address,
                             array($scopes),
                             $key);

    $client->setAssertionCredentials($cred);
    if($client->getAuth()->isAccessTokenExpired()) {
         $client->getAuth()->refreshTokenWithAssertion($cred);
    }

    $service = new Google_Service_Analytics($client);



    //Adding Dimensions
    $params = array('dimensions' => 'rt:medium');
    // requesting the data
    $results = $service->data_realtime->get(
      'ga:[your_view_id]',
      'rt:activeUsers',
      $params);
?>

<html>
    <table border="1">
        <tr>
        <?php
        //Printing column headers
        foreach($results->getColumnHeaders() as $header){
             print "<td><b>".$header['name']."</b></td>";
            }
        ?>
        </tr>
        <?php
        //printing each row.
        foreach ($results->getRows() as $row) {
            print "<tr><td>".$row[0]."</td><td>".$row[1]."</td><td>".$row[2]."</td></tr>";
        }

        $totals = $results->getTotalsForAllResults();

        $html='';
        foreach ($totals as $metricName => $metricTotal) {
            $html .= "Metric Name  = $metricName\n";
            $html .= "Metric Total = $metricTotal";
        }

?>
<tr><td colspan="2">Rows Returned <?php print $results->getTotalResults();?> </td></tr>
</table>

<?php print $html; ?>
</html>

推荐阅读