How get facebook user ID from my application? - php

I created a facebook application and send request to a user through below code.Now when a user allow my application then i need his id and email address into my canvas url.But on that below code user don't go to my canvas URL.So,Please help me to solve ,how a user go to my canvas url when he allow my application and i get the user id of that user?My code is below:
require_once 'facebook.php';
$facebook = new Facebook(array(
'appId' => '#######',
'secret' => '###################',
'cookie' => true, ));
$req_perms = "publish_stream,offline_access,user_status,email,read_stream";
$session = $facebook->getSession();
$loginUrl = $facebook->getLoginUrl(array('canvas'=>1,'fbconnect' => 0,'req_perms'=>$req_perms));
$me = null;
if (!$session)
{ echo "top.location.href= '$loginUrl';";exit;}
else{
try {
$uid = $facebook->getUser();
$me = $facebook->api('/me');
}
catch (FacebookApiException $e)
{ echo "<script type='text/javascript'>top.location.href= '$loginUrl';</script>"; exit;}
}
So,please help me to get the user id.
Thanks in advance
riad

The Facebook ID & email for the current user can be accessed through:
$me['id'];
$me['email'];
Is that what you're after?

First of all, your code is "badly" written. The catch block in your code "when executed" does not mean that the user is not logged in. It means that something went wrong in your try block (a.k.a bad Facebook Call).
Now for your question, you just need to place this in your try block:
$data = $facebook->api('/me?fields=id,email');
IMPORTANT NOTE:
You may not get the user real email, the user may choose to not share it with you and this way Facebook will create a "mirror" email to share with your App.

I am not familiar with php to comment on the code above. However in general it would be better to use javascript sdk for login alone (faced the same issue in asp.net). That way post user login, the control comes back to the same page where it was initiated. For example:
<div id="fb-root"></div>
<script type="text/javascript" src="http://connect.facebook.net/en_US/all.js"></script>
<script type="text/javascript">
FB.init({
appId: <app_id>, cookie: true, status: true, xfbml: true
});
function fblogin() {
FB.login(function (response) {
//Control comes back here
if (response.session) {
alert(response.session.access_token);
var url = '/me?fields=name,email';
FB.api(url, function (response) {
//You are now in the same page with the data you wanted. If necessary redirect.
alert(response.name);
alert(response.email);
});
}
else {
alert("User did not login successfully");
}
}, { perms: 'email' });
}
</script>
<img src="../Images/social_facebook.png" />

At last i solve my problem and now i can easily get the facebook user id and email address and other related information.Using this code i can hit to facebook for particular user's authentication and when user accept my application then i can get his/her facebook user id, email and other information into $user_info array.Hope it will help you.
Just see my code below:
<?php
require_once 'facebook.php';
$facebook = new Facebook(array(
'appId' => '########',
'secret' => '##########################',
'cookie' => true,
));
$req_perms = "publish_stream,offline_access,user_status,email,read_stream";
$session = $facebook->getSession();
$loginUrl = $facebook->getLoginUrl(array('canvas'=> 1,'fbconnect' => 0,'req_perms' => $req_perms));
$user_info = null;
if (!$session)
{ echo "<script type='text/javascript'>top.location.href = '$loginUrl';</script>";exit;}
else{
try { $user_info = $facebook->api('/me'); }
catch (FacebookApiException $e)
{ echo "<script type='text/javascript'>top.location.href = '$loginUrl';</script>"; exit;}
}
?>
<!doctype html>
<html>
<head>
</head>
<body>
<?php
$user_name=$user_info['name'];
echo "Hi $user_name ! Your Facebook ID is: ".$user_info['id']."<br/>";
echo "Hi $user_name ! Your E-mail Address is: ".$user_info['email']."<br/>";
echo "Thanks for accepting our application.";
//print_r($user_info);
?>
</body>
</html>

Related

facebook php sdk to make login and logout?

