正在获取访问令牌


Getting Access Token

我尝试使用以下代码访问访问令牌:

$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'];

它工作得很好,但当用户第二次尝试使用该应用程序时,在尝试授权用户时就无法顺利进行。

所以,我的问题是,在尝试授权用户时,我如何确保流畅?

为了顺利完成用户授权,我建议您使用最新的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();