Laravel, Facebook API: retrieving friends of friends - facebook

In a previous thread we were strugling with the Facebook login using a Laravel app. Now, as the user logs into our app using Facebook, we are trying to get his friend's list in order to provide some qualified suggestions. So, here's what we are trying:
Route::get('login/fb/callback', function() {
// A FacebookResponse is returned from an executed FacebookRequest
$helper = new FacebookRedirectLoginHelper('http://yoururl/login/fb/callback');
$session = $helper->getSessionFromRedirect();
$request = new FacebookRequest($session, 'GET', '/me/friends');
try {
$response = $request->execute();
$me = $response->getGraphObject();
} catch (FacebookRequestException $ex) {
echo $ex->getMessage();
} catch (\Exception $ex) {
echo $ex->getMessage();
}
print_r($me);//->getProperty("id"));
$user = new Giftee;
$user->name = $me->getProperty('first_name') . ' ' . $me->getProperty('last_name');
$user->email = $me->getProperty('email') . "#facebook.com.br";
$user->photo = 'https://graph.facebook.com/' . $me->getProperty('id') . '/picture?type=large';
$user->save();
});
As a result, we get:
object(Facebook\GraphObject)#146 (1) { ["backingData":protected]=> array(0) { } }
By reading the Facebook API docs, they pretty much say user_friends will only return friends of friends that already use your app and We could not see any login permission that would just return friends of friends (not only the ones using our app). In another words, is what we want really impossible?

You're not able to retrieve friends of friends. With Graph API v2.0, you even only get those friends of your app's users which also use your app.
And, all friends_* permissions have been removed. So I don't see a chance for you to implement what you want to achieve.

Related

Can't get instagram newly added business account through API

I am facing issue for Instagram business accounts retrieving from API.
Client is already authorized my app and after some time they converted there Instagram personal account to business account.
When i try to fetch newly added Instagram business account they are not showing in API response.
Every time i have to remove app from account and re-authorized. I re-authenticated app still not get newly added business account.
Guys any solution for this ??
Here is a screenshot for more info http://nimb.ws/zfwl7e
function fb_reauthenticate_relink()
{
$helper = $this->fb->getRedirectLoginHelper();
$permissions = ['email', 'public_profile', 'manage_pages', 'read_insights', 'publish_pages', 'instagram_basic', 'instagram_manage_comments', 'instagram_manage_insights'];
$loginUrl = $helper->getReAuthenticationUrl('facebook_reauthenticate_callback', $permissions);
redirect($loginUrl);
}
function facebook_reauthenticate_callback()
{
$helper = $this->fb->getRedirectLoginHelper();
try
{
$accessToken = $helper->getAccessToken();
} catch (Facebook\Exceptions\FacebookResponseException $e)
{
// When Graph returns an error
echo 'Graph returned an error: ' . $e->getMessage();
exit;
} catch (Facebook\Exceptions\FacebookSDKException $e)
{
// When validation fails or other local issues
echo 'Facebook SDK returned an error: ' . $e->getMessage();
exit;
}
$raw_accessToken = (string) $accessToken;
$oAuth2Client = $this->fb->getOAuth2Client();
$longLivedAccessToken = (string) $oAuth2Client->getLongLivedAccessToken($raw_accessToken);
$url = "https://graph.facebook.com/v3.1/me/accounts?fields=instagram_business_account,connected_instagram_account,global_brand_page_name,access_token&access_token=" . $longLivedAccessToken;
$request_response = $this->curl_request($url);
// In $request_response didn't get newly added business profile
}

Retrieving Facebook friends list

I am not able to get the Facebook friends list using the API. It was working fine earlier but not anymore. Here is the code I have used. Can someone help to validate the code. Thanks in advance.
<?php
require_once('PHPMailerAutoload.php');
require_once('PHPMailerConfig.php');
require_once("facebook/facebook.php");
$config = array();
$config['appId'] = '***************';
$config['secret'] = '*******************************';
$facebook = new Facebook($config);
$uid = $facebook->getUser();
if(!empty($_GET['error'])) {
echo "User cancelled the authentication with facebook";
echo "<script>
window.opener.location.href='merror.php';
window.close();
</script>";
exit;
}
if($uid) {
$url = $uid.'?fields=id,work,friends,email,picture.width(450).height(450)';
$user_profile = $facebook->api($url);
$friends = $facebook->api('/me/friends');
$d = '';
foreach($friends['data']as $val) {
$d .= $val['id'].',';
}
}
?>
Please read the docs before posting a question which has been answered here hundreds of times.
See
https://developers.facebook.com/docs/graph-api/reference/v2.3/user/friends#read
A user access token with user_friends permission is required to view the current person's friends.
This will only return any friends who have used (via Facebook Login) the app making the request.
If a friend of the person declines the user_friends permission, that friend will not show up in the friend list for this person.

Facebook Getting Event from PAGE! not user PHP sdk v4.0.x graph 2.1

