[英]Authentication Errors Trying to Access to the Google Analytics API via http (not using oAuth)
我正在尝试构建一个简单的脚本,以导入通过CMS发布的文章的页面浏览量。 我使用Google Analytics(分析)API查询构建器轻松构建了查询,该构建器可快速返回所需结果。 我的Web服务器上的计划作业将每天运行一次查询,并更新和浏览量。
因为我只获取综合浏览量,所以我认为没有必要完成整个oAuth流程。 这个Google帐户只有一个网络媒体资源和一个配置文件,因此不需要常规程序就可以实现。
我注册了一个应用并创建了API密钥。 我已确保为此配置文件打开Google Analytics(分析)。 根据对API的阅读,我相信可以将此键作为http参数传递,以正确授权查询。
通过http运行查询时,出现授权错误(401)。 该查询包括在下面:
https://www.googleapis.com/analytics/v3/data/ga?ids=ga%3A[MY ID]&metrics=ga%3Apageviews&start-date=2012-08-09&end-date=2012-08-23&max-results=50&key=[MY API KEY]
我已经在Google上搜索了许多示例,但是它们似乎都实现了非常复杂的认证例程(在我的用例中是不必要的)。 但是也许我想念一些东西。
提前谢谢了。
使用此示例修复401错误http://dumitruglavan.com/ganalytics-class-access-google-analytics-data-api-with-php/
您需要授权:
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "https://www.google.com/accounts/ClientLogin");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POST, true);
$data = array(
'accountType' => 'GOOGLE',
'Email' => $email,
'Passwd' => $password,
'service' => 'analytics',
'source' => ''
);
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
$output = curl_exec($ch);
$info = curl_getinfo($ch);
curl_close($ch);
$auth = '';
if($info['http_code'] == 200) {
preg_match('/Auth=(.*)/', $output, $matches);
if(isset($matches[1])) {
$auth = $matches[1];
} else {
throw new Exception('Login failed with message: ' . $output);
}
}
在授权后,在标题中发送授权令牌:
$headers = array("Authorization: GoogleLogin auth=$auth");
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
$output = curl_exec($ch);
$info = curl_getinfo($ch);
curl_close($ch);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.