I am trying to login a website by using facebook. For that I have taken the help of Facebook php SDK. For now my code looks like this
<div id="fb-root"></div>
<script type="text/javascript">
//<![CDATA[
window.fbAsyncInit = function() {
FB.init({
appId : 'xxxxxxxxxxxxxx', // App ID
channelURL : '', // Channel File, not required so leave empty
status : true, // check login status
cookie : true, // enable cookies to allow the server to access the session
oauth : true, // enable OAuth 2.0
xfbml : false // parse XFBML
});
};
// logs the user in the application and facebook
function login(){
FB.getLoginStatus(function(r){
if(r.status === 'connected'){
window.location.href = 'fbconnect.php';
}else{
FB.login(function(response) {
if(response.authResponse) {
//if (response.perms)
window.location.href = 'fbconnect.php';
} else {
// user is not logged in
}
},{scope:'email'}); // which data to access from user profile
}
});
}
// Load the SDK Asynchronously
(function() {
var e = document.createElement('script'); e.async = true;
e.src = document.location.protocol + '//connect.facebook.net/en_US/all.js';
document.getElementById('fb-root').appendChild(e);
}());
//]]>
</script>
<?php
require_once 'src/facebook.php'; //include the facebook php sdk
$facebook = new Facebook(array(
'appId' => 'xxxxxxxxxxxxxx', //app id
'secret' => 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx', // app secret
));
$user = $facebook->getUser();
if ($user) { // check if current user is authenticated
try {
// Proceed knowing you have a logged in user who's authenticated.
$user_profile = $facebook->api('/me'); //get current user's profile information using open graph
}
catch(Exception $e){}
}
?>
<a href='#' onclick='login();'>Facebook Login</a>
Now with this code I can do login easily. But after this I need two more things.
Make a logout after login. So how can I make a logout function here
so that when a user will click on logout he will be logout from both
facebook and the site at a time.
How to get user info after login like his name, email id etc.
So can someone kindly tell me how to do this? I am just a newbie in facebook app. So any help and suggestions will be raelly appreciable. Thanks
To get the Logout URL u can try this:
$fbUserId = $facebook->getUser();
if ($fbUserId) {
$host = $_SERVER['HTTP_HOST'];
$params = array('next' => "http://{$host}/project/page.php");
$logoutUrl = $facebook->getLogoutUrl($params);
}
For Getting the User Details you can try this
try {
$user_profile = $facebook->api('/me');
} catch (FacebookApiException $e) {
return false;
}
return $user_profile;

Authenticating Facebook with PHP and jQuery