im trying to just get PAGE/Event from facebook and im still in doubt about how to do it
and if im doing it right or am i totally of track?
// for permanet session
$session = new FacebookSession("permanet app token");
// If you're making app-level requests: (copy paste from facebook :P)
$session = FacebookSession::newAppSession();
// To validate the session:
try {
$session->validate();
} catch (FacebookRequestException $ex) {
// Session not valid, Graph API returned an exception with the reason.
echo $ex->getMessage();
} catch (\Exception $ex) {
// Graph API returned info, but it may mismatch the current app or have expired.
echo $ex->getMessage();
}
if ( isset( $session ) && $session->validate() ) {
if($session) {
try {
$user_profile = (new FacebookRequest(
$session, 'GET', '/PAGE/events'
))->execute()->getGraphObject(GraphUser::className());
print_r($user_profile);
} catch(FacebookRequestException $e) {
echo "Exception occured, code: " . $e->getCode();
echo " with message: " . $e->getMessage();
}
}
so im wondering is this wrong or is it okey i just wanna post events i don't wanna login and stuff like that
im sorry im not good at english or explaining, so if something is unclear please let me know and i will try to explain as best as i can!
If you just want to get public events from a page, when what you are doing is correct. Just make sure the events on the page are public.
You cannot, however, create or post events without logging in. Firstly, the API no longer allows you to create events via the API. Secondly, viewing private events will require to login so Facebook can determine if you have permission to view the event or not.

Fetching FB user-id returns incorrect value ("1")

I have a very strange problem:
Sometimes (but not every time!) when I try to get the current user facebook ID, I get "1";
for example:
$config = array();
$config["appId"] = API_KEY;
$config["secret"] = SECRET;
$facebook= new Facebook($config);
$user=$facbook->getUser();
echo $user['id'];//returns 1;
Obviously - this it not the real user ID.
When I check if the access token is still good -I see that it is still valid. Also, even if I force the user to login again using:
FB.login(function(response) {
if (response.authResponse) {
top.location.href="<?php echo HOME_URL;?>"
}, {scope: 'publish_stream'});
Still getting the same result.
Any idea what could be the problem?
You should ONLY get an ID back from FB:
$user_id = $facbook->getUser();
echo $user_id;
You would later have to query the API for a user profile (which is what it looks like you are doing):
$user_profile = $facebook->api('/me');
Reference:
http://developers.facebook.com/docs/reference/php/facebook-api/

Fetching friends' birthdays from facebook profile

I want to fetch 'birthdays' of users, and their friends on my website, from their facebook profiles (with their facebook credentials supplied).
Is their a feature in Facebook API/Connect that I can use to fetch these details from facebook as possible on Native Facebook Apps using Facebook API.
I want to store this data in my DB, and users will be asked for their facebook credentials and consent before this is done.
Read the api documentation things like this are easily done. You can do it like this:
$facebook = new Facebook( $apikey, $secret );
$uid = $facebook->require_login();
$friends = $facebook->api_client->friends_get(); // $friends is an array holding the user ids of your friends
foreach( $friends as $f ) {
$data = $facebook->api_client->fql_query( "SELECT birthday_date FROM user WHERE uid=$f" );
// $data[0] is an array with 'birthday_date' => "02/29/1904"
// see api documentation for other fields and do a print_r
}
So recently I wanted to check my friends to see if any of them had their birthday for the current day. Using FQL this is super easy and I encourage you to explore FQL more because it will yield a more efficient solution than, say, what Pierre kindly offered. Here is a small snippet of the code:
$friends = $facebook->api_client->friends_get();
$uids = "";
foreach($friends as $f) {
$uids .= "uid=$f OR ";
}
$query_uids = substr($uids,0,strlen($query_uids)-4);
date_default_timezone_set('UTC');
$current_date = date("m/d");
echo "<br />Searching for birthdays for the given month/day: $current_date<br />";
$data = $facebook->api_client->fql_query( "SELECT name, uid FROM user WHERE ( ($query_uids) AND strpos(birthday_date,'$current_date') >= 0 )" );
if(count($data) > 0) {
foreach($data as $d) {
print_r($d);
}
} else {
echo "<br />No Birthdays Today<br />";
}
require_once('facebook-platform/client/facebook.php');
$facebook = new Facebook(API_KEY, SECRET);
$facebook->require_login();
function getInfo($user_list, $fields)
{
try
{
$u = $facebook->api_client->users_getInfo($user_list, $fields);
return $u;
}
catch (FacebookRestClientException $e)
{
echo $e->getCode() . ' ' . $e->getMessage();
}
}
function getFriendsBirthdays($user_id)
{
$f = $_REQUEST['fb_sig_friends'];
$f = explode(',', $f);
$birthdays = array();
foreach($f as $friend_id)
{
$birthdays[] = getInfo($friend_id, 'birthday');
}
return $birthdays;
}
Do something like that or use the Batch API to do multiple calls at once. Check the Facebook API.
You could fetch it via the API, but Facebook's terms strictly forbid you from storing anything other than their user ID in your database - see the developer wiki for details. You will need to query the API each time.