【问题标题】:Google Analytics API from localhost来自本地主机的 Google Analytics API
【发布时间】:2015-05-07 13:30:12
【问题描述】:

使用 php 脚本使用 Google PHP Client API 从 Google Analytics 中提取数据。我已经在 localhost/ga/ 设置了脚本。

我的 API 密钥已全部设置完毕,Analytics API 已开启。

在“Web 应用程序的客户端 ID”中:

REDIRECT URIS  http://localhost/ga/
JAVASCRIPT ORIGINS http://localhost

在“浏览器应用程序密钥”中:

REFERERS  http://localhost/*

仔细检查了所有密钥、ID 和机密。但是我收到了这个错误:

"(403) There is a per-IP or per-Referer restriction configured on your API key and the request does not match these restrictions. Please use the Google Developers Console to update your API key configuration if request from this IP or referer should be allowed."

我当前的代码:

$client = new Google_Client();
$client->setApplicationName('GA Test');
$client->setClientId($cred['id']);
$client->setClientSecret($cred['secret']);
$client->setRedirectUri($cred['redirect']);
$client->setDeveloperKey($cred['api_key']);
$client->setScopes(array('https://www.googleapis.com/auth/analytics.readonly'));

if (isset($_GET['code'])) {
    $client->authenticate($_GET['code']);
    $_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->isAccessTokenExpired()) {
    $authUrl = $client->createAuthUrl();
    header('Location: ' . filter_var($authUrl, FILTER_SANITIZE_URL));
}

if (!$client->getAccessToken()) {
    $authUrl = $client->createAuthUrl();
    echo '<a class="login" href="'.$authUrl.'">Connect Me!</a>';
} else {
    $analytics = new Google_Service_Analytics($client);
    try {
        $optParams = array(
            'dimensions' => 'ga:source,ga:keyword',
            'sort' => '-ga:sessions,ga:source',
            'filters' => 'ga:medium==organic',
            'max-results' => '25'
        );
        $dump =  $analytics->data_ga->get(
            'ga:52371304',
            '2015-01-01',
            '2015-03-01',
            'ga:sessions',
            $optParams
        );
        var_dump($dump);
        echo 'hi!';
    } catch(Exception $e) {
        echo $e->getMessage();
    }
}

知道我做错了什么吗?

【问题讨论】:

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


    【解决方案1】:

    我想通了。呸。

    我生成的公钥是浏览器密钥而不是服务器密钥。您可以将 IPs 字段留空,它将与 localhost 一起使用。

    【讨论】:

      猜你喜欢
      • 2014-09-14
      • 2013-11-15
      • 2018-12-19
      • 1970-01-01
      • 2018-04-04
      • 2014-09-13
      • 2021-12-24
      • 2017-01-12
      • 2016-07-16
      相关资源
      最近更新 更多