几天来,我一直在努力让 Google API 在我的网站上运行,但一直没有成功。在我搜索的所有地方,我都能找到过时的示例...我需要它与 codeigniter 一起工作,我想做的就是从 Google Analytics 获取数据,以显示在我的 codeigniter 网站的管理仪表板中。
我知道我需要一个服务帐户,如果我不想每次查看仪表板时都进行身份验证(?)
任何人都可以帮我让它工作吗?非常感谢您!
我想做的是:从谷歌分析中获取数据,返回数据可能是 json,然后我想我可以用插件制作图表(也许一些 jQuery 插件已经存在,或者我可以使用谷歌自己的图表抽屉?)并将其显示给管理员。我只想要非常简单的数据,例如,上个月有多少用户...
最佳答案
大约一周后 - 当然,在我发布这个问题的同一天,我终于设法自己解决了这个问题。
我是这样的:
我从 their github 下载了最新的 Google 客户端 API(用于 php) .
我在我的 application/third_party 文件夹中添加了 Google 文件夹 (src)。
在我的 Controller 中,我通过执行以下操作包含了所需的文件:
require_once(BASEPATH . '../application/third_party/Google/Client.php');
require_once(BASEPATH . '../application/third_party/Google/Service/Analytics.php');
然后我在下面添加了以下代码以使用服务帐户进行授权(您从 Google Console 获得并选择您的项目 > APIs & auth > Credentials > 然后创建一个新的客户端 ID,选择服务帐户,完成后,按“生成新的 p12 key ”并将该 key 添加到您的 third_party/Google 文件夹:
session_start();
$client_id = '<YOUR_CLIENT_ID>'; //Client ID
$service_account_name = '<YOUR_CLIENT_EMAIL>'; //Email Address
$key_file_location = BASEPATH . '../application/third_party/Google/<YOUR KEY.p12>'; //key.p12
$client = new Google_Client();
$client->setApplicationName("ApplicationName");
$service = new Google_Service_Analytics($client);
if (isset($_SESSION['service_token'])) {
$client->setAccessToken($_SESSION['service_token']);
}
$key = file_get_contents($key_file_location);
$cred = new Google_Auth_AssertionCredentials(
$service_account_name,
array(
'https://www.googleapis.com/auth/analytics',
),
$key,
'notasecret'
);
$client->setAssertionCredentials($cred);
if($client->getAuth()->isAccessTokenExpired()) {
$client->getAuth()->refreshTokenWithAssertion($cred);
}
$_SESSION['service_token'] = $client->getAccessToken();
下面的代码用于获取过去 31 天的 session (页面访问)
$analytics = new Google_Service_Analytics($client);
$profileId = "ga:<YOUR_PROFILE_ID>";
$startDate = date('Y-m-d', strtotime('-31 days')); // 31 days from now
$endDate = date('Y-m-d'); // todays date
$metrics = "ga:sessions";
$optParams = array("dimensions" => "ga:date");
$results = $analytics->data_ga->get($profileId, $startDate, $endDate, $metrics, $optParams);
$data['report'] = $results->rows; //To send it to the view later
要获取您可以使用的所有维度和指标,use this link . 有关如何将其发送到 View 的示例:
$this->view->load('your_view', $data);
为了将其写成图表,我刚刚使用了 Google charts ,在 JS 中(在 View 中)我只是循环 $data['report'] 中的数据来绘制图表。
希望这对以后遇到这个问题的人有所帮助。
关于php - Codeigniter 网站上的 Google Analytics API,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25668009/