谷歌分析和网站站长API的起点



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

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

我注册了一个应用程序并在其中启用了分析 API,但没有网站站长 API。我对 oAuth 也没有清晰的了解。有没有办法不每次都重定向和请求新的访问令牌?这就像从我的 ip 授予我的帐户中的应用程序的永久访问权限,而无需进一步确认。

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

以下代码将帮助您使用脱机访问 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 和客户端密码。

对于您的用例,我建议使用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
  })

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

相关内容

  • 没有找到相关文章

最新更新