2014-01-14 32 views
0

我正在使用Facebook SDK獲取Facebook好友列表。如果我用JavaScript調用API FB.init();它完美罰款..php必須使用活動訪問令牌來查詢

但如果我直接使用它像

facebook = new Facebook(array(
'appId' => $appid, 
'secret' => $secret 
)); 

$fbuser = $facebook->getUser(); 
try{ 
    $user_profile = $facebook->api('/me'); 
    print_r($user_profile); 
} catch(Exception $e){ 
    echo $e->getMessage(); 
} 

(用戶登錄與在同一瀏覽器的Facebook) 它總是給我一個錯誤:一個活躍的訪問令牌必須是用於查詢有關當前用戶的信息。

請幫助我如何使用它沒有FB.init()或任何重定向..

回答

3

使用此

facebook = new Facebook(array(
'appId' => $appid, 
'secret' => $secret, 
'cookie' => true 
)); 

$fbuser = $facebook->getUser(); 
if($fbuser){ 
    $access_token = $facebook->getAccessToken(); 
    $facebook->setAccessToken($access_token); 
    try{ 
     $user_profile = $facebook->api('/me'); 
     print_r($user_profile); 
    } catch(Exception $e){ 
     echo $e->getMessage(); 
    } 
}else{ 
    // User not logged in generate the login button or link here 
} 

確保在上面的腳本,當用戶登錄ffor首次將重換句話說,你的頁面需要提供REDIRECT_URI https://developers.facebook.com/docs/reference/php/facebook-getLoginUrl/

您也可以使用下面的API來獲取用戶的詳細信息

$user_profile = $facebook->api('/'. $fbuser,'GET'); 

然後在頁面下方添加以下內容。這將檢查用戶是否已經登錄,將重新定向到同一頁,換句話說,它不會要求用戶重新登錄

<div id="fb-root"></div> 

<script type="text/javascript"> 
    window.fbAsyncInit = function() 
      { 
       FB.init 
       ({ 
        appId : 'your fb app id', 
        status : true, // check login status 
        cookie : true, // enable cookies to allow the server to access the session 
        xfbml : true, // parse XFBML 
        oauth : true 
       }); 
       FB.Event.subscribe('auth.login', function() 
       { 
        window.location.reload(); 
       }); 
      }; 

      (function() 
      { 
      var e = document.createElement('script'); 
      e.src = document.location.protocol + '//connect.facebook.net/en_US/all.js'; 
      e.async = true; 
      document.getElementById('fb-root').appendChild(e); 
      }()); 
</script> 
+0

是它的工作原理,但只有一些時間,第一次給我同樣的錯誤..「訪問令牌」,第二次..它的工作原理,第三次再次錯誤..第四次..再次它的作品..任何想法,爲什麼發生? –

+0

是的,一旦用戶登錄,您需要將用戶重定向到同一頁面,您可以發佈您添加的登錄腳本嗎?或者我們需要標記頁面下方的JS代碼,如果你願意,我可以爲你添加該代碼? –

+0

我修改了答案讓我知道如果仍然有問題。 'cookie'=> true在api中給出。 –

相關問題