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.
Related
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;
I am using facebook SDK to get facebook friends list. If I Invoke API with Javascript FB.init(); it works perfectly fine..
but if I use it directly like
facebook = new Facebook(array(
'appId' => $appid,
'secret' => $secret
));
$fbuser = $facebook->getUser();
try{
$user_profile = $facebook->api('/me');
print_r($user_profile);
} catch(Exception $e){
echo $e->getMessage();
}
(User is logged in with facebook in the same browser)
It always gives me an error : An active access token must be used to query information about the current user.
Please help me how to use it without FB.init() or redirect anywhere..
Use this
facebook = new Facebook(array(
'appId' => $appid,
'secret' => $secret,
'cookie' => true
));
$fbuser = $facebook->getUser();
if($fbuser){
$access_token = $facebook->getAccessToken();
$facebook->setAccessToken($access_token);
try{
$user_profile = $facebook->api('/me');
print_r($user_profile);
} catch(Exception $e){
echo $e->getMessage();
}
}else{
// User not logged in generate the login button or link here
}
Make sure in the above script when user login ffor the first time it reloads the page in other words you need to provide the redirect_uri
https://developers.facebook.com/docs/reference/php/facebook-getLoginUrl/
Also you can use the following api to get the user details
$user_profile = $facebook->api('/'. $fbuser,'GET');
Then add the following below the page. This will check if the user is already logged in it will re-direct to the same page, in other words it will not ask user to login again
<div id="fb-root"></div>
<script type="text/javascript">
window.fbAsyncInit = function()
{
FB.init
({
appId : 'your fb app id',
status : true, // check login status
cookie : true, // enable cookies to allow the server to access the session
xfbml : true, // parse XFBML
oauth : true
});
FB.Event.subscribe('auth.login', function()
{
window.location.reload();
});
};
(function()
{
var e = document.createElement('script');
e.src = document.location.protocol + '//connect.facebook.net/en_US/all.js';
e.async = true;
document.getElementById('fb-root').appendChild(e);
}());
</script>
im getting "OAuthException: An active access token must be used to query information about the current user" once every two page loads (with any authenticated user), the correct load gets the user info with out any problems.
This is my current script:
$facebook = new Facebook(array(
'appId' => 'XXXXXXXXXXXXXXXX',
'secret' => 'XXXXXXXXXXXXXXXXXXXXXXXXX',
'cookie' => true,
));
//obtiene las Variables Iniciales
$user = $facebook->getUser();
if ($user) {
try {
$user_profile = $facebook->api('/me');
} catch (FacebookApiException $e) {
error_log($e);
$user = null;
}
}
if ($user) {
$logoutUrl = $facebook->getLogoutUrl(array( 'next' => ('http://xxxxx.com/Salir') ));
} else {
$loginUrl = $facebook->getLoginUrl(array('scope' => 'email,user_birthday,user_hometown,user_location'));
}
This is the button:
<fb:login-button perms='email,user_birthday,user_hometown,user_location' length='long' autologoutlink='false' onlogin='fbLogin();'></fb:login-button>
<div id='fb-root'></div>
<script>
window.fbAsyncInit = function() {
FB.init({
appId: '$FBid',
cookie: true,
xfbml: true,
oauth: true
});
FB.Event.subscribe('auth.login', function(response) {
return false;
});
FB.Event.subscribe('auth.logout', function(response) {
return false;
});
};
(function() {var e = document.createElement('script'); e.async = true;
e.src = document.location.protocol +
'//connect.facebook.net/es_ES/all.js';
document.getElementById('fb-root').appendChild(e);
}());
</script>
Does anyone have any idea about why this is happening?
Thanks for the help :D
I apologize for my bad English.
I am using codeigniter on my site and I use facebook login to login but I have a problem.
->getUser does not return any data when I try my normal codeigniter project. But, in the new folder which is not related my project I try to login from example.php which comes from facebook sdk it works well.
I have checked everything (autoloads, config, etc.)
I think my problem is about sessions.
Thanks for your help.
I suggest that you use the new version of PHP SDK for the Facebook API. I had the same problem with version 3.0.1, that is why I use the previews version 2.1.2 which works just fine.
Unfortunately I don't have time to play with the new version (3.0.1) but there is a very simple example with version 2.1.2:
Config
/* application/config/autoload.php */
$autoload['libraries'] = array('template', 'session', 'facebook');
Library
/* application/libraries/Facebook.php */
require_once("Facebook/2.1.2/facebook.php");
class CI_Facebook extends Facebook {}
Template
/* application/views/template.php */
$facebook = new Facebook(array(
'appId' => 'xxxxxxxxxxxxxx',
'secret' => 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx',
'cookie' => true
));
$session = $facebook->getSession();
$me = null;
// Session based API call.
if ($session) {
try {
$uid = $facebook->getUser();
$me = $facebook->api('/me');
} catch (FacebookApiException $e) {
error_log($e);
}
}
// login or logout url will be needed depending on current user state.
if ($me) {
$logoutUrl = $facebook->getLogoutUrl();
} else {
$loginUrl = $facebook->getLoginUrl();
}
?>
<div id="fb-root"></div>
<script>
window.fbAsyncInit = function() {
FB.init({
appId : '<?php echo $facebook->getAppId(); ?>',
session : <?php echo json_encode($session); ?>,
cookie : true,
xfbml : true
});
// whenever the user logs in, we refresh the page
FB.Event.subscribe('auth.login', function() {
window.location.reload();
});
};
(function() {
var e = document.createElement('script');
e.src = document.location.protocol + '//connect.facebook.net/en_US/all.js';
e.async = true;
document.getElementById('fb-root').appendChild(e);
}());
</script>
I have a working single sign on for facebook that works (most of the time) But for whatever reason I occasionally get an error. I'm trying to write a fallback method that uses the php sdk login that directs to facebook and then forwards back to the url, once facebook redirects back to my page I can see session data in the URL under $_GET['session'] as a json string, I need to figure out how to use that string to make valid API calls.
<?php
require_once "facebook_sdk.php";
$facebook = new Facebook(array('appId' => '123','secret' => '456','cookie' => true,));
$session = null;
$_fb_profile = null;
$session = $facebook->getSession();
//get links for login/logout
$loginUrl = $facebook->getLoginUrl();
$logoutUrl = $facebook->getLogoutUrl();
if($session){
try {
$facebook_id = $facebook->getUser();
$_fb_profile = $facebook->api('/me'); //if not null valid session
$facebook_name = $_fb_profile['name'];
$facebook_link = $_fb_profile['link'];
}
catch (FacebookApiException $e) {
echo $e;
}
}
//there is not a valid session though the single sign on FBML button, try checking php login
if(!$_fb_profile){
$session = $_GET['session'];//json string from facebook
$session = json_decode($session);//make into an array
try {
$facebook->setSession($session,true);//need to set the session some how with $_GET['session']
$facebook_id = $facebook->getUser();
$_fb_profile = $facebook->api('/me');
$facebook_name = $_fb_profile['name'];
$facebook_link = $_fb_profile['link'];
}
catch (FacebookApiException $e) {
die($e); //getting invalid OAuth access token
}
}
?>
<div id="fb-root"></div>
<script>
window.fbAsyncInit = function() {
FB.init({
appId : '<?php echo $facebook->getAppId(); ?>',
session : <?php echo json_encode($session); ?>, // don't refetch the session when PHP already has it
status : true, // check login status
cookie : true, // enable cookies to allow the server to access the session
xfbml : true // parse XFBML
});
// whenever the user logs in, we refresh the page
FB.Event.subscribe('auth.login', function() {
window.location.reload();
});
};
(function() {
var e = document.createElement('script');
e.src = document.location.protocol + '//connect.facebook.net/en_US/all.js';
e.async = true;
document.getElementById('fb-root').appendChild(e);
}());
</script>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
</head>
<body>
<?php if(!$session || !$_fb_profile){
//user is not logged in show FBML button and php login link
echo "<fb:login-button perms='email,user_birthday,user_education_history,read_friendlists,publish_stream'></fb:login-button>
<p class='small' style='float:right;'>Having trouble? try <a href='$loginUrl'>logging in here</a></p>";
}
else{
//user has logged in
echo "You are logged into facebook as <a href='$facebook_link'>$facebook_name</a>";
}?>
</body>
</html>