I am having a little trouble authenticating with the below code.
I have a page that produces a loginUrl for the user to login/authenticate my app on Facebook:
<?php
$loginUrl = $facebook->getLoginUrl(array('scope' => 'publish_stream, read_friendlists, user_birthday', 'redirect_uri' => 'complete.php'));
?>
<div id="connect_facebook">
<a class="button" href="<?php echo $loginUrl; ?>">Connect to Facebook</a>
</div>
And my complete.php has a script that does the following:
<script>
$(document).ready(function() {
pop_db();
});
function pop_db() {
$.post(
"pop_db.php",
function(data) {
alert(data);
}
);
}
</script>
And my pop_db.php file looks like:
<?php
require_once('constants.php');
$response = array();
$user = $facebook->getUser();
if($user) {
try {
// make API calls
$response['code'] = "success";
} catch (FacebookApiException $e) {
error_log($e);
$user = null;
}
} else {
$response['code'] = "failure";
$response['userID'] = $facebook->getUser();
$response['access_token'] = $facebook->getAccessToken();
}
echo json_encode($response);
?>
And constants.php has my secret info for the Facebook object (and it also creates the $facebook object).
My issue is that when I do this using "complete.php" as the redirect and try to do the API calls async using this jQuery, I get back a response that userID = 0 (meaning the user isn't logged in) but it seems like I get a valid access token. When I use "pop_db.php" as my redirect instead of "complete.php" and therefore don't use any async calls, everything works fine.
Am I missing something? Why does it keep telling me the user isn't logged in?
Any suggestions are much appreciated.
Who are getting problem to login their own website thorough facebook / integrate facebook login to their website just follow the given link "http://developers.facebook.com/docs/howtos/login/server-side-login/#step2".It is a very nice link which can solve your problem definitely.
Thanks.
banalata.
"

How do you get a facebook user's information and insert it into a database?

I wasn't sure how to ask it, but I am trying to teach myself how to create a program that uses the graph api. Most of the tutorials I have seen are older, and I don't know how relevant they are now. Essentially, I am trying to get the "thing" where someons clicks my app, it says, this app wants your username, etc. and then Allow or Don't Allow.
I want it to take the information and then I can insert it into a database. I am using php and have a domain.
I can insert the data no problem, if I can get the data. I don't understand how to do it.
I'm sorry for a vague question, and I have searched. Not asking you to write my code for me, just point me in the right direction, maybe to a modern tutorial doing what I am asking. Thanks.
1) Create a Facebook application from here:
http://developers.facebook.com/apps
And configure it with your domain.
This step is really easy, put any namespace you want that will be your application name, then check that your application will be used as an "application and login page" (not a fan page or something related) and finally specify the URLs where you will use Facebook API (leave Canvas URL blank).
Just a heads up, I believe Facebook API requires HTTPS URLs but I don't know why is still allowing HTTP, so don't worry by now.
Login config:
Set the URL: http://yourdomain.com/
Application config:
http://yourdomain.com/myfacebookapp/
So, when a user goes to:
http://apps.facebook.com/yourappName
Means that a user is really browsing the first link and in that page (let's say index.php) you will need to do everything from below.
Just FYI, at this point you can also set a logo for your application, manage administrators and get your application ID and secret that you will use in your PHP file later.
(If you get confused in this step you can do a Google search, this configuration is easy to find)
2) I always use these files to link my PHP enviroment with Facebook API, here's the link from my Dropbox: https://www.dropbox.com/s/itw4pav1f7a9vez/files.rar
3) Put those files in a folder called fb.
4) I will show you the way to get data and picture from a user but first the user has to allow your application to get this info when getting logged in your application.
So, for this example I will use a simple button for the login:
(Don't forget to replace your application ID and secret, notice the 'xxx' and 'yyy')
<?php
require 'fb/facebook.php';
$facebook = new Facebook(array(
'appId' => 'xxx',
'secret' => 'yyy',
));
// Check if user is already logged
$user = $facebook->getUser();
if ($user) {
try {
$user_profile = $facebook->api('/me');
} catch (FacebookApiException $e) {
error_log($e);
$user = null;
}
}
// Get login or logout URL
if ($user) {
$logoutUrl = $facebook->getLogoutUrl();
} else {
$loginUrl = $facebook->getLoginUrl();
}
?>
<html xmlns:fb="http://www.facebook.com/2008/fbml">
<head>
<title>Facebook PHP SDK</title>
</head>
<body>
<h1>Facebook PHP SDK</h1>
<?php if ($user): ?>
Logout
<?php else: ?>
<div>
Login with Facebook
</div>
<?php endif ?>
<h3>PHP Session</h3>
<pre><?php print_r($_SESSION); ?></pre>
<?php if ($user): ?>
<h3>Your picture</h3>
<img src="https://graph.facebook.com/<?php echo $user; ?>/picture">
<h3>Your info (/me)</h3>
<pre><?php print_r($user_profile); ?></pre>
<?php else: ?>
<strong><em>You are not connected.</em></strong>
<?php endif ?>
</html>
5) Above example uses Facebook PHP SDK without JavaScript. So, if user wants to login and authorize your application to get the info then the whole page will be redirected to the Facebook permissions page of your application and after it will go back to the main page of your Facebook application (specified in the configurations from your application).
6) Below code will do the same as above but using JavaScript and custom Facebook login button that allows you to put special permissions as you wrote in your question. Another difference is that a popup will appear instead of redirecting the whole page.
(Don't forget to replace your application ID and secret, notice the 'xxx' and 'yyy')
<?php
require 'fb/facebook.php';
$facebook = new Facebook(array(
'appId' => 'xxx',
'secret' => 'yyy',
));
// Check if user is already logged
$user = $facebook->getUser();
if ($user) {
try {
$user_profile = $facebook->api('/me');
$logoutUrl = $facebook->getLogoutUrl();
} catch (FacebookApiException $e) {
$user = null;
}
} else {
$loginUrl = $facebook->getLoginUrl();
}
?>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Facebook PHP SDK</title>
</head>
<body>
<fb:login-button size="small" onlogin="after_login_button()" scope="email, user_about_me, user_birthday, user_status, publish_stream, user_photos, read_stream, friends_likes">Login with facebook</fb:login-button>
<div id="fb-root"></div>
<script>
window.fbAsyncInit = function() {
FB.init({
appId: '<?php echo $facebook->getAppID() ?>',
cookie: true,
xfbml: true,
oauth: true
});
// This is used by Facebook login button
FB.Event.subscribe('auth.login', function(response) {
if (response.authResponse) {
// Specify the login page where Facebook login button is located
window.location = 'main.php';
}
});
FB.Event.subscribe('auth.logout', function(response) {
window.location = 'logout.php';
});
};
(function() {
var e = document.createElement('script');
e.async = true;
e.src = document.location.protocol + '//connect.facebook.net/en_US/all.js';
document.getElementById('fb-root').appendChild(e);
}());
function after_login_button(){
FB.getLoginStatus(function(response) {
if (response.status == 'connected') {
// If user is connected, redirect to below page
window.location = 'main.php';
}
}, true);
}
</script>
</body>
</html>
7) As you can see, the scope attribute in the Facebook login button determines which special permissions and info your application will need from a user like the email for example (which is always private unless authorized).
8) To add something, you can get only public information from someone by using the following:
// For example: Your Facebook friend's profile is http://www.facebook.com/foobar
$myFriend = $facebook->api('/foobar');
// For example: Your Facebook friend's profile is http://www.facebook.com/users/1002020300010
$myFriend = $facebook->api('/1002020300010');
// Print the name
echo $myFriend['name'];
// Print all data
print_r($myFriend);
And, in order to get your Facebook friend's picture just do this:
<img src="https://graph.facebook.com/foobar/picture">
Or:
<img src="https://graph.facebook.com/1002020300010/picture">
Finally, supposing that you have all user info that was needed then now you can save it all into DB without problems or restrictions.
Hope this helps as reference.
It seems that you are looking to creating an authentication (login) using Facebook.
You may wish to check out Opauth, it handles all of that for you and returns you the user info in an array, of which you can then insert into database easily.
See http://opauth.org for a quick demo and download the library which contains sample code.
Considering that you are using the PHP SDK Classes provided by Facebook here
You can do something like this
$fb = new Facebook(array(
'appId' => 'YOUR_APP_ID',
'secret' => 'YOUR_APP_SECRET'
));
$userData = $fb->api('/me','GET');
$userData = serialize($userData);
//now userdata is a string, so, insert into the database.
Remembering, in your app configurantion, you must specify the kind of information you want from user.
You can use the php API and the query language that facebook provides (FQL). Here is a link that contains sample query's and tutorials http://developers.facebook.com/docs/reference/fql/

