I'm authenticating via PHP:
// the php facebook api downloaded at step 3
require_once("facebook-client/facebook.php");
// start facebook api with the codes defined in step 1.
$fb=new Facebook( 'XXXXXXXXXXXXXXXXXXXX' , 'a3eaa49141ed38e230240e1b6368254a' );
$fb_user=$fb->get_loggedin_user();
var_dump($fb_user);
And the session is created in PHP. I want to use it with facebook javascript client library from here on out. How do I do this?
With this you can promote a session from PHP to JavaScript and from JavaScript to PHP using the Facebook->setSession() function
<?php
require 'facebook.php';
// Create our Application instance (replace this with your appId and secret).
$facebook = new Facebook(array(
'appId' => $appId,
'secret' => $secret,
'cookie' => true,
));
$_SESSION['facebook'] = $facebook;
// We may or may not have this data based on a $_GET or $_COOKIE based session.
//
// If we get a session here, it means we found a correctly signed session using
// the Application Secret only Facebook and the Application know. We dont know
// if it is still valid until we make an API call using the session. A session
// can become invalid if it has already expired (should not be getting the
// session back in this case) or if the user logged out of Facebook.
$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);
}
}else{
//pass in json object of FB._session and convert it to array
$session = json_decode(stripslashes($_POST['session']));
$session = (array) $session;
if($session)
$facebook->setSession($session);
}
?>
var constant = {};
constant.session = <?php echo json_encode($session); ?>;
window.fbAsyncInit = function() {
FB.init({
appId : '<?php echo $facebook->getAppId(); ?>',
session : constant.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
});
if(!FB._session)
stream.load();
else
jwpage.getAlbums();
// whenever the user logs in, we refresh the stream
FB.Event.subscribe('auth.login', function() {
jwpage.getAlbums();
});
};
(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>
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>
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!).
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 am successfully using the Facebook SDK (PHP) to connect users to my site, but I'm having issues when they authenticate their account. Their account is successfully authenticated, but for some reason my site's sessions are cleared.
Flow:
User logs into my site (local username and password)
User connects to Facebook in a popup
Facebook authenticates user and returns back to my site
My sites session is now invalid (both in the popup and main window) causing the user to be logged out
I am using the Facebook SDK (PHP) and my site uses the CakePHP framework
Any help will be greatly appreciated.
I can't tell you what is deleting your session, but you might want to try this (works for me)
use the Javascript SDK to display the login buttons that will open the popup to connect to FB
add the js SDK to your page like this:
<div id="fb-root"></div>
<script>
window.fbAsyncInit = function() {
FB.init({appId: '<?php echo FB_API_ID; ?>', status: true, cookie: true, xfbml: true});
FB.Event.subscribe('auth.login', function() {
new Request({
'method': 'get',
'url': '<?php echo $this->Html->url(array('controller'=>'users','action'=>'login_fb'));?>',
'onSuccess': function(result){
window.location.reload();
}
}).send();
});
};
(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>
On the auth.login event i'm using an ajax call to /users/login_fb that will use the Facebook SDK to check the facebook session:
App::import('Lib', 'facebook_sdk/facebook');
// "MyAuth" is a custom Auth Component that extends the normal Auth component
$this->MyAuth->facebook = new Facebook(array(
'appId' => FB_API_ID,
'secret' => FB_SECRET,
'cookie' => true,
));
$me = null;
$session = $this->MyAuth->facebook->getSession();
if ($session) {
try {
$uid = $this->MyAuth->facebook->getUser();
$me = $this->MyAuth->facebook->api('/me');
} catch (FacebookApiException $e) {
error_log($e);
}
}
if ($me) {
$this->Session->write('FbLogin.session',$session);
$this->Session->write('FbLogin.user',$me);
$UserModel = ClassRegistry::init('User');
$user = $UserModel->findByUid($me['id']);
if(!$user){
$UserModel->create();
$user_data = array( 'username'=>$me['username'],
'name'=>$me['first_name'],
'lastname'=>$me['last_name'],
'email'=>$me['email'],
'group_id'=>GROUP_VISITOR,
'uid'=>$me['id']
);
$UserModel->save($user_data);
$user['User']['id'] = $UserModel->id;
}
$this->Session->write($this->MyAuth->sessionKey, $user['User']);
$this->MyAuth->_loggedIn = true;
}
}
the main idea is that.. in js i call an ajax to check the fb session and then save it in the cake session , and the js will refresh the page
Could be worth checking the Cake security level, it might be doing referrer checks (I think it does this in the "high" setting, maybe the "medium" as well), which would be invalidating the session.
I couldn't find out why the session was being reset so decided not to use the SDK for the authentication. This is what I used instead.
$code = (isset ($_REQUEST['code']) ? $_REQUEST['code'] : null);
if (empty ($code)) {
$dialogUrl = 'http://www.facebook.com/dialog/oauth?client_id=' . $this->appId . '&redirect_uri=' . urlencode($this->url) . '&scope=' . implode(',', $this->scope);
header('Location: ' . $dialogUrl);
die;
}
else {
$tokenUrl = 'https://graph.facebook.com/oauth/access_token?client_id=' . $this->appId . '&redirect_uri=' . urlencode($this->url) . '&client_secret=' . $this->secret . '&code=' . $code;
$accessToken = file_get_contents($tokenUrl);
$this->Session->write('facebookAccessToken', $accessToken);
$graphUrl = 'https://graph.facebook.com/me?' . $accessToken;
$fbUser = json_decode(file_get_contents($graphUrl));
if ($fbUser) {
...
}
}