2

我正在尝试拨打电话以从 Google Analytics 获取数据。

<?php

require_once 'lib/apiClient.php';
require_once 'lib/contrib/apiAnalyticsService.php';
session_start();

$client = new apiClient();

$service = new apiAnalyticsService($client);

if (isset($_GET['logout'])) {
    unset($_SESSION['token']);
}

if (isset($_GET['code'])) {
    $client->authenticate();
    $_SESSION['token'] = $client->getAccessToken();
    $redirect = 'http://' . $_SERVER['HTTP_HOST'] . $_SERVER['PHP_SELF'];
    header('Location: ' . filter_var($redirect, FILTER_SANITIZE_URL));
}

if (isset($_SESSION['token'])) {
    $client->setAccessToken($_SESSION['token']);
}

if ($client->getAccessToken()) {
    $accounts = $service->management_accounts->listManagementAccounts();
    print "<h1>Accounts</h1><pre>" . print_r($accounts, true) . "</pre>";

    try {
        $data = $service->data_ga->get('ga:29214712', '2012-01-01', '2012-01-15',
            'ga:visits', array('dimensions' => 'ga:source,ga:keyword', 'sort' =>
            '-ga:visits,ga:source', 'filters' => 'ga:medium==organic', 'max-results' => '25'));
    }
    catch (apiServiceException $e) {
        echo $e->getCode();
        print_r($data);
    }

    $_SESSION['token'] = $client->getAccessToken();
} else {
    $authUrl = $client->createAuthUrl();
    print "<a class='login' href='$authUrl'>Connect Me!</a>";
}

在 TRY Catch 块中包装代码后,我收到以下错误

403

调用 GET https://www.googleapis.com/analytics/v3/data/ga?ids=ga%3A29214712&start-date=2012-01-01&end-date=2012-01-15&metrics=ga%3Avisits时出错:(403)禁止的

( ! ) 注意:未定义变量:第 43 行 C:\wamp\www\gitgrow\index.php 中的数据

注意:我已授予权限并已强制配置文件 ID 对其进行测试。

4

1 回答 1

2

您收到的 403 错误意味着授权用户无权访问您的查询中定义的 ga:29214712 报告配置文件。

查看 examples/analytics/demo 目录中的 HelloAnalyticsAPI.php 示例,并确保您可以连接到 API: http ://code.google.com/p/google-api-php-client/source/浏览/#svn%2Ftrunk%2Fexamples%2Fanalytics%2Fdemo

另外,请查看 Google Analytics(分析)开发人员指南。它将描述如何获取正确的配置文件 ID: https ://developers.google.com/analytics/devguides/reporting/core/v3/#user_reports

于 2012-05-29T20:30:07.877 回答