0

我的谷歌分析帐户中有大约 50 个网站。我想做一些研究,创建通知系统并将分析数据与其他来源的数据进行比较。

这意味着我想每天两次为每个站点获取十几个报告。我解析它们并存储在mysql中。最简单的方法是什么?

我注册了一个应用程序并在其中打开了分析 api,但是没有网站管理员 api。我对oAuth也没有清楚的了解。有没有一种方法不需要每次都重定向和请求新的访问令牌?这就像在没有进一步确认的情况下从我的 ip 授予我帐户中我的应用程序的永久访问权限。

那么,对于初学者来说,有没有用 php、perl 或 ruby​​ 编写的关于从分析和网站管理员中检索数据的好教程?

4

2 回答 2

0

以下代码将帮助您使用 oauth 流的离线访问来检索“刷新令牌”。您可以使用此刷新令牌来获取访问令牌,而不会打扰用户。

确保您在 API 控制台中提到的重定向 Uri 应该与您将在其中放置以下代码的文件名相同。

例如。如果重定向 uri 是:- http://test.com/google_oauth.php 那么下面的脚本应该放在:- google_oauth.php (路径:http://test.com/google_oauth.php

<?php
$OAuth = array(
    'oauth_uri' => 'https://accounts.google.com/o/oauth2/auth',
    'client_id' => '#clientId',
    'client_secret' => '#clientSecret',
    'access_type' => 'offline',
    'redirect_uri' => 'http://test.com/google_oauth.php',   //this url should be same as you had registered in your api console as redirect uri()
    'oauth_token_uri' => 'https://accounts.google.com/o/oauth2/token'

);
$token = array(
    'access_token' => '',
    'token_type' => '',
    'expires_in' => '',
    'refresh_token' => ''
);

$title = 'No Code';
$AuthCode = 'Null';

// see if error parameter exisits
$error = _get_url_param($_SERVER['REQUEST_URI'], 'error');
if ($error != NULL)
{   // this means the user denied api access to GWMTs
    $title = $error;
}
else
{   // does the code parameter exist?
    $AuthCode = _get_url_param($_SERVER['REQUEST_URI'], 'code');
    if ($AuthCode == NULL)
    {   // get authorization code
        $OAuth_request = _formatOAuthReq($OAuth, "https://www.googleapis.com/auth/analytics.readonly");

        header('Location: ' . $OAuth_request);
        exit; // the redirect will come back to this page and $code will have a value
    }
    else
    {
        $title = 'Got Authorization Code';
        // now exchange Authorization code for access token and refresh token
        $token_response = _get_auth_token($OAuth, $AuthCode);
        $json_obj = json_decode($token_response);
        $token['access_token'] = $json_obj->access_token;
        $token['token_type'] = $json_obj->token_type;
        $token['expires_in'] = $json_obj->expires_in;
        $token['refresh_token'] = $json_obj->refresh_token;
        echo 'access_token = ' . $json_obj->access_token;
    }
}

function _get_auth_token($params, $code)
{
    $url = $params['oauth_token_uri'];

    $fields = array(
        'code' => $code,
        'client_id' => $params['client_id'],
        'client_secret' => $params['client_secret'],
        'redirect_uri' => $params['redirect_uri'],
        'grant_type' => 'authorization_code'
    );
    $response = _do_post($url, $fields);
    return $response;
}

function _do_post($url, $fields)
{
    $fields_string = '';

    foreach ($fields as $key => $value)
    {
        $fields_string .= $key . '=' . $value . '&';
    }
    $fields_string = rtrim($fields_string, '&');

    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_POST, count($fields));
    curl_setopt($ch, CURLOPT_POSTFIELDS, $fields_string);
    $response = curl_exec($ch);
    curl_close($ch);

    return $response;
}

function _formatOAuthReq($OAuthParams, $scope)
{
    $uri = $OAuthParams['oauth_uri'];
    $uri .= "?client_id=" . $OAuthParams['client_id'];
    $uri .= "&redirect_uri=" . $OAuthParams['redirect_uri'];
    $uri .= "&scope=" . $scope;
    $uri .= "&response_type=code";
    $uri .= "&access_type=offline";


    return $uri;
}

