Facebook PHP SDK:检查用户是否已授予某组权限

时间:2015-10-29 00:41:13

标签: php facebook laravel-5 facebook-php-sdk

我想检查用户是否已授权以下权限;对于我的应用,' manage_pages',' publish_pages' read_insights' 。简而言之,如果他们拒绝一个或多个权限,我需要知道,因为所有权限都是必需的。

一旦我获得了用户的访问令牌,这就是我的回调方法。如何验证他们是否批准了所有权限请求?

注意: 我使用的是SammyK Laravel Facebook SDK软件包。

public function handleFacebookCallback()
    {
        try {
            $token = Facebook::getAccessTokenFromRedirect();

            $user = Facebook::get('/me?fields=permissions', $token)->getGraphUser();
            $permissions = $user['permissions']->asArray();

            // permissions: 'manage_pages', 'publish_pages', 'read_insights'

            if (array_key_exists('publish_pages', $permissions['data'][0]))
            {
                // permissions exist, proceed
            }
            else 
            {
                // user denied permission(s), redirect
            }
        }
        ....

2 个答案:

答案 0 :(得分:1)

根据mesosphere,您可以致电Facebook Graph API以获取用户授予应用的所有权限。

$request = new FacebookRequest(
  $session,
  'GET',
  '/me/permissions'
);

$response = $request->execute();
$graphObject = $response->getGraphObject();
/* handle the result */

foreach($graphObject as $permission) {
        if($permission->permission == 'publish_pages' AND $permission->status == 'granted') {
            // User has granted publish_pages permission
    }
}

您可以调试此来电user/permissions,但我没有对其进行测试,但它应该有效。

答案 1 :(得分:0)

不确定这是否是最简单的答案或其他人如何接近这一点,但这就是我想出来的......

try {
    $token = Facebook::getAccessTokenFromRedirect();

    $request = Facebook::get('/me?fields=permissions', $token);
    $user = $request->getGraphUser();
    $permissions = $user['permissions'];

    // if user denied ANY of the required permissions
    foreach ($permissions as $p => $permission) 
    {
        if ($permission['status'] !== 'granted')
        {
            return redirect()->route('connect.index')->withErrors('Error: We require all permissions in order to connect your Facebook page.');
        }
    }
}