Facebook API help

Where do I go from here? This is almost just copy paste from the example provided in the sdk. I don't understand how people can build anything with this API?? How do I open the prompt screen for login etc? Where the heck does Facebook say something about that?
<?php
require 'fb_sdk/src/facebook.php';
// Create our Application instance (replace this with your appId and secret).
$facebook = new Facebook(array(
'appId' => 'APIID',
'secret' => 'SECRET',
));
// 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.
$user_profile = $facebook->api('/me');
} catch (FacebookApiException $e) {
error_log($e);
$user = null;
}
}
// Permissions requested from the user.
$par = array();
$par['scope'] = 'user_about_me, read_friendlists';
// Login or logout url will be needed depending on current user state.
if ($user) {
$logoutUrl = $facebook->getLogoutUrl();
} else {
$loginUrl = $facebook->getLoginUrl($par);
}
?>
You can find information on using the Graph for user authentication here on Facebook Developers.
With $loginUrl = $facebook->getLoginUrl($par); the variable $loginUrl will contain a url to the authentication dialog. Most developers either present this to the user as a link or perform a redirect with javascript - eg:
die('<script>top.location.href = "' . $loginUrl . '"</script>');
The other alternative is to use the JavaScript SDK with XFBML to authenticate (if you have cookies enable with both SDKs they will share session data) - example from here:
<?php
require 'php-sdk/src/facebook.php';
$facebook = new Facebook(array(
'appId' => 'YOUR_APP_ID',
'secret' => 'YOUR_APP_SECRET',
));
// See if there is a user from a cookie
$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) {
echo '<pre>'.htmlspecialchars(print_r($e, true)).'</pre>';
$user = null;
}
}
?>
<!DOCTYPE html>
<html xmlns:fb="http://www.facebook.com/2008/fbml">
<body>
<?php if ($user_profile) { ?>
Your user profile is
<pre>
<?php print htmlspecialchars(print_r($user_profile, true)) ?>
</pre>
<?php } else { ?>
<fb:login-button></fb:login-button>
<?php } ?>
<div id="fb-root"></div>
<script>
window.fbAsyncInit = function() {
FB.init({
appId: '<?php echo $facebook->getAppID() ?>',
cookie: true,
xfbml: true,
oauth: true
});
FB.Event.subscribe('auth.login', function(response) {
window.location.reload();
});
FB.Event.subscribe('auth.logout', function(response) {
window.location.reload();
});
};
(function() {
var e = document.createElement('script'); e.async = true;
e.src = document.location.protocol +
'//connect.facebook.net/en_US/all.js';
document.getElementById('fb-root').appendChild(e);
}());
</script>
</body>
</html>
You can also login purely with JavaScript using FB.Login:
FB.login(function(response) {
if (response.authResponse) {
console.log('Welcome! Fetching your information.... ');
FB.api('/me', function(response) {
console.log('Good to see you, ' + response.name + '.');
FB.logout(function(response) {
console.log('Logged out.');
});
});
} else {
console.log('User cancelled login or did not fully authorize.');
}
}, {scope: 'user_about_me, read_friendlists'});
It is mentioned in the comment :
// Login or logout url will be needed depending on current user state.
if ($user) {
$logoutUrl = $facebook->getLogoutUrl();
} else {
$loginUrl = $facebook->getLoginUrl($par);
}
SDK will take care of that, you need not worry about it.
The user details are there in $user_profile
do a echo"<pre>"; print_r($user_profile); echo"</pre>"; and you will get it.