function _get_url_param($url, $name)
{
    parse_str(parse_url($url, PHP_URL_QUERY), $params);
    return isset($params[$name]) ? $params[$name] : null;
}

function _get_refresh_token($params, $code)
{
    $url = $params['oauth_token_uri'];

    $fields = array(
        'code' => $code,
        'client_id' => $params['client_id'],
        'client_secret' => $params['client_secret'],
        'refresh_token' => $token['refresh_token'],
        'grant_type' => 'refresh_token'
    );
    $response = _do_post($url, $fields);
    return $response;
}
?>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <title><?= $title; ?></title>
    </head>
    <body>
        <h1>OAuth2 Authorization Code</h1>
        <p>Authorization Code: <?= $AuthCode; ?></p>
        <p>access token: <?= $token['access_token']; ?></p>
        <p>expires in: <?= $token['expires_in']; ?></p>
        <p>refresh token: <?= $token['refresh_token']; ?></p>
        <p></p>

    </body>
</html>

获得刷新令牌后,您可以使用以下代码从谷歌分析中获取数据:-

<?php
$refresh_token='#refresh-token';
$fields_string = "client_id=#ClientId&client_secret=#clientSecret&refresh_token=$refresh_token&grant_type=refresh_token";
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 'https://accounts.google.com/o/oauth2/token');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POST, count($fields));
curl_setopt($ch, CURLOPT_POSTFIELDS, $fields_string);
$token_response = curl_exec($ch);
$json_obj = json_decode($token_response);
$access_token = $json_obj->access_token;
curl_close($ch);



$url = "https://www.googleapis.com/analytics/v3/data/ga?ids=ga:30566906&start-date=2013-01-01&end-date=2013-04-16&dimensions=ga:medium&metrics=ga:visits,ga:bounces";
$ch = curl_init();
curl_setopt($ch, CURLOPT_HTTPHEADER, array("Authorization: Bearer $access_token"));
curl_setopt($ch, CURLOPT_URL, html_entity_decode($url));
curl_setopt($ch, CURLOPT_USERAGENT, "Mozilla/4.0 (compatible; MSIE 5.01; Windows NT 5.0)");
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, TRUE);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); 
$output = curl_exec($ch);
$json_obj = json_decode($output);
$test=$json_obj->columnHeaders;
foreach($test as $a){
    var_dump($a);

}
curl_close($ch);
?>

在上面的脚本中:-
#clientId 和 #clientSecret 应该替换为您在注册 Web 应用程序时收到的客户端 ID 和客户端密码。

于 2013-11-10T13:35:28.267 回答
0

对于您的用例,我建议使用Google 服务帐户而不是需要人工确认的 OAuth 流程。

有多种语言的客户端库可以使 OAuth 部分更简单。例如,在ruby​​ 库中包含一个示例脚本,显示如何将服务帐户与 Google Analytics API 一起使用。本质上是这样的:

@client = Google::APIClient.new(
  :application_name => opts['application_name'],
  :application_version => opts['application_version'])

## Load our credentials for the service account
key = Google::APIClient::KeyUtils.load_from_pkcs12(key_file, key_secret)

@client.authorization = Signet::OAuth2::Client.new(
  :token_credential_uri => 'https://accounts.google.com/o/oauth2/token',
  :audience => 'https://accounts.google.com/o/oauth2/token',
  :scope => 'https://www.googleapis.com/auth/analytics.readonly',
  :issuer => service_account_email,
  :signing_key => key)

## Request a token for our service account
@client.authorization.fetch_access_token!

query_data = @client.execute(:api_method => @analytics.data.ga.get, :parameters => {
    'ids' => "ga:" + @profileID,
    'start-date' => @startDate,
    'end-date' => @endDate,
    'dimensions' => dimension,
    'metrics' => metric,
    'sort' => sort
  })

有一个Webmaster API 可用,尽管它无权访问查询数据。您可以通过这个 Google 发布的python 脚本或通过PHP 中具有更多数据的类似脚本来获得它。

于 2015-05-26T21:41:13.447 回答