简体   繁体   English

来自localhost的Google AnalyticsAPI

[英]Google Analytics API from localhost

Working on a php script to pull data from Google Analytics with the Google PHP Client API. 使用php脚本通过Google PHP客户端API从Google Analytics中提取数据。 I've got the script set up at localhost/ga/. 我已经在localhost / ga /设置了脚本。

Got my API keys all set up, Analytics API turned on. 设置了所有API密钥,启用了Analytics API。

In "Client ID for Web application": 在“Web应用程序的客户端ID”中:

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

In "Key for browser application": 在“浏览器应用程序密钥”中:

REFERERS  http://localhost/*

Double checked all keys,ids, and secrets. 双重检查所有密钥,ID和密码。 But I'm getting this error: 但是我收到了这个错误:

"(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."

My current code: 我目前的代码:

$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();
    }
}

Any idea what I might be doing wrong? 知道我可能做错了什么吗?

I figured this out. 我想通了。 Bah. 呸。

The Public Key I generated was the browser key not the server key. 我生成的公钥是浏览器密钥而不是服务器密钥。 You can leave the IPs field blank and it will work with localhost. 您可以将IP字段留空,它将与localhost一起使用。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM