2011-06-03 178 views
0

我曾嘗試使用下面的代碼訪問的訪問令牌:獲得訪問令牌

$code=$_REQUEST['code']; 

if(empty($code)) { 
    $dialog_url = "http://www.facebook.com/dialog/oauth?client_id=" 
    . $app_id . "&redirect_uri=" . urlencode($my_url) 
    . "&scope=publish_stream,user_photo_video_tags"; 
    echo("<script>top.location.href='" . $dialog_url . "'</script>"); 
    } 

    $token_url = "https://graph.facebook.com/oauth/access_token?client_id=" 
    . $app_id . "&redirect_uri=" . urlencode($my_url) 
    . "&client_secret=" . $app_secret 
    . "&code=" . $code; 
    $response = file_get_contents($token_url); 
    $params = null; 
    parse_str($response, $params); 
    $access_token = $params['access_token']; 

它工作正常,但是當用戶試圖使用該應用程序第二次,也試圖不暢通授權用戶。

所以,我的問題是如何確保在試圖授權用戶時有平穩的流程?

回答

0

要做到用戶授權順利,我建議你使用最新Facebook PHP SDK

這裏是我的示例腳本處理用戶授權:

// init new facebook class instance with app info 
$facebook = new Facebook(array(
'appId' => 'YOUR APP ID', 
'secret' => 'YOUR APP SECRET' 
)); 

// get user UID 
$fb_user_id = $facebook->getUser(); 

// get the url where to redirect the user 
$location = "". $facebook->getLoginUrl(array('scope' => 'publish_stream')); 

// check if we have valid user 
if ($fb_user_id) { 
try { 
    // Proceed knowing you have a logged in user who's authenticated. 
    $fb_user_profile = $facebook->api('/me'); 

} catch (FacebookApiException $e) { 
    $fb_user_id = NULL; 
    // seems we don't have enough permissions 
    // we use javascript to redirect user instead of header() due to Facebook bug 
    print '<script language="javascript" type="text/javascript"> top.location.href="'. $location .'"; </script>'; 

    // kill the code so nothing else will happen before user gives us permissions 
    die(); 
} 

} else { 
// seems our user hasn't logged in, redirect him to a FB login page 

print '<script language="javascript" type="text/javascript"> top.location.href="'. $location .'"; </script>'; 

// kill the code so nothing else will happen before user gives us permissions 
die(); 
} 

// at this point we have an logged in user who has given permissions to our APP 
// basic user info can be fetched easily 
print "User access token is: ". $facebook->getAccessToken();