I have created test app in developer facebook. Trying to get facebook friend list using App id and app Secret.i have created Follow code
<?php
//facebook application configuration
$fbconfig['appid' ] = "xxxxxxxxxxxxxxxxxxxx";
$fbconfig['secret'] = "xxxxxxxxxxxxxxxxxxxx";
try{
include_once ('.\facebook-php-sdk-master\src\facebook.php');
}
catch(Exception $o){
print_r($o);
}
$facebook = new Facebook(array(
'appId' => $fbconfig['appid'],
'secret' => $fbconfig['secret'],
'cookie' => true,
));
$user = $facebook->getUser();
$loginUrl = $facebook->getLoginUrl(
array(
'scope' => 'email'
)
);
if ($user) {
try {
$user_profile = $facebook->api('/me');
$user_friends = $facebook->api('/me/friends');
$access_token = $facebook->getAccessToken();
} catch (FacebookApiException $e) {
d($e);
$user = null;
}
}
if (!$user) {
echo "<script type='text/javascript'>top.location.href = '$loginUrl';</script>";
exit;
}
$total_friends = count($user_friends['data']);
echo 'Total friends: '.$total_friends.'.<br />';
$start = 0;
while ($start < $total_friends) {
echo $user_friends['data'][$start]['name'];
echo '<br />';
$start++;
}
?>
Finally Run the code in My localhost its showing friend List zero Like this
Total friends: 0.
but I have 2 friends.please any idea about how to resolve my issues? thanks in advance ?
You need to authorize with the user_friends permission. After that, you can use /me/friends to get friends who authorized your App with user_friends too (and only those). It is not possible to get all friends anymore, except for tagging (taggable_friends) or inviting friends to a canvas game (invitable_friends). Check out the changelog to find out about more changes: https://developers.facebook.com/docs/apps/changelog
For more information, check out the answer of this thread, it´s from a Facebook employee: Facebook Graph Api v2.0+ - /me/friends returns empty, or only friends who also use my app
facebook returns your friends list in two scenarios only.
Your app must be in Gaming category.
If your app not comes under games, then it will only returns the list of your friends who liked that particular app.
before getting friends list please check that your app was approved with proper permissions by facebook.
Related
I'm trying to use php to access and collect basic information on-
users name, gender, birthday, age_range etc.
but for some reason I can only get the name and gender to work and I get an Undefined index: with birthday and age_range.
Can someone help me figure this out? I am new to Facebook Graph API and trying to modify the given code they gave for logging. I think I don't need an access token yet because I'm trying to get the initial permissions when they log into the site.
<?php
include('src\facebook.php');
//$scope = 'username,age_range,birthday,gender';
$config = array(
'appId' => 'XXXXXXXXXXXXXXXX',
'secret' => 'XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX',
'fileUpload' => false,
'allowSignedRequest' => false
);
$facebook = new Facebook($config);
$user_id = $facebook->getUser();
?>
<html>
<head></head>
<body>
<?php
if($user_id) {
try {
//$user_profile = $facebook->api('/me','GET');
$user_profile = $facebook->api('/me','GET', array('scope' => 'user_birthday,gender,age_range,name,likes'));
echo "Name: " . $user_profile['name'];
echo " Gender: " . $user_profile['gender'];
echo " DOB: " . $user_profile['birthday'];
echo " Age_Range: " . $user_profile['age_range'];
} catch(FacebookApiException $e) {
$login_url = $facebook->getLoginUrl();
echo 'Please login.';
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 login.';
}
?>
</body>
</html>
Also could someone explain to how to get user likes, I know I have to specify user permission using the Facebook->api(me/like) but then how do I access the array? Thanks for the help!
Please follow only the official docs to avoid such mistakes-
You are adding the permissions scope into the wrong place.
You are using the wrong permissions: gender,age_range,name,likes - these are not valid permissions!
Permissions that you require are: user_likes (for likes), user_birthday(for birthday); rest are the part of the basic(default) permissions only!
The age range field is also included in the public profile- for anyone who installs your app.
You have to add the scope parameter while using the login code: getLoginUrl().
$params = array(
'scope' => 'user_likes, user_birthday'
);
$loginUrl = $facebook->getLoginUrl($params);
After the user successfully grants the permissions, you'll get the required things!
My app uses Facebook PHP SDK 3.2.2 to authenticate users, what I've done so far:
$facebook = new Facebook(array('appId' => APP_ID,'secret' => APP_SECRET));
$fbme = $facebook->getUser();
if ($fbme) {
try {
$user_profile = $facebook->api('/'.$fbme);
catch (FacebookApiException $e) {
error_log($e);
$fbme = null;
}
}else{
$login_url = $facebook->getLoginUrl(array('scope' => 'email,publish_actions', 'redirect_uri' => $baseurl));
echo("<script>top.location.href = '" . $login_url . "';</script>");
die();
}
This code gets included at the top of every page. As you can see, is very basic. Everything works, the user gets authenticated but the sessions lasts very short, lets say, around 1hr. Is it possible to configure the FB session timeout anywhere? Thanks.
I am on the verge of going crazy I think!
I am logged into my Personal Facebook account on my work machine and the app I am using works fine but on any other machine logged in as me, the app admin or anyone else the page just seems to keep on constantly refreshing with the state parameter in the url just whirring away and changing between page loads. (I have a laptop sitting on my desk, both using Firefox aswell)
I'm sure it was working on all machines that tested it the other day. Today it started with an error but I can't remember the error code but it was to do with the re-direct url not being owned by the domain but this doesn't seem to crop up now.
I am not the admin of the app either.
Here is the relevant code:
<?
error_reporting(0);
// Facebook PHP SDK
include_once "src/facebook.php";
// app id and seret from the facebook app
$appId = 'xxxxxxxxxxxxxx';
$secret = 'xxxxxxxxxxxxxxxxxxxxxxxxxxx';
$facebook = new Facebook(array(
'appId' => $appId,
'secret' => $secret,
'cookie' => true,
));
//Facebook Authentication part
$user = $facebook->getUser();
$loginUrl = $facebook->getLoginUrl(
array(
'canvas' => 1,
'fbconnect' => 0,
'scope' => 'user_status,publish_stream,user_photos'
)
);
if ($user)
{
try
{
// page id and the feed we want
$user_feed = $facebook->api('PAGENUMBER/feed');
echo "<div id=\"graph\">";
$count = 0;
for ($i=0; $i<25; $i++)
{
// only want statuses - no videos, events, links etc.
if ($user_feed['data'][$i]['type'] == "status")
// just grabbing stuff and echoing it out
// blah blah blah
}
}
catch (FacebookApiException $e)
{
$user = null;
}
// close graph div
echo "</div>";
}
// if the user is not logged in then redirect to login page
if (!$user)
{
echo "<script type='text/javascript'>top.location.href = '$loginUrl';</script>";
exit;
}
?>
This was a pain but took out the if ($user) and the try catch and the login redirect and all that seemed to work.
<?php
require '../src/facebook.php';
try
{
// Create our Application instance (replace this with your appId and secret).
$facebook = new Facebook(array(
'appId' => '120875194666085',
'secret' => '0272027b5c5c1dabde81096497970c56',
'scope' => 'read_stream',
));
$user = $facebook->getUser();
if ($user) {
try {
// Proceed knowing you have a logged in user who's authenticated.
$user_profile = $facebook->api('/me/feed');
} catch (FacebookApiException $e) {
error_log($e);
$user = null;
}
}
// Login or logout url will be needed depending on current user state.
if ($user) {
$logoutUrl = $facebook->getLogoutUrl();
} else {
$loginUrl = $facebook->getLoginUrl(array('scope' => 'read_stream'));
}
}
catch(FacebookApiException $e){}
?>
<?php
if ($user): ?>
<?php else: ?>
<div>
Login using OAuth 2.0 handled by the PHP SDK:
Login with Facebook
</div>
<?php endif ?>
<?php if ($user): ?>
<?php
for($i = 0; $i < 25; $i++)
{
echo "<br />";
echo $user_profile['data'][$i]['from']['name'];
echo " : ";
echo $user_profile['data'][$i]['message'];
}
?>
<?php endif ?>
This worked just fine for normal accounts, but when I tried to log in with a Facebook "Pages" account, it didn't work at all. Any help on this matter? Also, when I got to the Facebook Graphs API documentation, even those links don't give me a proper feed of the Pages wall. From what I had gathered, I had to
https://graph.facebook.com/[company page id]/feed??access_token=[access_token]
to get it to work (which I am not sure how to translate into the Facebook API.
You should be able to access Fan Page Feeds as long as you have any access_token.
If you have a valid authorised user that is logged in
$fan_page_feed = $facebook->api('/COMPANY_PAGE_ID/feed');
will return a JSON object containing feed data.
Alternatively you could use the applications access_token to get the information. This example gets the feed from the Facebook Platfrom page (For the sake of conciseness, the script also assumes everything will work perfectly - you should implement your own error handling as you see fit):
<html><head></head>
<body>
<pre>
<?php
require ('facebook.php');
$facebook = new Facebook(array(
'appId' => 'YOUR_APP_ID',
'secret' => 'YOUR_APP_SECRET',
'cookie' => true
));
$result = $facebook->api('oauth/access_token', array('client_id'=>'YOUR_APP_ID', 'client_secret'=>'YOUR_APP_SECRET', 'grant_type'=>'client_credentials'));
// $result should contain 'access_token=VALID_ACCESS_TOKEN'
$access_token = explode('=',$result);
$fan_page_feed = $facebook->api('/19292868552/feed', array('access_token'=>$access_token[1]));
print_r($fan_page_feed);
?>
</pre>
</body>
</html>
Is it possible to check if a user already likes my facebook fanpage from my website with Javascript or PHP?
EDIT: I need a solution, so the user doesn't need to authenticate / allow some persmissions first
<?php
require '../src/facebook.php';
// Create our Application instance (replace this with your appId and secret).
$facebook = new Facebook(array(
'appId' => 'APP_ID',
'secret' => 'APP_SECRET',
));
$user = $facebook->getUser();
$page_id = "123456789";
$page_name = $facebook->api("/".$page_id)['name'];
$page_link = $facebook->api("/".$page_id)['link'];
if ($user) {
try {
$likes = $facebook->api("/me/likes/".$page_id);
if( !empty($likes['data']) )
echo "I like!";
else
echo "not a fan!";
} catch (FacebookApiException $e) {
error_log($e);
$user = null;
}
}
if ($user) {
$logoutUrl = $facebook->getLogoutUrl();
} else {
$loginUrl = $facebook->getLoginUrl(array(
'scope' => 'user_likes'
));
}
// rest of code here
?>
The simplest way would be to call the Graph API to get the /me/likes connections (note you have to require the user_likes permission). Then go through each and compare id with the ID of your page.
Assuming you're using the official Facebook PHP SDK, and have an instance of the Facebook object set up (see Usage section in the aforementioned page), the following code can be used to find out if the user is fan of Daft Punk:
$our_page_id = '22476490672'; // This should be string
$user_is_fan = false;
$likes = $facebook->api( '/me/likes?fields=id' );
foreach( $likes['data'] as $page ) {
if( $page['id'] === $our_page_id ) {
$user_is_fan = true;
break;
}
}
Now, you can further work with the $user_is_fan variable.
In JavaScript, the code would be very similar. Using the official JavaScript SDK's method FB.api (again, assuming you have taken of the authentication):
FB.api('/me/likes?fields=id', function(response) {
var our_page_id = '22476490672';
var user_is_fan = false;
var likes_count = response.data.length;
for(i = 0; i < likes_count; i++) {
if(response.data[i].id === our_page_id) {
user_is_fan = true;
break;
}
}
});
Note that here we're using an asynchronous request and callback, so the code using the user_is_fan variable must be inside the function.
In case you are OK with user giving the permissions, for a PHP based website it can be done this way easily:
1- Create a new Facebook app here.
2 - Download Facebook PHP SDK from here. Extract the files and place it in the same folder with the file in which you will paste the code given below!
3 - Get your Facebook Page ID using this tool.
4 - Generate Facebook like box code for your page from here.
After 1, 2, 3 and 4 steps are complete, you can check if user has liked a page or not with the following code:
<?php
require('facebook.php');
$config = array(
'appId' => 'your facebook app id',
'secret' => 'your facebook app secret code',
'allowSignedRequest' => false
);
$facebook = new Facebook($config);
$user_id = $facebook->getUser();
if (isset($user_id)) {
try {
$likes = $facebook->api('/me/likes/your_facebook_page_id_here', 'GET');
if (!empty($likes['data'])) // if user has liked the page then $likes['data'] wont be empty otherwise it will be empty
{
echo 'Thank you for liking our fan page!';
}
else {
echo 'You have not liked our fan page! Like it now:';
?>
<iframe src="//www.facebook.com/plugins/likebox.php?href=https%3A%2F%2Fwww.facebook.com%2Fchillopedia&width&height=290&colorscheme=light&show_faces=true&header=true&stream=false&show_border=true&appId=1392604484339363" scrolling="no" frameborder="0" style="border:none; overflow:hidden; height:290px;" allowTransparency="true"></iframe> //replace this with your own Facebook like box code
<?php
}
} catch (FacebookApiException $e) {
$login_url = $facebook->getLoginUrl();
echo 'Please click here to login into your Facebook account.';
error_log($e->getType());
error_log($e->getMessage());
}
} else {
$login_url = $facebook->getLoginUrl();
echo 'Please lick here to login into your Facebook account';
}
?>
The user will click on the "Please click here to login into your Facebook account." text which will redirect it to Facebook app permissions page, once user allows the permission to your app the code will fetch user's data and will display the likebox if user hasn't liked your fan page.
<script src="http://connect.facebook.net/en_US/all.js"></script>
<script>
FB.init({
appId : 'YOUR_APP_ID_WITHIN_QUOTES', //Change this to your app id
status : true, // check login status
cookie : true, // enable cookies to allow the server to access the session
xfbml : true // parse XFBML
});
</script>
$signed_request = $_REQUEST["signed_request"];
list($encoded_sig, $payload) = explode('.', $signed_request, 2);
$data = json_decode(base64_decode(strtr($payload, '-_', '+/')), true);
$has_liked = $data["page"]["liked"];
now check the $has_liked param to see if user likes ur page or not!
seems like "/me/likes/[page_id]" doesn't always return the record even there is one.
recently I request by "/me/likes/[page_id]", it will return 0,
but if I request without page_id, but grab a bunch of record by "/me/likes/", and you will see the page_id is actually there, can't figure why.
when checking with graph.facebook.com/[page_id], only suspicious thing is its "can_post" is false, and others which "/me/likes/[page_id]" do works, is true.
but looping is not good in this situation, especially some crazy people has millions of likes.
is there any kinda privacy setting related to the page_id owner account would cause the problem?