Google Analytics Api在刷新时删除会话

时间:2016-01-21 17:24:38

标签: laravel google-api google-analytics-api google-api-client google-oauth2

我首先要说的是我真的很困惑谷歌API和我现在尝试了很多不同方法的文档,但是我们想要了解它,我终于找到了一些代码可以指导我走向完成它我只是有一个小问题,每次我刷新我的页面我失去了谷歌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 '&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;WebProperty: ' ,$wp['name'], "  " , $wp['id'], "<br /> \n";    

        $views = $wp->getProfiles();
        if (!is_null($views)) {
            foreach($wp->getProfiles() as $view) {
            echo '&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;View: ' ,$view['name'], "  " , $view['id'], "<br /> \n";    
            }
        }
    }
} // closes account summaries

}
 print_r($_SESSION['token']); 
?>

我尝试过这篇文章http://www.daimto.com/google-oauth2-php/。还有一点额外的问题,我下一步检索用户分析数据是什么?希望有人在那里不像我一样困惑,并可以提供帮助。我也使用Laravel 5.2作为框架

1 个答案:

答案 0 :(得分:0)

只需使用https://github.com/OzanKurt/google-analytics/就可以了。 ;)