facebook php sdk - 如果用户没有授予权限,则会捕获(身份验证失败)

Mar*_*ski 5 php facebook user-permissions facebook-authentication facebook-php-sdk

文档说:"redirect_uri - (可选)在登录/授权过程完成后将用户重定向到的URL.用户将在登录成功和失败时重定向到URL,因此您必须检查URL中的错误参数如验证文档中所述.如果未指定此属性,则用户将被重定向到当前URL(即调用此方法的页面的URL,通常是用户浏览器中的当前URL).因此,有一种方法可以捕获用户是否拒绝了身份验证/权限,但是不再存在与相应文档的链接(https://developers.facebook.com/docs/authentication/).

为简单起见,redirect_uri与起始php文件的地址相同,php代码简单如下:

require 'facebook.php';
$facebook = new Facebook(array(
  'appId'  => 'X',
  'secret' => 'Y',
));
$user = $facebook->getUser();
if ($user) {
  try {
    $user_profile = $facebook->api('/me');
  } catch (FacebookApiException $e) {
    error_log($e);
    $user = null;
  }
}
if (!$user) {
  $params = array(
    'scope' => 'read_stream, friends_likes',
    'redirect_uri' => 'http://myapp.com/app'
  );
  $loginUrl = $facebook->getLoginUrl($params);
}
Run Code Online (Sandbox Code Playgroud)

谁知道如何捕获这些信息?

Alp*_*ale 11

您可以执行以下操作来检查权限:

$permissions = $facebook->api("/me/permissions");
if( array_key_exists('publish_stream', $permissions['data'][0]) ) {
    // Permission is granted!
    // Do the related task
    $post_id = $facebook->api('/me/feed', 'post', array('message'=>'Hello World!'));
} else {
    // We don't have the permission
    // Alert the user or ask for the permission!
    header( "Location: " . $facebook->getLoginUrl(array("scope" => "publish_stream")) );
}
Run Code Online (Sandbox Code Playgroud)