【发布时间】:2016-01-21 17:24:37
【问题描述】:
首先我不得不说我真的对 Googles API 和文档感到困惑,我现在已经尝试了很多不同的方法,但我确实想了解它,我终于找到了一些可以指导我的代码完成它我只是有一个小问题,每次我刷新我的页面时,我都会丢失由 Google 的 api 制作的会话,我不知道为什么。
$client = new Google_Client();
$client->setScopes(array('https://www.googleapis.com/auth/analytics.readonly'));
$client->setAccessType('offline'); // Gets us our refreshtoken
// Step 2: The user accepted your access now you need to exchange it.
if (isset($_GET['code'])) {
$client->authenticate($_GET['code']);
$_SESSION['token'] = $client->getAccessToken();
$redirect = 'http://' . $_SERVER['HTTP_HOST'] . $_SERVER['PHP_SELF'];
header('Location: ' . filter_var($redirect, FILTER_SANITIZE_URL));
}
// Step 1: The user has not authenticated we give them a link to login
if (!$client->getAccessToken() && !isset($_SESSION['token'])) {
$authUrl = $client->createAuthUrl();
print "<a class='login' href='$authUrl'>Connect Me!</a>";
}
// Step 3: We have access we can now create our service
if (isset($_SESSION['token'])) {
print "<a class='logout' href='".$_SERVER['PHP_SELF']."?logout=1'>LogOut</a><br>";
$client->setAccessToken($_SESSION['token']);
$service = new Google_Service_Analytics($client);
// request user accounts
$accounts = $service->management_accountSummaries->listManagementAccountSummaries();
foreach ($accounts->getItems() as $item) {
echo "Account: ",$item['name'], " " , $item['id'], "<br /> \n";
foreach($item->getWebProperties() as $wp) {
//echo ' WebProperty: ' ,$wp['name'], " " , $wp['id'], "<br /> \n";
$views = $wp->getProfiles();
if (!is_null($views)) {
foreach($wp->getProfiles() as $view) {
echo ' View: ' ,$view['name'], " " , $view['id'], "<br /> \n";
}
}
}
} // closes account summaries
}
print_r($_SESSION['token']);
?>
我尝试关注这篇文章http://www.daimto.com/google-oauth2-php/。还有一个额外的问题,我下一步检索用户分析数据是什么?希望有人没有像我一样困惑,并且可以提供帮助。我也使用 Laravel 5.2 作为框架
【问题讨论】:
-
我推荐你使用这个包:github.com/spatie/laravel-analytics
-
我看了这个,真的不知道如何设置用户身份验证,也许我再看看
-
我花了 2 个小时来弄清楚如何设置它,更大的问题是谷歌控制台 UX。我会尽力帮助你。您在文档中的哪个位置?
-
目前我不确定,我阅读了很多不同的指南等,我就在附近,但我认为我正处于必须刷新令牌的地步。(developers.google.com/identity/protocols/OAuth2WebServer)但我不完全确定
-
我说的是 spatie/laravel-analytics。我以为你在关注它。
标签: laravel google-api google-analytics-api google-api-client google-oauth