php An active access token must be used to query - php

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>

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;

how to integrate twitter login and facebook login in a web site using codeigniter?

I have already used twitter oauth and facebook library to login to my website.It works fine before now it is not working :(.I have debug the code and got to know that twitter access token and secret is not returning.For facebook login it also didnt get user id.pls help
Step 1: Download facebook library.https://github.com/facebook/facebook-php-sdk/tree/master/src
Step 2: Upload it in \application\libraries
Step 3:Create a facebook application.You wil get appId and secretcode.Paste the below code in your controller facebook() function.Set the appId and secret.
$config = array(
'appId' => '234353465466',
'secret' => 'xxxxxxxxxxxxxxxxxxxxxxxxxxxx',
'fileUpload' => true, // Indicates if the CURL based # syntax for file uploads is enabled.
);
$this->load->library('Facebook',$config);
$user = $this->facebook->getUser();
if($user){
try {
$profile = $this->facebook->api('/me?fields=id,name,link,email');
}
catch (FacebookApiException $e) {
$user = null;
}
echo '<pre>';
print_r($profile);
Step 4:Paste the below code in the view page and change the appId and domain name.
<div id="fb-root"></div>
<script type="text/javascript">// <![CDATA[
window.fbAsyncInit = function() {
FB.init({appId: '234463456', status: true, cookie: true,xfbml: true,oauth: true});};
(function() {
var e = document.createElement('script');
e.type = 'text/javascript';
e.src = document.location.protocol+'//connect.facebook.net/en_GB/all.js';
e.async = true;
document.getElementById('fb-root').appendChild(e);
}());
function login()
{
FB.getLoginStatus(function(response) {
if (response.status === 'connected') {
document.location.href = "http://www.mydomain.com/facebook?accessToken="+response.authResponse.accessToken;
}
});
}
// ]]></script>
<fb:login-button scope="email" onlogin="login();" >Sign in with Facebook</fb:login-
for more - http://www.livey.info/blog/category/php/codeigniter/

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.

Facebook Login Problem

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>

pass facebook connect session from php to javascript

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>

Categories