簡體   English   中英

來自localhost的Google AnalyticsAPI

[英]Google Analytics API from localhost

使用php腳本通過Google PHP客戶端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();
    }
}

知道我可能做錯了什么嗎?

我想通了。 呸。

我生成的公鑰是瀏覽器密鑰而不是服務器密鑰。 您可以將IP字段留空,它將與localhost一起使用。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM