3

Do you have an example of how to confirm that the person trying to access the content of your app is a member of a specific facebook group, using php? I've read through the developer docs and all it managed to do was confuse me even more. I've seen posts similar to this one but they only show me how to print a list of members...

I need to know how to get the list and see if the user trying to access the app is a member of the group so that I can either a: allow access or b: deny access and re-direct the user to the group page so they can request membership...

ekad
  • 14,436
  • 26
  • 44
  • 46

2 Answers2

4

Yes its pretty simple, you just need to know the ID of the group you want to do that and ask for the scope user_groups permission, so you can query the groups the user have.

With the PHP SDK you can do this:

<?php
  // Remember to copy files from the SDK's src/ directory to a
  // directory in your application on the server, such as php-sdk/
  require_once('php-sdk/facebook.php');

  $config = array(
    'appId' => 'YOUR_APP_ID',
    'secret' => 'YOUR_APP_SECRET',
  );

  $facebook = new Facebook($config);
  $user_id = $facebook->getUser();
if($user_id) {

      // We have a user ID, so probably a logged in user.
      // If not, we'll get an exception, which we handle below.
      try {

        $user_profile = $facebook->api('/me?fields=id,name,groups','GET');
        $user_belongs_to_group= FALSE;
        foreach($user_profile['groups']['data'] as $group){
          if($group['id']==YOUR_GROUP_ID)
           $user_belongs_to_group=TRUE;
        }
        if($user_belongs_to_group){
         //Alright! the user belongs to the group
        }
        else{
          //Oh snap you don't belong here, but you can if want to
        }

      } catch(FacebookApiException $e) {
        // If the user is logged out, you can have a 
        // user ID even though the access token is invalid.
        // In this case, we'll get an exception, so we'll
        // just ask the user to login again here.
        $login_url = $facebook->getLoginUrl(); 
        echo 'Please <a href="' . $login_url . '">login.</a>';
        error_log($e->getType());
        error_log($e->getMessage());
      }   
    } else {

      // No user, print a link for the user to login
      $login_url = $facebook->getLoginUrl();
      echo 'Please <a href="' . $login_url . '">login.</a>';

        }

?>

Some of this code I grabbed from the facebook, you can see the data that is returned when query for groups here: https://developers.facebook.com/tools/explorer

Press the plus sign after the name go to connections, choose groups and press send

Fabio Antunes
  • 22,251
  • 15
  • 81
  • 96
0

You are in a catch-22, you will need the user to grant permission to his groups via the user_groups permission.

phwd
  • 19,975
  • 5
  • 50
  • 78