How can we check user liked the facebook application or not?
I am trying to create a Facebook app, in it there are two different pages , if user liked then page_1 will be show, otherwise page_2 show.
<?php
$user = $facebook->getUser();
if ($user) {
try{
$user_profile = $facebook->api('/me');
$likeID = $facebook->api(array( 'method' => 'fql.query',
'query' => 'SELECT url FROM url_like WHERE user_id = "'.$user_profile['id'].'" AND url="myurl/"'; ));
}
catch(FacebookApiException $e) { }
}
if(count($likeID)>0) echo "User likes this page";
else echo "User doesn\'t like this page";
?>
credible and/or official sources:
http://www.zuberi.me/2011/how-to-check-if-user-liked-the-application-or-page.html
http://www.chilipepperdesign.com/2011/02/15/reveal-fan-gate-like-gate-facebook-iframe-tab-tutorial-with-php
How to check if a user likes my Facebook Page or URL using Facebook's API
Facebook how to check if user has liked page and show content?
Facebook Check if user "Liked" the page
A better approach to the problem can be:
// to generate user access token after the user is logged in
$USER_ACCESS_TOKEN = $facebook->getExtendedAccessToken();
$isFan = curl("https://api.facebook.com/method/pages.isFan?format=json&access_token=" . $USER_ACCESS_TOKEN . "&page_id=" . $FACEBOOK_PAGE_ID);
function curl($url) {
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
$data = curl_exec($ch);
curl_close($ch);
return $data;
}
require 'facebook.php';
$app_id = "your app id";
$app_secret = "your app secret";
$facebook = new Facebook(array(
'appId' => $app_id,
'secret' => $app_secret,
'cookie' => true,
));
$signed_request = $facebook->getSignedRequest();
$like_status = $signed_request["app"]["liked"];
if ($like_status == 1){
echo 'User likes this page';
}
else{
echo 'User doesn\'t like this page';
}
Maybe you should try somethng like this, check Facebook's PHP SDK reference page for the exact approach.
Related
I want to get latest posts from fb and need to display on my site(magento). I have registerd one app in facebook and try to getting posts by using the url but it's giving empty array
require_once(Mage::getBaseDir('lib') . '/facebook/facebook.php');
$facebook = new Facebook(array(
'appId' => 'xxxxxxxxxxxx',
'secret' => 'xxxxxxxxxxxxxxxxxxxx',
));
$fbid = "xxxxxxxxxx";
$secret = "xxxxxxxxxxxxxxxxxxxxxxx";
$token = 'https://graph.facebook.com/oauth/access_token?client_id='.$fbid.'&client_secret='.$secret.'&grant_type=client_credentials';
$token = file_get_contents($token);
$posts = json_decode(
file_get_contents('https://graph.facebook.com/' . $fbid . '/feed?
access_token=' . $token
)
);
But it's giving an empty array and could you help me to get the results and why it is giving empty?
In order to read the Feed from Facebook, you must log the user into Facebook and ask the user for the read_stream permission.
The feed will be the logged-in user's feed and may not be appropriate for all users of your website, unless each user of your website sees their own feed...
If you have a valid access token, you can get feed from any public page using php graph api.You can call api using file_get_contents or curl method.
function curl_get_file_contents($URL) {
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $URL);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT ,0);
curl_setopt($ch, CURLOPT_TIMEOUT, 400);
$contents = curl_exec($ch);
$err = curl_getinfo($ch,CURLINFO_HTTP_CODE);
curl_close($ch);
$contents=json_decode($contents,true);
if ($contents) return $contents;
else return FALSE;
}
$access_token = 'your accesstoken';
$url = " https://graph.facebook.com/$page_id/feed?access_token=$access_token";
$posts = curl_get_file_contents($url);
Now $posts will have all the recents posts from the page and you can use foreach to get each post.
Create App Developer Facebook Page.
Live Access token you can get via graph. Then code exmaple:
<ul>
<?php
$page_name = '{PAGE_NAME}'; // Example: http://facebook.com/{PAGE_NAME}
$page_id = '{PAGE_ID}'; // can get form Facebook page settings
$app_id = '{APP_ID}'; // can get form Developer Facebook Page
$app_secret = '{APP_SECRET}'; // can get form Developer Facebook Page
$limit = 5;
function load_face_posts($page_id, $page_name, $app_id, $app_secret, $limit, $message_len) {
$access_token = "https://graph.facebook.com/oauth/access_token?client_id=$app_id&client_secret=$app_secret&grant_type=client_credentials";
$access_token = file_get_contents($access_token); // returns 'accesstoken=APP_TOKEN|APP_SECRET'
$access_token = str_replace('access_token=', '', $access_token);
$limit = 5;
$data = file_get_contents("https://graph.facebook.com/$page_name/posts?limit=$limit&access_token=$access_token");
$data = json_decode($data, true);
$posts = $data[data];
//echo sizeof($posts);
for($i=0; $i<sizeof($posts); $i++) {
//echo $posts[$i][id];
$link_id = str_replace($page_id."_", '', $posts[$i][id]);
$message = $posts[$i][message];
echo ($i+1).". <a target='_blank' href='https://www.facebook.com/AqualinkMMC/posts/".$link_id."'>".$message."</a><br>";
}
}
load_face_posts($page_id, $page_name, $app_id, $app_secret, $limit, $message_len);
?>
</ul>
I'm using the Facebook API connected script written in PHP (provided by Facebook). Everything works, it generates the login URL and redirects me back to the website when I'm logged in.
However, the $user variable seems to be undefined.
Have anyone experienced a similar problem? In the Facebook Apps statistics page I can see that the app has been used.
Update - The code:
<?php
$app_id = "xxxxxxxxxxxxxx";
$app_secret = "xxxxxxxxxxxxx";
$site_url = "http://xxx";
try{
include_once "src/facebook.php";
}catch(Exception $e){
error_log($e);
}
$facebook = new Facebook(array(
'appId' => $app_id,
'secret' => $app_secret
));
if($user = $facebook->getUser())
{
echo 'ok';
}
else
{
}
if($user){
//==================== Single query method ======================================
try{
// Proceed knowing you have a logged in user who's authenticated.
$user_profile = $facebook->api('/me');
}catch(FacebookApiException $e){
error_log($e);
$user = NULL;
}
//==================== Single query method ends =================================
}
if($user){
// Get logout URL
$logoutUrl = $facebook->getLogoutUrl();
}else{
// Get login URL
$loginUrl = $facebook->getLoginUrl(array(
'scope' => 'email,user_birthday,user_about_me',
'redirect_uri' => $site_url . '/auth_complete.php',
));
}
if($user){
// Proceed knowing you have a logged in user who has a valid session.
//========= Batch requests over the Facebook Graph API using the PHP-SDK ========
// Save your method calls into an array
$queries = array(
array('method' => 'GET', 'relative_url' => '/'.$user),
array('method' => 'GET', 'relative_url' => '/'.$user.'/home?limit=50'),
array('method' => 'GET', 'relative_url' => '/'.$user.'/friends'),
array('method' => 'GET', 'relative_url' => '/'.$user.'/photos?limit=6'),
);
// POST your queries to the batch endpoint on the graph.
try{
$batchResponse = $facebook->api('?batch='.json_encode($queries), 'POST');
}catch(Exception $o){
error_log($o);
}
//Return values are indexed in order of the original array, content is in ['body'] as a JSON
//string. Decode for use as a PHP array.
$user_info = json_decode($batchResponse[0]['body'], TRUE);
$feed = json_decode($batchResponse[1]['body'], TRUE);
$friends_list = json_decode($batchResponse[2]['body'], TRUE);
$photos = json_decode($batchResponse[3]['body'], TRUE);
//========= Batch requests over the Facebook Graph API using the PHP-SDK ends =====
}
?>
I'm not entirely sure why it worked, but I redirected the user to a page where the Javascript SDK is included (http://developers.facebook.com/docs/reference/javascript/), and now it's working!
The user have not authorized the app yet. Try something like this-
$user_id = $facebook->getUser();
echo $uid;
if($user_id){
try {
$user_profile = $facebook->api('/me');
} catch (FacebookApiException $e) {
error_log($e);
$user_id = null;
}
}else{
$login_url = $facebook->getLoginUrl();
echo("<br>login url=".$login_url);
};
An FB app of ours that previously worked for months is now experiencing the issue you speak of. $fb_user is now being returned undefined. =(
Update your SDK, sounds like you are hitting a certificate issue from a few weeks back.
You can find the latest version at https://github.com/facebook/facebook-php-sdk/
I have a file named fbmain.php which will authenticate the user.
<?php
//set facebook application id, secret key and api key here
$fbconfig['appid' ] = "MY_APP_ID";
$fbconfig['secret'] = "MY_APP_SECRET";
$uid = null; //facebook user id
try{
include_once "facebook.php";
}catch(Exception $o){
echo '<pre>';
print_r($o);
echo '</pre>';
}
// Create our Application instance.
$facebook = new Facebook(array(
'appId' => $fbconfig['appid'],
'secret' => $fbconfig['secret'],
'cookie' => true,
));
//Facebook Authentication part
$session = $facebook->getSession();
//Get permission from user
$loginUrl = $facebook->getLoginUrl(
array(
'canvas' => 1,
'fbconnect' => 0,
'req_perms' => 'email,publish_stream,status_update'
)
);
if (!$session) {
echo "<script type='text/javascript'>top.location.href = '$loginUrl';</script>";
exit;
}
if ($session) {
try {
$uid = $facebook->getUser();
} catch (FacebookApiException $e) {
echo "<script type='text/javascript'>top.location.href = '$loginUrl';</script>";
exit;
}
}
//signed_request part
$signed_request = $_REQUEST['signed_request'];
$secret = $fbconfig['secret'];
$data = parse_signed_request($signed_request, $secret);
$fan_page_id = $data['page']['id'];
$admin_check = $data['page']['admin'];
$like_check = $data['page']['liked']; //New
//Get fan page id
function parse_signed_request($signed_request, $secret) {
list($encoded_sig, $payload) = explode('.', $signed_request, 2);
// decode the data
$sig = base64_url_decode($encoded_sig);
$data = json_decode(base64_url_decode($payload), true);
if (strtoupper($data['algorithm']) !== 'HMAC-SHA256') {
error_log('Unknown algorithm. Expected HMAC-SHA256');
return null;
}
// check sig
$expected_sig = hash_hmac('sha256', $payload, $secret, $raw = true);
if ($sig !== $expected_sig) {
error_log('Bad Signed JSON signature!');
return null;
}
return $data;
}
function base64_url_decode($input) {
return base64_decode(strtr($input, '-_', '+/'));
}
?>
I have included fbmain.php file to my index.php file and access user data.
Then later I wanted to access user birthday.So I added 'user_birthday' permission references to the fbmain.php file.code is given bellow
//Get permission from user
$loginUrl = $facebook->getLoginUrl(
array(
'canvas' => 1,
'fbconnect' => 0,
'req_perms' => 'email,publish_stream,status_update,user_birthday'
)
);
code of the index.php file is given bellow,
<?php
//index.php file
include_once "fbmain.php";
$me = $facebook->api('/me');
$_SESSION['id'] = $me['id'];
$_SESSION['name'] = $me['name'];
$_SESSION['link'] = $me['link'];
$_SESSION['email'] = $me['email'];
if($me['birthday'] == null){ ?>
<script>
top.location = 'http://www.facebook.com/dialog/oauth?client_id=MY_APP_ID&redirect_uri=MY_REDIRECT_URL&scope=user_birthday';
</script>
<?php }else{ ?>
//Some other codes
<?php } ?>
I redirect user to permission window requesting user's birthday if $me['birthday'] returns null value. I had to add this part since I added user_birthday to the scope of permission references later.
This works for some users and display 'Request for Permission' window asking to access user's birthday.
But for some users it display a facebook error message(It may since I try to access user's birthday before display 'Request for Permission' window : $me['birthday']==null)
Can anyone tell me a proper way to get the re-permission from user to access user birthday?
Note that this problem occurs only for users those who have already authenticated in my app
You know facebook changed the parameter for the permissions from req_perms to scope in getLoginUrl() function. Try scope, may be it works.
https://github.com/facebook/php-sdk/issues/381
I don't understand php...bt check FB.ui
https://developers.facebook.com/docs/reference/dialogs/oauth/
Here you have oAuth dialog to ask for user permision.
You can use scope params for you requesting permission.
this is code for you want to replace
if ($user) {
$logoutUrl = $facebook->getLogoutUrl();
} else {
$loginUrl = $facebook->getLoginUrl(
array(
'scope' => 'email,publish_stream,user_birthday',
)
);
if you these this code ,your visitor who visit first time this code request full permision ,and already authendicate for other permisions user comes to this page it request only for birthday permisions .
you not need to use
if($me['birthday'] == null){ ?>
<script>
top.location = 'http://www.facebook.com/dialog/oauth?client_id=MY_APP_ID&redirect_uri=MY_REDIRECT_URL&scope=user_birthday';
</script>
<?php }else{ ?>
//Some other codes
I'm using the facebook API to get my wall feed using the graph API.
<?php
require_once('facebook.php');
// Create our Application instance (replace this with your appId and secret).
$facebook = new Facebook(array(
'appId' => '188687744521977',
'secret' => 'c2c3692845602812f473436d1da95014',
'cookie' => true
));
// Get User ID
$user = $facebook->getUser();
// We may or may not have this data based on whether the user is logged in.
// If we have a $user id here, it means we know the user is logged into
// Facebook, but we don't know if the access token is valid. An access
// token is invalid if the user logged out of Facebook.
if($user)
{
try
{
// Proceed knowing you have a logged in user who's authenticated.
$access_token = $_SESSION['fb_188687744521977_access_token'];
$user_profile = $facebook->api('/me');
$likes = $facebook->api('/me?fields=feed,likes');
$friends = $facebook->api('/me/friends');
$feed = 'https://graph.facebook.com/me/feed? access_token='.$access_token.'';
} 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();
}
// Save the user's info as variables
$full_name = $user_profile['name'];
$first_name = $user_profile['first_name'];
$last_name = $user_profile['last_name'];
$relationship = $user_profile['relationship_status'];
$partner_id = $user_profile['significant_other_id'];
$id = $user_profile['id'];
$link = $user_profile['link'];
function get_url($url)
{
$ch = curl_init();
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_TIMEOUT, 5);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
$tmp = curl_exec($ch);
curl_close($ch);
return $tmp;
}
$wall = get_url($feed);
print_r(json_decode($wall, true));
?>
However, an empty array is displayed. Any suggestions?
You should definitly try to find a better solution for handling the access token! Where are you setting this $_SESSION['fb_..._access_token']? Who says that 188687744521977 is always the userid of the logged in user? Why do you have spaces in your feed url?
The first thing you should do is delete the json_decode() and just var_dump() the $wall. I think your access token is not valid, maybe you also get a 401 Unauthorized or 403 Forbidden response?
I have created a simple Facebook application in PHP, that greets user by there user name,
I also want there Email id, to be displayed. But i am not able to do that. the code that i am using is,
require_once('facebook.php');
require_once('config.php');
$facebook = new Facebook(APIKEY, SECRETKEY);
$user=$facebook->require_login();
echo $user; // displaying the ID
<div style="padding: 10px;" id="greeting">
<fb:if-is-app-user uid="loggedinuser">
<h2>Hi <fb:name firstnameonly="true" uid="loggedinuser" useyou="false"/>! welcome to facebook</h2>
<fb:else>
<h2>Hi <fb:name firstnameonly="true" uid="loggedinuser" useyou="false"/>! welcome to facebook</h2>
</fb:else>
</fb:if-user-has-added-app>
</div>
the Output that i am getting is,
1000002020202020
Hi User! welcome to facebook
I want the Email address to be displayed along with the user name, i searched many code but did not get any solution. and if you any good facebook tutorial site please post the links too..
You can get the Email Address, directly without using the FQL.
// initialize facebook
$facebook = new Facebook(array(
'appId' => APP_ID,
'secret' => APP_SECRET));
$session = $facebook->getSession();
if ($session) {
try {
$fbme = $facebook->api('/me');
} catch (FacebookApiException $e) {
error_log($e);
}
}
else
{
echo "You are NOT Logged in";
}
//getting the login page if not signned in
if (!$fbme) {
$loginUrl = $facebook->getLoginUrl(array('canvas' => 1,
'fbconnect' => 0,
'req_perms' => 'email,user_birthday,publish_stream',
'next' => CANVAS_PAGE,
'cancel_url' => CANVAS_PAGE ));
echo '<fb:redirect url="' . $loginUrl . '" />';
} else {
// $fbme is valid i.e. user can access our app
echo "You can use this App";
}
// getting the profile data
$user_id = $fbme[id];
$name=$fbme['name'];
$first_name=$fbme['first_name'];
$last_name=$fbme['last_name'];
$facebook_url=$fbme['link'];
$location=$fbme['location']['name'];
$bio_info=$fbme['bio'];
$work_array=$fbme['work'];
$education_array=$fbme["education"];
$email=$fbme['email'];
$date_of_birth=$fbme['birthday'];
This code worked for me..and i go all the information needed with the Email ID.
NOTE: User has to allow us to get their Information during the Approval of Application.
You need to ask for extended permissions when the user authorizes your application, so you can have access to the user email.
Here's an example using the new PHP SDK and the Graph API:
<?php
require_once($_SERVER['DOCUMENT_ROOT'] . '/includes/config.php');
// initialize facebook
$facebook = new Facebook(array(
'appId' => APP_ID,
'secret' => APP_SECRET));
$user = $facebook->getUser();
$session = $facebook->getSession();
// in case we don't have a valid session, we redirect asking for email extended permissions
if ($user == null || $session == null) {
$params = array();
$params["canvas"] = "1";
$params["fbconnect"] = "0";
$params["next"] = CANVAS_URL;
$params["req_perms"] = "email";
$loginUrl = $facebook->getLoginUrl($params);
echo '<fb:redirect url="' . $loginUrl . '"/>';
exit();
}
// get user email via the new graph api, using the fql.query method
$url = "https://api.facebook.com/method/fql.query";
$url .= "?access_token=" . $session['access_token'];
$url .= "&query=SELECT email FROM user WHERE uid={$user}";
$userData = simplexml_load_file($url);
$userEmail = $userData->user->email;
echo 'The user ID is: ' . $user;
echo 'The user name is: <fb:name uid="' . $user . '" />';
echo 'The user email is: ' . $userEmail;
Thanks for all the help. I finally figure out how to do that.
first, I need to get the access token, NOT the user session one, but the one for admin.
So, here is the code:
$url = 'https://graph.facebook.com/oauth/access_token';
$ch = curl_init();
$params = array(
'grant_type'=>'client_credentials',
'client_id'=>$appId,
'client_secret'=>$secret,
);
$opts[CURLOPT_POSTFIELDS] = http_build_query($params, null, '&');
// set URL and other appropriate options
curl_setopt_array($ch, $opts);
curl_setopt($ch, CURLOPT_URL, "$url");
curl_setopt($ch, CURLOPT_HEADER, 0);
// grab URL and pass it to the browser
$adminAccessToken = curl_exec($ch);
// close cURL resource, and free up system resources
curl_close($ch);
And then, I can use the facebook API to get any user who accept the application and the extended permission like that:
$fql = "select name, hometown_location, sex, pic_square, email from user where uid=1000000001";
$param = array(
'method' => 'fql.query',
'query' => $fql,
'access_token' =>$adminAccessToken ,
'callback' => ''
);
$fqlResult2 = $facebook->api($param);
with the access token, i can also post things onto user's wall. :)