Facebook – Accessing a user’s friends via the Facebook Graph API

facebookfacebook-graph-apioauth

Has anybody successfully accessed the list of a user's friends via the Facebook Graph API?

I have written code to authenticate users on my website via Facebook's OAuth API. It works splendidly; I can access public information, likes, interests, activities, etc. I access these data points via the following URL format, where I substitute "uid" with a valid id (I use the uid in place of "me" because "me" doesn't work as advertised):

https://graph.facebook.com/uid?access_token=
https://graph.facebook.com/uid/likes?access_token=
https://graph.facebook.com/uid/interests?access_token=
https://graph.facebook.com/uid/activities?access_token=

However, accessing friends simply does not work. The url,

https://graph.facebook.com/uid/friends?access_token=

returns the following error:

{
   "error": {
      "type": "OAuthAccessTokenException",
      "message": "An access token is required to request this resource."
   }
}

The examples on the Graph API docs all work, yet the access token generated on that page has a different format than mine. I'm not sure why. I've followed their instructions to a tee (and have it working for everything else!).

Friends are considered publicly accessible information, and I've double-checked my Facebook account permissions, so I don't think that's the problem.

Best Answer

If a user connects to your Application you can retrieve their friends like so:

    $facebook = new Facebook(array(
                'appId' => 'xxxxxxxx',
                'secret' => 'xxxxxxx',
                'cookie' => true,
            ));

    // $session is only != null, when you have the session-cookie, that is set by facebook, after the user logs in
    $session = $facebook->getSession(); 

    // you dont get a list of friends, but a list, which contains other friendlists
    $friendsLists = $facebook->api('/me/friends');

    foreach ($friendsLists as $friends) {
      foreach ($friends as $friend) {
         // do something with the friend, but you only have id and name
         $id = $friend['id'];
         $name = $friend['name'];
      }
   }

But you only have access to id and name of the friends.