【发布时间】:2012-11-08 01:50:22
【问题描述】:
我正在尝试使用 PHP 获取我的 Google Analytics 帐户的一些信息。我已经按照在 Google Console API in this answer 中创建服务帐户的步骤进行了操作。我正在使用Google API Client for PHP。
这是我目前得到的代码:
<?php
$path_to_src = 'src';
// These files are in /src, upload its contents to your web server
require_once $path_to_src . '/Google_Client.php';
require_once $path_to_src . '/contrib/Google_AnalyticsService.php';
$path_to_keyfile = '***'; //my private key
// Initialise the Google Client object
$client = new Google_Client();
// Your 'Product name'
$client->setApplicationName('My App Name');
$client->setAssertionCredentials(
new Google_AssertionCredentials(
'**', //gserviceaccount mail
array('https://www.googleapis.com/auth/analytics.readonly'),
file_get_contents($path_to_keyfile)
)
);
// Get this from the Google Console, API Access page
$client->setClientId('***'); // my cliente ID
$client->setAccessType('offline_access');
$analytics = new Google_AnalyticsService($client);
// create service and get data
$service = new Google_AnalyticsService($client);
// We have finished setting up the connection,
// now get some data and output the number of visits this week.
// Your analytics profile id. (Admin -> Profile Settings -> Profile ID)
$analytics_id = 'ga:****'; // my profile id
$lastWeek = date('Y-m-d', strtotime('-1 week'));
$today = date('Y-m-d');
try {
$results = $analytics->data_ga->get($analytics_id,
$lastWeek,
$today,'ga:visits');
echo '<b>Number of visits this week:</b> ';
echo $results['totalsForAllResults']['ga:visits'];
} catch(Exception $e) {
echo 'There was an error : - ' . $e->getMessage();
}
我在 PHP 中启用了openssl 扩展:
当浏览到 php 脚本的位置时,我只是得到一个几乎永远加载和以下错误:
我使用的是 PHP 5.4.7:
调试 Google API 客户端代码后,脚本似乎在这一行中断:
if (!openssl_sign($data, $signature, $this->privateKey, "sha256"))
这条线以下的任何东西都不会被调用。看起来错误发生在这一行。这里有不兼容的地方,还是什么?
【问题讨论】:
-
您提到的 API 客户端代码的最后一行代码追溯到哪一行?
-
这是用我的私钥对我进行身份验证的线路。我不确切知道代码是什么,但我遵循并设法到达那里。
openssl_sign行出于某种原因给了我这个Error 101。 -
我认为您调用上周开始日期的方式可能存在问题。看看这个教程。它可能有用。 developers.google.com/analytics/solutions/articles/…
-
如果您确定这是产生错误的行,我建议暂时为所有 openssl_sign() 参数添加 var_dumps 以查看是否将它们中的任何一个设置为奇怪的东西。不过,您可能不应该在此处发布您的 var_dump'd 私钥。只要注意它是否为空或什么。
-
另外:你的钥匙上有密码吗?