I just managed to connect to the facebook PHP api. Facebook API tutorial seems really bad or at least poorly organized.
I realised I can get the logged in user's name with: <?php print_r($user_profile[name]); ?> since it's beforehand set as $user_profile = $facebook->api('/me'); . How do I print another user's name who is not logged in, knowing his UID, for example '2222'
How do I fetch user info, specifically name and UID?
Thanks
What user do you want to fetch ? You can fetch current user with /me. Before using the Facebook PHP API , you need to understand about Facebook graph api. It explain everything about Facebook api access url. So, you can call the graph URL in Facebook PHP SDK.
You can check sample source code from
https://github.com/facebook/php-sdk/
require './facebook.php';
$facebook = new Facebook(array(
'appId' => 'YOUR_APP_ID',
'secret' => 'YOUR_APP_SECRET',
));
// Get User ID
$user = $facebook->getUser();
if ($user) {
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;
}
}
<script>
FB.init({appId: <?php echo FACEBOOK_APP_ID;?>, status: true, cookie: true, xfbml: true});
FB.Event.subscribe('auth.logout', function(response) {});
FB.Event.subscribe('auth.sessionChange', function(response) {
if (response.session) {
FB.api('/me', function(response) {
if(response.id!='undefined')
{
window.location='Fbaccess.php?first_name='+response.first_name+'&last_name='+response.last_name+'&email='+response.email;
}
else
{
window.location='login.php';
}
});
} else {
// The user has logged out, and the cookie has been cleared
}
});
</script>
php code ....
<?php
$cookie = get_facebook_cookie(FACEBOOK_APP_ID, FACEBOOK_SECRET);
if(isset($cookie))
{
$first_name = json_decode(#file_get_contents('https://graph.facebook.com/me?access_token=' .$cookie['access_token']))->first_name;
$last_name = json_decode(#file_get_contents('https://graph.facebook.com/me?access_token=' .$cookie['access_token']))->last_name;
}
?>
function get_facebook_cookie($app_id, $application_secret)
{
$args = array();
parse_str(trim($_COOKIE['fbs_' . $app_id], '\\"'), $args);
ksort($args);
$payload = '';
foreach ($args as $key => $value)
{
if ($key != 'sig') {
$payload .= $key . '=' . $value;
}
}
if (md5($payload . $application_secret) != $args['sig']) {
return null;
}
return $args;
}
i think this much code is available for you to get facebook name and user id ....
on this url you will find whole response
https://graph.facebook.com/me?access_token=' .$cookie['access_token']
In your api call, replace the '/me' with '/2222'
Related
Is there some limitation with Fat Free Framework when we try to output the page into facebook tab?
I already try it with this below code, and unfortunately in the facebook tab iframe always empty blank page.
<?php
$f3=require('app/lib/base.php');
require_once 'app/lib/fb/facebook.php';
$f3->route('GET /',
function() {
echo 'Hello';
}
);
$f3->route('GET /landing',
function() {
$app_id = 'xxxx';
$secret_key = 'yyyy';
$page_id = 'zzzz';
$config = array(
'appId' => $app_id,
'secret' => $secret_key
);
$fb = new Facebook($config);
$fbdata = $fb->getSignedRequest();
$fbInPage = false;
if(!empty($fbdata) && is_array($fbdata)
&& !empty($fbdata['page']) && is_array($fbdata['page'])
&& !empty($fbdata['page']['id'])
) {
$fbInPage = $fbdata['page']['id'];
}
// Check if user not in fb tab
if(!$fbInPage) {
// Redirect to facebook tab
echo '<script>window.location.href="https://www.facebook.com/'.
$page_id.
'?sk=app_'.
$app_id.
'"</script>';
exit;
}
// Get User ID
$user = $fb->getUser();
// Check if user not connected to facebook
if ($user) {
try {
$user_data = $fb->api("/me");
} catch (FacebookApiException $e) {
$user_data = null;
}
} else {
// Asking permission for email and user_likes
$fb_login_url = $fb->getLoginUrl(array(
'scope' => 'email, user_likes'
));
echo '<script>top.location.href = "'.$fb_login_url.'"</script>';
exit;
}
}
);
$f3->run();
First when user try to access GET /landing it will redirect to facebook tab and show the page GET /. But somehow it always return empty page, already inspect it with firebug on firefox and there is no error, on the response tab always shows Reload the page to get source for: https://localhost/f3-fb/. Already try it with my office framework and works perfectly.
If anybody ever get this problem please advise.
The problem is in XFRAME, on default F3 set the XFRAME value as SAME-ORIGIN, based on this doc, developer must overload the value with ALLOW-FROM uri.
Here is the full code for index.php:
<?php
$f3=require('app/lib/base.php');
require_once 'app/lib/fb/facebook.php';
$f3->set('XFRAME', 'ALLOW-FROM https://localhost/f3-fb/');
$f3->route('POST /',
function() {
echo 'Hello';
}
);
$f3->route('GET /landing',
function() {
$app_id = 'xxxx';
$secret_key = 'yyyy';
$page_id = 'zzzz';
$config = array(
'appId' => $app_id,
'secret' => $secret_key
);
$fb = new Facebook($config);
$fbdata = $fb->getSignedRequest();
$fbInPage = false;
if(!empty($fbdata) && is_array($fbdata)
&& !empty($fbdata['page']) && is_array($fbdata['page'])
&& !empty($fbdata['page']['id'])
) {
$fbInPage = $fbdata['page']['id'];
}
// Check if user not in fb tab
if(!$fbInPage) {
// Redirect to facebook tab
echo '<script>window.location.href="https://www.facebook.com/'.
$page_id.
'?sk=app_'.
$app_id.
'"</script>';
exit;
}
// Get User ID
$user = $fb->getUser();
// Check if user not connected to facebook
if ($user) {
try {
$user_data = $fb->api("/me");
} catch (FacebookApiException $e) {
$user_data = null;
}
} else {
// Asking permission for email and user_likes
$fb_login_url = $fb->getLoginUrl(array(
'scope' => 'email, user_likes'
));
echo '<script>top.location.href = "'.$fb_login_url.'"</script>';
exit;
}
}
);
$f3->run();
Add the config $f3->set('XFRAME', 'ALLOW-FROM https://localhost/f3-fb/'); to allow this url inside on facebook iframe.
And always use POST for the route inside the facebook iframe (still don't know why must using that with F3, but it will occur the error and asking for POST route)
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
How can I ask for permissions using new PHP SDK? I don't want to use the graph api and parse the url all the time. When the application is opened it should automatically ask for permissions if the user hasn't granted one already.
Here's how i'm doing it with the latest PHP SDK (3.0.1)
// init new facebook class instance with app info (taken from the DB)
$facebook = new Facebook(array(
'appId' => 'YOUR APP ID',
'secret' => 'YOUR APP SECRET'
));
// get user UID
$fb_user_id = $facebook->getUser();
// get the url where to redirect the user
$location = "". $facebook->getLoginUrl(array('scope' => 'publish_stream, email'));
// check if we have valid user
if ($fb_user_id) {
try {
// Proceed knowing you have a logged in user who's authenticated.
$fb_user_profile = $facebook->api('/me');
} catch (FacebookApiException $e) {
$fb_user_id = NULL;
// seems we don't have enough permissions
// we use javascript to redirect user instead of header() due to Facebook bug
print '<script language="javascript" type="text/javascript"> top.location.href="'. $location .'"; </script>';
// kill the code so nothing else will happen before user gives us permissions
die();
}
} else {
// seems our user hasn't logged in, redirect him to a FB login page
print '<script language="javascript" type="text/javascript"> top.location.href="'. $location .'"; </script>';
// kill the code so nothing else will happen before user gives us permissions
die();
}
// at this point we have an logged in user who has given permissions to our APP
// basic user info can be fetched easily
print "Welcome to my app". $fb_user_profile['name'];
Session Based Login with scope and Logout with access_token for PHP-SDK 3.2.0.
<?php
require './src/facebook.php';
$facebook = new Facebook(array(
'appId' => '135669679827333',
'secret' => 'xxxxxxxxxxxxxxxxxxxxxx',
));
$user = $facebook->getUser();
if ($user) {
try {
// Proceed knowing you have a logged in user who's authenticated.
$user_profile = $facebook->api('/me');
} catch (FacebookApiException $e) {
$user = null;
}
}
if ($user) {
$params = array(access_token => ''.$access_token.'');
$logoutUrl = $facebook->getLogoutUrl($params);
} else {
$params = array(
scope => 'read_stream,publish_stream,publish_actions,read_friendlists',
//redirect_uri => $url
);
$loginUrl = $facebook->getLoginUrl($params);
};
$access_token = $_SESSION['fb_135669679827333_access_token'];
?>
.
<?php if($_SESSION['fb_135669679827333_access_token']): ?>
Login & Connect
<?php else: ?>
Login & Connect
<?php endif ?>
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?
I want our web app to be able to update a users wall using the offline access permission. I'm going around in circles at the moment because I don't seem to be able to store the access token. I've tried using example.php but am not retaining the session (I think, please forgive me I'm a newbie)
The way I want it to work is as follows:
User Clicks add Facebook - i.e. our app is approved by user (I can do this using the graph api)
Token is returned and we save it in database (this bit I'm struggling to get my head around) to enable a post later.
If anyone can give me a step by step guide I'd really appreciate it. Please don't just redirect me to a the developers page at facebook.
You use the javascript for the authentication as
FB.login(function(response) {
// As of Facebook's transition to OAuth 2.0 session has been replaced with authResponse
// See https://developers.facebook.com/blog/post/525/
// var access_token = response.session.access_token;
var access_token = null;
if (response.authResponse) {
access_token = response.authResponse.accessToken;
if (response.perms) {
// user is logged in, everithig is ok
} else {
// user is logged in, but did not grant any permissions
}
} else {
// user is not logged in
}
}, {perms:'read_stream,publish_stream,offline_access'});
You will get the access token in javascript variable access_token.You can save this access token in database and then publish to wall using the following code
function graphStreamPublish(){
var body = document.getElementById("txtTextToPublish").value;
FB.api('/me/feed', 'post', { message: body }, function(response) {
if (!response || response.error) {
alert('Error occured');
} else {
alert('Post ID: ' + response.id);
}
});
}
Or if you want to use php sdk then create authentication.php as follows.
<?php
$app_id = "YOUR_APP_ID";
$app_sec = "APP_SEC";
$canvas_page = "APP_CANVAS_PAGE_URL";
$scope = "&scope=user_photos,email,publish_stream"; $auth_url"http://www.facebook.com/dialog/oauth?client_id=" . $app_id . "&redirect_uri=" . urlencode($canvas_page).$scope;
$signed_request = $_REQUEST["signed_request"];
list($encoded_sig, $payload) = explode(".", $signed_request, 2);
$data = json_decode(base64_decode(strtr($payload, "-_", "+/")), true);
if (empty($data["user_id"])) {
echo(""); }
$access_token = $data["oauth_token"];
$user_id = $data["user_id"];
$user = json_decode(file_get_contents( "https://graph.facebook.com/me?access_token=" . $access_token));
function get_facebook_cookie($app_id, $application_secret) {
$args = array();
parse_str(trim($COOKIE["fbs" . $app_id], "\""), $args);
ksort($args);
$payload = "";
foreach ($args as $key => $value) {
if ($key != "sig") {
$payload .= $key . "=" . $value;
}
}
if (md5($payload . $application_secret) != $args["sig"]) {
return null;
}
return $args;
}
$cookie = get_facebook_cookie($app_id, $app_sec);
?>
In the page where you need to publish to wall include this page and facebook api page(facebook.php) then the code to publish to wall
$attachment = array('message' => 'some meesgae',
'name' => 'This is my demo Facebook application!',
'caption' => "Caption of the Post",
'link' => 'mylink.com',
'description' => 'this is a description',
'actions' => array(array('name' => 'Get Search', 'link' => 'google.com')) );
$result = $facebook->api('/me/feed?access_token='.$access_token, 'post', $attachment);
I think this is helpful..
I have created a simple demo iframe application which uses facebook php sdk to do exactly what needed.
http://eagerfish.eu/using-facebook-off-line-access-to-post-on-users-wall/
Hope it helps out someone.