Authenticating Facebook with PHP and jQuery - php

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.
"

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;

Stop the condition once it executes

Problem
I am using below mentioned JS code in my PHP try catch. Basically I am making facebook app. In that when users session gets timed out it shows an error message which doesn't look good but when a user refreshes the page it starts working perfectly. For that reason I used PHP try catch to know whether the session got timed out or not if yes then in catch I run the below JavaScript code. I want to auto refresh the page instead of asking user to do it manually.
The below code refreshes the page but then it keeps refreshing it. I'm new to javascript can you please suggest how should I get out of this condition once it gets true.
Code
try{
$facebook = new Facebook(array(
'appId' => '123456789',
'secret' => 'some_secret',
));
$accessToken = $facebook->getAccessToken();
$facebook->setAccessToken($accessToken);
$user_profile = $facebook->api('/me','GET');
$username= $user_profile['email'];
$fb_id= $user_profile['id'];
}catch(Exception $e){
location.reload(true);
console.log('Session has been timed out');
}
<script type="text/javascript">
if(window.location.hash==-1)
{
//add a # if it doesn't exist
newurl = document.URL+"#";
location = "#";
//Refresh page
location.reload(true);
}
</script>
or try this(will not work if the user has disabled local storage/cookies)
function()
{
if( window.localStorage )
{
if( !localStorage.getItem( 'firstLoad' ) )
{
localStorage[ 'firstLoad' ] = true;
location.reload(true);
}
else
localStorage.removeItem( 'firstLoad' );
}
}

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 Oauth 2.0 Login using PHP 3.1.1 and Javascript SDKs

I am trying to migrate to the new Facebook API for websites, and just can't get it to work smoothly. I would like to use the Javascript and PHP SDKs together, but am having problems. I can authenticate, but the page doesn't refresh automatically.
I have searched throughout SO and the Facebook documentation, but still can't get this to work correctly. I have read through http://developers.facebook.com/blog/post/534/, dowloaded the latest PHP SDK (3.1.1), and basically copied the example on the aforementioned post from facebook. I have made what I think are the correct settings in my app 'Migration' settings, but this could be where the problem lies. I can't post an image, so here are the setting:
Remove Deprecated API's: Enabled
Forces use of login secret: Enabled
Encrypted Access token: Enabled
Enhanced Auth Dialog: Enabled
(Everything else is disabled)
Here is the code:
<?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>
I was going to write this as a comment but it got a bit long... :)
A couple of pointers using the PHP SDK:
$facebook->getUser();
This will work regardless of authentication. getUser() pulls publicly available data that does not require an access token, HOWEVER if you do have an access token and the user has provided email permissions for example, this method will also contain their email address.
A better test for an authenticated user:
$code = $_REQUEST['code'] ? true : false;
if (!$code) {
echo ("<script>window.top.location=\"...\"</script>");
}
will check if a user has authorised your app.
$access = $facebook->getAccessToken();
Make sure that you always request the Access Token (priority!) You will only ever recieve a signed request when you have been redirected from a facebook dialogue to your app. (i.e.) oAUTH dialogue. This method of the SDK will also save your Access Token to a session variable. You can call the getAccessToken() method on any subsequent app page where a PHP session is active EVEN WHEN no signed request has been issued.
Now that you have your valid access token for the logged in user, you can proceed with:
$user = $facebook->api('/me');
or, simpler still:
$user = $facebook->getUser();
I tend to reserve API calls for more complex requests such as posting to a users feed / friends feed.
So to recap:
-> check for $code
-> get signed request on first page after oAuth dialogue.
-> If browser cookies are disabled (likely in ie) don't forget to pass your session to the next page with the SID constant. If you don't, you will loose your stored access token (not good!).

How get facebook user ID from my application?

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>

Categories