Posting to a Facebook Page as the Page (not a person)

I use Facebook PHP SDK 3.0.1 (latest currently).
What I need to be able to do is to post as a the identity of the Page on the Page.
I tried replacing the access_token with the access_token I get from the page (/me/accounts) however it now says token is invalid for some reason.
Facebook "impersonation" pages are offline now, and I don't see any info in the API regarding doing what I want.. maybe I'm lost or maybe not looking in the right direction..
Here's the example.php that I modified and use to archive this:
require '../src/facebook.php';
// Create our Application instance (replace this with your appId and secret).
$facebook = new Facebook(array(
'appId' => 'xxxxxxxxxxxxx',
'secret' => 'xxxxxxxxxxxxxxxxxxxxxxxxxx'
));
// Get User ID
$user = $facebook->getUser();
//Lists all the applications and pages
if ($user) {
try {
// Proceed knowing you have a logged in user who's authenticated.
$accounts_list = $facebook->api('/me/accounts');
} catch (FacebookApiException $e) {
error_log($e);
$user = null;
}
}
$page_selected = 'xxxxxxxxxxxx';
$page_access_token = $accounts_list['data']['0']['access_token'];
echo 'page_access_token:' . $page_access_token;
<?php
if (isset($_GET['publish'])){
try {
$publishStream = $facebook->api("/$page_selected/feed", 'post', array(
'access_token' => '$page_access_token',
'message' => 'Development Test message',
'link' => 'http://xxxxxxx.com',
'picture' => 'http://xxxxxx/xxxx_logo.gif',
'name' => 'xxxxxxxx Goes Here',
'description'=> 'And the exciting description here!'
)
);
//as $_GET['publish'] is set so remove it by redirecting user to the base url
} catch (FacebookApiException $e) {
echo($e);
echo $publishStream;
echo 'catch goes here';
}
}
?>
Since I can't answer my own question I edited the question.
Went through the whole API..
Solution:
Before posting as the page you need to set your access_token to the one page owns.
$facebook->setAccessToken($page_access_token);
does just that, and afterwards everything goes as it normally would be expected, no need to modify post function and add "access_token" option to post.
1.First you have to get the page access token.
public function getPageToken()
{
$page_id = "xxxxxxxxxx";
$page_access_token = "";
$result = $this->facebook->api("/me/accounts");
if( !empty($result['data']) )
{
foreach($result["data"] as $page)
{
if($page["id"] == $page_id)
{
$page_access_token = $page["access_token"];
break;
}
}
}
else
{
$url = "https://www.facebook.com/dialog/oauth?client_id=xxxxxxxxxx&redirect_uri=http://apps.facebook.com/xxxxxx&scope=manage_pages&response_type=token";
echo "<script type='text/javascript'> top.location.href='".$url."'; </script>";
}
return $page_access_token;
}
2.After getting the page access token just include that token in your post to wall code.
<script src="//connect.facebook.net/en_US/all.js"></script>
<script type="text/javascript">
var token = '<?php echo $page_access_token ?>';
var wallPost = {
access_token: token,
message : 'xxxxxxxx',
link : 'http://apps.facebook.com/xxxxxxx/',
picture : 'xxxxxxxx',
name : 'xxxxx',
caption : 'xxxxxx',
description : 'xxxxxxx',
};
FB.api('/pageid/feed', 'post', wallPost, function(response) {
if (!response || response.error) {
} else {
}
});
</script>
3.Remember this code will only publish your post on Fan page's wall and users who liked the fan page will be able to see that post as the post is posted on their own feed.
Hope this will solve your problem.

Categories