Google Analytics V3 API PHP

时间:2013-12-03 10:34:04

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

我正在尝试从我的Google分析帐户获取数据。我已经完成了这些步骤:

  1. 启用了Analytic的
  2. 的API访问权限
  3. 创建了OAuth2和服务器帐户以访问数据
  4. 添加了电子邮件地址(在代码中指定)以访问我的分析。
  5. 我在这里使用PHP客户端:https://github.com/google/google-api-php-client(Alpha)

    我收到的错误是: 出现错误: - (获取)未知参数:'start-date'

    任何帮助都会非常感激,因为我的头靠在墙上。

    我在下面提供了我的代码。

    `

    set_include_path("../src/" . PATH_SEPARATOR . get_include_path());
    require_once 'Google/Client.php';
    require_once 'Google/Service/Analytics.php';
    
    $client_id = 'xxx.apps.googleusercontent.com';
    $service_account_name = 'xxx@developer.gserviceaccount.com';
    $keyfile = 'xxx-privatekey.p12';
    $redirect_url = 'http://xxx/tags/v1.0.0-alpha/examples/analytics.php';
    $client_secret = 'xxx';
    
    // Initialise the Google Client object
    $client = new Google_Client();
    $client->setApplicationName('Your product name');
    $client->setRedirectUri($redirect_url);
    $client->setClientSecret($client_secret);
    
    $client->setAssertionCredentials(
            new Google_Auth_AssertionCredentials(
                $service_account_name,
                array('https://www.googleapis.com/auth/analytics'),
                file_get_contents($keyfile)
            )
    );
    
    // Get this from the Google Console, API Access page
    $client->setClientId($client_id);
    $client->setAccessType('offline_access');
    $analytics = new Google_Service_Analytics($client);
    
    // We have finished setting up the connection,
    // now get some data and output the number of visits this week.
    
    // Your analytics profile id. (Admin -> Profile Settings -> Profile ID)
    $analytics_id   = 'ga:xxx';
    $lastWeek       = date('Y-m-d', strtotime('-1 week'));
    $today          = date('Y-m-d');
    
    try {
        $results = $analytics->data_ga->get($analytics_id, $lastWeek, $today,'ga:visits');
        echo '<b>Number of visits this week:</b> ';
        echo $results['totalsForAllResults']['ga:visits'];
    } catch(Exception $e) {
        echo 'There was an error : - ' . $e->getMessage();
    }
    

    `

1 个答案:

答案 0 :(得分:4)

不确定您是否自己找到了这个问题的答案,但我遇到了同样的问题并通过修改第93行的 apiclient / src / Google / Service / Analytics.php 文件解决了这个问题&安培; 98

          "start_date" => array(
              "location" => "query",
              "type" => "string",
              'required' => true,
          ),
            "end_date" => array(
              "location" => "query",
              "type" => "string",
              'required' => true,
          ),

需要成为:

        "start-date" => array(
              "location" => "query",
              "type" => "string",
              'required' => true,
          ),
            "end-date" => array(
              "location" => "query",
              "type" => "string",
              'required' => true,
          ),