获取访问令牌

时间:2011-06-03 06:50:01

标签: php facebook api 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'];

它运行正常但是当用户第二次尝试使用该应用程序时,尝试授权用户时没有顺畅的流程。

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

1 个答案:

答案 0 :(得分: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();