i am using the following code to get the access_token
<?php
//include the Facebook PHP SDK
include_once 'facebook.php';
//instantiate the Facebook library with the APP ID and APP SECRET
$facebook = new Facebook(array(
'appId' => 'REPLACE WITH APP ID',
'secret' => 'REPLACE WITH APP SECRET',
'cookie' => true
));
//Get the FB UID of the currently logged in user
$user = $facebook->getUser();
//if the user has already allowed the application, you'll be able to get his/her FB UID
if($user) {
//start the session if needed
if( session_id() ) {
} else {
session_start();
}
//do stuff when already logged in
//get the user's access token
$access_token = $facebook->getAccessToken();
//check permissions list
$permissions_list = $facebook->api(
'/me/permissions',
'GET',
array(
'access_token' => $access_token
)
);
//check if the permissions we need have been allowed by the user
//if not then redirect them again to facebook's permissions page
$permissions_needed = array('publish_stream', 'read_stream', 'offline_access', 'manage_pages');
foreach($permissions_needed as $perm) {
if( !isset($permissions_list['data'][0][$perm]) || $permissions_list['data'][0][$perm] != 1 ) {
$login_url_params = array(
'scope' => 'publish_stream,read_stream,offline_access,manage_pages',
'fbconnect' => 1,
'display' => "page",
'next' => 'http://'.$_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI']
);
$login_url = $facebook->getLoginUrl($login_url_params);
header("Location: {$login_url}");
exit();
}
}
//if the user has allowed all the permissions we need,
//get the information about the pages that he or she managers
$accounts = $facebook->api(
'/me/accounts',
'GET',
array(
'access_token' => $access_token
)
);
//save the information inside the session
$_SESSION['access_token'] = $access_token;
$_SESSION['accounts'] = $accounts['data'];
//save the first page as the default active page
$_SESSION['active'] = $accounts['data'][0];
//redirect to manage.php
header('Location: manage.php');
} else {
//if not, let's redirect to the ALLOW page so we can get access
//Create a login URL using the Facebook library's getLoginUrl() method
$login_url_params = array(
'scope' => 'publish_stream,read_stream,offline_access,manage_pages',
'fbconnect' => 1,
'display' => "page",
'next' => 'http://'.$_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI']
);
$login_url = $facebook->getLoginUrl($login_url_params);
//redirect to the login URL on facebook
header("Location: {$login_url}");
exit();
}
?>
But it is not getting back to my redirect URL, Firefox shows the following error
Firefox has detected that the server is redirecting the request for this address in a way that will never complete.
This problem can sometimes be caused by disabling or refusing to accept
cookies.
You can put login and auth process in another file like login.php
And then when you need to authenticate, then use include_once "login.php"; from your app.
Replace your-app-namespace.
<?php
//login.php
require 'lib/facebook.php';
require 'lib/fbconfig.php';
if (isset($_GET['code'])){
header("Location:http://apps.facebook.com/your-app-namespace");
exit;
}
$user=null;
//Facebook Authentication part
$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.
$loginUrl = $facebook->getLoginUrl(
array(
'scope' => 'email,read_mailbox,publish_stream,user_birthday,user_location,read_stream,user_work_history,user_about_me,user_hometown'
)
);
if ($user) {
try {
// Proceed knowing you have a logged in user who's authenticated.
$user_profile = $facebook->api('/me');
} catch (FacebookApiException $e) {
//you should use error_log($e); instead of printing the info on browser
d($e); // d is a debug function defined at the end of this file
$user = null;
}
}
if (!$user) {
echo "<script type='text/javascript'>top.location.href = '$loginUrl';</script>";
exit;
}
//get user basic description
$userInfo = $facebook->api("/$user");
function d($d){
echo '<pre>';
print_r($d);
echo '</pre>';
}
?>
Instead of using
//redirect to the login URL on facebook
header("Location: {$login_url}");
Try using :
echo "<script type='text/javascript'>top.location.href = '$loginUrl';</script>";
Related
index.php
<?php
//facebook application
$fbconfig['appid'] = "32##########";
$fbconfig['secret'] = "ca2dc#############";
$fbconfig['baseurl'] = "http://localhost/sbs/fblogin/index.php";
//
if (isset($_GET['request_ids'])) {
//user comes from invitation
//track them if you need
}
//facebook user uid
try {
include_once "src/facebook.php";
}
catch (Exception $o) {
error_log($o);
}
// Create our Application instance.
$facebook = new Facebook(array(
'appId' => $fbconfig['appid'],
'secret' => $fbconfig['secret'],
'baseurl' => $fbconfig['baseurl'],
'cookie' => true
));
//Facebook Authentication part
$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.
$loginUrl = $facebook->getLoginUrl(array(
'scope' => 'email,offline_access,publish_stream,user_birthday,user_location,user_work_history,user_about_me,user_hometown,user_photos ,user_work_history'
));
$logoutUrl = $facebook->getLogoutUrl();
if ($user) {
try {
// Proceed knowing you have a logged in user who's authenticated.
$user_profile = $facebook->api('/me');
}
catch (FacebookApiException $e) {
//you should use error_log($e); instead of printing the info on browser
// d is a debug function defined at the end of this file
$user = null;
}
}
//if user is logged in and session is valid.
if ($user) {
//get user basic description
$userInfo = $facebook->api("/$user?fields=picture,name,email,gender,birthday");
//$pic = $facebook->api("/$user/pictures");
$profile = json_encode($userInfo);
$res = json_decode($profile, true);
$_SESSION['name'] = $res['name'];
$_SESSION['email'] = $res['email'];
$_SESSION['id'] = $res['id'];
$_SESSION['gender'] = $res['gender'];
$_SESSION['birthday'] = $res['birthday'];
$_SESSION['img'] = $res['picture']['data']['url'];
$_SESSION['auth_type'] = "facebook";
if (isset($_COOKIE['registration']) && $_COOKIE['registration'] == true) {
header("location:../sbs/registration.php");
} else {
header("location:../sbs/sbs_login.php");
}
}
?>
For the 1st time I am working on the Facebook app. I have made app on the Facebook developer. It's working properly but it is not redirecting me in the index.php. I want to redirect it in this page only so all the values are stored in the session and I am checking it if the cookies is made then this value is going to registration.php and if not then its going to sbs_login.php. Please can anybody tell where to give the redirect url?
$loginUrl = $facebook->getLoginUrl(array(
'baseurl' => $fbconfig['baseurl'],
'scope' => 'email,offline_access,publish_stream,user_birthday,user_location,user_work_history,user_about_me,user_hometown,user_photos ,user_work_history'
));
I find the solution of my problem . so this is the solution
$loginUrl = $facebook->getLoginUrl(array(
'baseurl' => $fbconfig['baseurl'],
'scope' => 'email,offline_access,publish_stream,user_birthday,user_location,user_work_history,user_about_me,user_hometown,user_photos ,user_work_history'
So as the title sugests I am using Facebook php sdk to authorize the user on my site, the problem I am having is that after a few minutes of beeing logged in and I refresh the page the $user = $facebook->getUser(); is gone and the page thinks I am logged out but if I refresh again it's authorized again.
index.php
<?php
session_start();
include_once "facebook/fbaccess.php";
?>
fbaccess.php
<?php
//Application Configurations
$app_id = "xxxxxxxxxxxxx";
$app_secret = "XXXXXXXXXXXXXXXXXXXXX";
$site_url = "http://xxxxxxxxx";
try{
include_once "facebook.php";
}catch(Exception $e){
error_log($e);
}
// Create our application instance
$facebook = new Facebook(array(
'appId' => $app_id,
'secret' => $app_secret,
'cookie' => true
));
// 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.
$facebook->setExtendedAccessToken();
$access_token = $facebook->getAccessToken();
if($user){
//==================== Single query method ======================================
try{
// Proceed knowing you have a logged in user who's authenticated.
$user_profile = $facebook->api('/me');
$_SESSION['fid'] = $user_profile['id'];
}catch(FacebookApiException $e){
error_log($e);
$user = NULL;
}
//==================== Single query method ends =================================
}
if($user){
// Get logout URL
$logoutUrl = $facebook->getLogoutUrl();
}else{
// Get login URL
$loginUrl = $facebook->getLoginUrl(array(
'scope' => 'publish_stream', 'offline_access',
'redirect_uri' => $site_url,
));
}
?>
index.php
<div id="mainMenu">
<?php if ($user) {echo '<h5>Logout</h5>'; }else{ echo '<h5>Login</h5>';} ?>
</div>
I am using this tutorial for the login process: http://25labs.com/tutorial-integrate-facebook-connect-to-your-website-using-php-sdk-v-3-x-x-which-uses-graph-api/
Check your session lifetime settings and cookies. Does same behavior exist when you continiously browsing at your website or after some inactivity time only?
I created a contest where a submitted form will:
write a comment on the wall of Facebook staff and
write a comment on the wall of my page
I had no problems with step 1, but step 2 does not work. My code is as follows:
connect.php
<?php
//include the Facebook PHP SDK
include_once 'facebook.php';
//instantiate the Facebook library with the APP ID and APP SECRET
$facebook = new Facebook(array(
'appId' => 'CRYPT FOR THIS FORUM',
'secret' => 'CRYPT FOR THIS FORUM',
'cookie' => true
));
//Get the FB UID of the currently logged in user
$user = $facebook->getUser();
//if the user has already allowed the application, you'll be able to get his/her FB UID
if($user) {
//start the session if needed
if( session_id() ) {
} else {
session_start();
}
//do stuff when already logged in
//get the user's access token
$access_token = $facebook->getAccessToken();
//check permissions list
$permissions_list = $facebook->api(
'/me/permissions',
'GET',
array(
'access_token' => $access_token
)
);
//check if the permissions we need have been allowed by the user
//if not then redirect them again to facebook's permissions page
$permissions_needed = array('publish_stream', 'read_stream');
foreach($permissions_needed as $perm) {
if( !isset($permissions_list['data'][0][$perm]) || $permissions_list['data'][0][$perm] != 1 ) {
$login_url_params = array(
'scope' => 'publish_stream,read_stream',
'fbconnect' => 1,
'display' => "page",
'next' => 'http://'.$_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI']
);
$login_url = $facebook->getLoginUrl($login_url_params);
header("Location: {$login_url}");
exit();
}
}
//if the user has allowed all the permissions we need,
//get the information about the pages that he or she managers
//id pag sposiamo è 494659577226200
$accounts = $facebook->api(
'/me/accounts',
'GET',
array(
'access_token' => $access_token
)
);
//save the information inside the session
$_SESSION['access_token'] = $access_token;
$_SESSION['accounts'] = $accounts['data'];
//save the first page as the default active page
//$_SESSION['active'] = $accounts['data'][0];*/
//redirect to manage.php
header('Location: manage.php');
} else {
//if not, let's redirect to the ALLOW page so we can get access
//Create a login URL using the Facebook library's getLoginUrl() method
$login_url_params = array(
'scope' => 'publish_stream,read_stream',
'fbconnect' => 1,
'display' => "page",
'next' => 'http://'.$_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI']
);
$login_url = $facebook->getLoginUrl($login_url_params);
//redirect to the login URL on facebook
header("Location: {$login_url}");
exit();
}
?>
newpost.php
<?php
//include the Facebook PHP SDK
include_once 'facebook.php';
//start the session if necessary
if( session_id() ) {
} else {
session_start();
}
//instantiate the Facebook library with the APP ID and APP SECRET
$facebook = new Facebook(array(
'appId' => 'CRYPT',
'secret' => 'CRYPT',
'cookie' => true
));
//get the info from the form
$parameters = array(
'message' => $_POST['message'],
'picture' => $_POST['picture'],
'link' => $_POST['link'],
'name' => $_POST['name'],
'caption' => $_POST['caption'],
'description' => $_POST['description']
);
//add the access token to it
$parameters['access_token'] = $_SESSION['active']['access_token'];
//build and call our Graph API request
$newpost = $facebook->api(
'/494659577226200/feed',
'/me/feed',
'POST',
$parameters
);
//redirect back to the manage page
header('Location: manage.php');
exit();
494659577226200 = FBPAGEID
PROBLEM IS '/494659577226200/feed', and error AuthCode 200...
You need to ask your user's to give your app manage_pages permission to post to their pages they manage on behalf of them. Check out their permissions doc here, See Page Permissions section.
Quoted from docs:
manage_pages
Enables your application to retrieve access_tokens for Pages and Applications that the user administrates. The access tokens can be queried by calling //accounts via the Graph API. This permission is only compatible with the Graph API, not the deprecated REST API.
See here for generating long-lived Page access tokens that do not expire after 60 days.
Once you get this permission, you can then make a wall post using page access token
How can I ask for permissions using new PHP SDK? I don't want to use the graph api and parse the url all the time. When the application is opened it should automatically ask for permissions if the user hasn't granted one already.
Here's how i'm doing it with the latest PHP SDK (3.0.1)
// init new facebook class instance with app info (taken from the DB)
$facebook = new Facebook(array(
'appId' => 'YOUR APP ID',
'secret' => 'YOUR APP SECRET'
));
// get user UID
$fb_user_id = $facebook->getUser();
// get the url where to redirect the user
$location = "". $facebook->getLoginUrl(array('scope' => 'publish_stream, email'));
// check if we have valid user
if ($fb_user_id) {
try {
// Proceed knowing you have a logged in user who's authenticated.
$fb_user_profile = $facebook->api('/me');
} catch (FacebookApiException $e) {
$fb_user_id = NULL;
// seems we don't have enough permissions
// we use javascript to redirect user instead of header() due to Facebook bug
print '<script language="javascript" type="text/javascript"> top.location.href="'. $location .'"; </script>';
// kill the code so nothing else will happen before user gives us permissions
die();
}
} else {
// seems our user hasn't logged in, redirect him to a FB login page
print '<script language="javascript" type="text/javascript"> top.location.href="'. $location .'"; </script>';
// kill the code so nothing else will happen before user gives us permissions
die();
}
// at this point we have an logged in user who has given permissions to our APP
// basic user info can be fetched easily
print "Welcome to my app". $fb_user_profile['name'];
Session Based Login with scope and Logout with access_token for PHP-SDK 3.2.0.
<?php
require './src/facebook.php';
$facebook = new Facebook(array(
'appId' => '135669679827333',
'secret' => 'xxxxxxxxxxxxxxxxxxxxxx',
));
$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) {
$user = null;
}
}
if ($user) {
$params = array(access_token => ''.$access_token.'');
$logoutUrl = $facebook->getLogoutUrl($params);
} else {
$params = array(
scope => 'read_stream,publish_stream,publish_actions,read_friendlists',
//redirect_uri => $url
);
$loginUrl = $facebook->getLoginUrl($params);
};
$access_token = $_SESSION['fb_135669679827333_access_token'];
?>
.
<?php if($_SESSION['fb_135669679827333_access_token']): ?>
Login & Connect
<?php else: ?>
Login & Connect
<?php endif ?>
I have developed a Facebook application that runs inside an iframe in the Facebook canvas. For it to work properly I request extended permissions from the user. If the user hasn't authorized the application I send him/her to a login page with the getLoginUrl() method in the PHP SDK.
It works, but it's not pretty. The method sends the user to a landing page before the authentication page. It looks like this:
When I click "Go to Facebook.com" I see the actual page for permission requests (I also get right to the permissions page if I print the url, copy it and enter it into a new browser window). How do I make Facebook skip this step when I do the redirect from an Iframe?
My code looks like this (using CodeIgniter and Facebook PHP SDK):
$this->facebook = new Facebook(array(
'appId' => '{MY_APP_ID}',
'secret' => '{MY_SECRET}',
'cookie' => TRUE,
'domain' => $_SERVER['SERVER_NAME']
));
$this->facebook->getSession();
try {
$this->me = $this->facebook->api('/me');
}
catch (FacebookApiException $e) {
$this->me = NULL;
}
if ( is_null($this->me) ) {
redirect($this->facebook->getLoginUrl(array(
'req_perms' => 'offline_access,read_stream,publish_stream,user_photos,user_videos,read_friendlists',
'next' => $this->config->item('base_url').'fblogin.php?redirect_uri='.$this->uri->uri_string()
)));
}
I think you need to redirect the parent frame (i.e. _top) rather than the iFrame itself?
The way I do it is set up an INDEX.PHP file with the following
//if user is logged in and session is valid.
if ($fbme){
//fql query example using legacy method call and passing
parameter
try{
$fql = "select name, hometown_location, sex,
pic_square from user where uid=" .
$uid;
$param = array(
'method' => 'fql.query',
'query' => $fql,
'callback' => 'http://apps.facebook.com/yoursite/'
);
$fqlResult = $facebook->api($param);
}
catch(Exception $o){
d($o);
}
}
Then point your canvas url to http://yoursite.com/INDEX.php
The callback url in the above code which will be in INDEX.PHP sets where to look after permissions are granted.
FBMain.php looks like this
//set application urls here
$fbconfig['http://www.yoursite.com/iframeapp/YOURMAINPAGE.php/']
= "http://www.tyoursite.com/YOURMAINPAGE.php/";
$fbconfig['http://apps.facebook.com/CANVASBASEURL']
= "http://apps.facebook.com/CANVASBASEURL";
$uid = null; //facebook user id
try{
include_once "facebook.php";
}
catch(Exception $o){
echo '<pre>';
print_r($o);
echo '</pre>';
}
// Create our Application instance.
$facebook = new Facebook(array(
'appId' => $fbconfig['APPID'],
'secret' => $fbconfig['SECRET'],
'cookie' => true,
));
//Facebook Authentication part
$session = $facebook->getSession();
$loginUrl = $facebook->getLoginUrl(
array(
'canvas' => 1,
'fbconnect' => 0,
'req_perms'=>'email,publish_stream,status_update,user_birthday,user_location'
)
);
$fbme = null;
if (!$session) {
echo "<script type='text/javascript'>top.location.href
= '$loginUrl';";
exit;
}
else {
try {
$uid = $facebook->getUser();
$fbme = $facebook->api('/me');
} catch (FacebookApiException $e) {
echo "<script type='text/javascript'>top.location.href
= '$loginUrl';";
exit;
}
}
function d($d){
echo '<pre>';
print_r($d);
echo '</pre>';
} ?>
Hope its a little clearer. It took me a while to figure it out, but I got there, thought I would help.