PHP loop issues with facebook app auth - php

I am using the latest PHP-SDK(3.11) and i have issues when users come on my app for the first time. The application make infinite loops.
When the user have to give permissions to the application, he is redirected to :
https://www.facebook.com/connect/uiserver.php?app_id=**myappId**&method=permissions.request&display=page&next=http%3A%2F%2Fapps.facebook.com%2F**myApp**%2F&response_type=code&state=**theSate**&canvas=1&perms=user_birthday%2Cuser_location%2Cuser_work_history%2Cuser_about_me%2Cuser_hometown
and when he accept i have the following link returned :
http://apps.facebook.com/**myApp**/?error_reason=user_denied&error=access_denied&error_description=***The+user+denied+your+request.***&state=**theSate**#_
i don't understand why the access is denied when the user click on "allow".
if ($this->fbUser) {
.... Do Somthing
} else {
$this->loginUrl = $this->fb->facebook->getLoginUrl(array(
'scope' => implode(',', sfConfig::get('app_facebook_perms')
), 'next' => 'http://apps.facebook.com'. sfConfig::get('app_facebook_app_url')));
$this->logMessage($this->loginUrl, 'info');
sfConfig::set('sf_escaping_strategy', false);
}
<script type='text/javascript'>
top.location.href = "echo $this->loginUrl ";
</script>

Try something like this, since you need to store the access token, one way or another. Hard to know what you are doing (or not doing) from that snippet.
<?php
# We require the library
require("facebook.php");
# Creating the facebook object
$facebook = new Facebook(array(
'appId' => 'APP_ID_HERE',
'secret' => 'APP_SECRET_HERE',
'cookie' => true
));
# Let's see if we have an active session
$session = $facebook->getUser();
if(empty($session)) {
# There's no active session, let's generate one
$url = $facebook->getLoginUrl(array(
"response_type"=>"token", //Can also be "code" if you need to
"scope" => 'email,user_birthday,status_update,publish_stream,user_photos,user_videos' ,
"redirect_uri"=> "http://test.com" //Your app callback url
));
header("Location: $url");
exit;
}
// user is logged in

Related

facebook->getUser() returning 0

Whenever I try to login a prompt opens asking for the basic permissions, after that its being redirected to my redirect_uri with an URL
=">http://localhost/demo/?code=AQDwzia3Wx1BktixF59jVHbm0ViGVJm8Xhb2tNZDyYreZh0KoSJhrSsJ8Aa2KX3gocwR0XNQjQz7ZlBh26_nBi-3iOMByhVO2cxwJ8maC4IHxBacfqXjzqIyBaZQbWKUUxPI6VBrqBgFXQasj7PEtmug7lt93dK4fmMC2A4i2dUYU-gSvzn0f0ZdB3eT_aSvgR1KoLCmQgLh3xix4H05QR6LCP9nLtQC4l9rMJW83kS0PNmWq0COZYvGfuX1R7519Fn3iXRB9F0MTsK1KQ_ulpK84PUCkuMu8et88Lln0ZwuzaPo0oERelkPWYnrrTKa-5w&state=ed66ea618d8076d9e72c15d9a65a6312#=
Even though facebook->getUser() returns 0
Here is my code
<?php
require_once('php-sdk/facebook.php');
$facebook = new Facebook (array(
'appId' => '1234',
'secret' => '12313',
'cookie' => true
));
?>
<html>
<head> <title> Warming Up with FB API </title> </head>
<body> <h1> Hello World </h1> </body>
</html>
<?php
$loginUrl = $facebook->getLoginUrl(array (
'display' => 'popup',
'redirect_uri' => 'http://localhost/demo'
));
$user = $facebook->getUser();
//echo $user. '</br>';
if ($user) {
echo '<em>User Id: </em> '.$user;
} else {
$loginUrl = $facebook->getLoginUrl(array (
'display' => 'popup',
'redirect_uri' => 'http://localhost/demo'
));
echo 'Login Here ';
}
?>
I know its a very trivial question but I am kinda stuck at this and unable to proceed further. Kindly suggest what to do.
*UPDATE*
Leaving the App Domain empty solved my problem.
if someone is still banging their head over this here is what is wrong now. I was hired to fix this mess!
Check App domain in fb panel , must match with the domain where your app is.
edit base_facebook.php find:
public function getAccessToken() {
if ($this->accessToken !== null) {
// we've done this already and cached it. Just return.
return $this->accessToken;
}
// first establish access token to be the application
// access token, in case we navigate to the /oauth/access_token
// endpoint, where SOME access token is required.
$getApplicationAccessToken = $this->getApplicationAccessToken();
$this->setAccessToken($getApplicationAccessToken);
$user_access_token = $this->getUserAccessToken();
if ($user_access_token) {
$this->setAccessToken($user_access_token);
}
return $this->accessToken;
}
to::
public function getAccessToken() {
if ($this->accessToken !== null) {
// we've done this already and cached it. Just return.
return $this->accessToken;
}
// first establish access token to be the application
// access token, in case we navigate to the /oauth/access_token
// endpoint, where SOME access token is required.
$getApplicationAccessToken = $this->getApplicationAccessToken();
$this->setAccessToken($getApplicationAccessToken);
$user_access_token = $this->getUserAccessToken();
if ($user_access_token) {
//$this->setAccessToken($user_access_token);
$this->accessToken = $user_access_token; //edit; msolution
}
return $this->accessToken;
}
Next find the function: getAccessTokenFromCode()
find the line:
parse_str($access_token_response, $response_params);
replace it with:
//parse_str($access_token_response, $response_params); //edit:: msolution;;
$response_params = json_decode($access_token_response, true );
commenting the original and adding json_decode
thats it!
If User is logged in and still getting $user = 0
I faced this issue on different occasions but SDK issue is not happening to everyone. So I'm not sure what goes wrong here. But I dig in to it little bit and found solution as mentioned below.
SOLUTION : This worked for me after trying for many solutions for this issue.
In base_facebook.php file, find the makeRequest() method and check for following Line.
$opts = self::$CURL_OPTS;
Immediately following it, add this line
$opts[CURLOPT_SSL_VERIFYPEER] = false;
More details can be found here - http://net.tutsplus.com/tutorials/php/how-to-authenticate-your-users-with-facebook-connect/
Change this
$loginUrl = $facebook->getLoginUrl(array (
'display' => 'popup',
'redirect_uri' => 'http://localhost/demo'
));
to
$loginUrl = $facebook->getLoginUrl(array (
'display' => 'popup',
'redirect_uri' => 'http://localhost/demo/index.php'
));
And see if this works !!
After several hours, the solution for me was (Let's say my site is http://www.site123.com):
Settings # https://developers.facebook.com
App Domain: site123.com (even blank it will work though)
Site URL: http://site123.com IMPORTANT : NOT http://www.site123.com
PHP Code - fb_config.php
//Declarations
$app_id = "{you AppID}";
$app_secret = "{your App Secret}";
$site_url = "http://site123.com/receive_data_from_facebook.php";
//New Facebook
$facebook = new Facebook(array(
'appId' => $app_id,
'secret' => $app_secret,
'cookie' => TRUE, /* Optional */
'oath' => TRUE /* Optional */
));
//Login URL
$loginUrl = $facebook->getLoginUrl(array(
'scope' => 'email,user_birthday',
'redirect_uri' => $site_url,
));
//Get FacebookUserID
$fbuser = $facebook->getUser();
Important Note Also: I had some issues with Firefox $facebook->getUser() was 0 even my code was working on Chrome. But after cleaning Firefox cache, it worked nicely!
Hope it helps.
It might be Worked using
$opts[CURLOPT_SSL_VERIFYPEER] = false; after $opts = self::$CURL_OPTS; on file base_facebook.php.

Facebook API and PHP - getLoginUrl() - never shows dialog and breaks on other FB account

I'm using the Facebook API and it's doing strange things - I have two issues:
When I use getLoginUrl(...) - I never get a popup - I don't click anything and it just redirects.
Using my FB account this code redirects and i see the 'user' and 'token' but when I try the same thing on a workmates FB account it gives the error "An error occurred. Please try again later".
Here's my code for the redirector:
require_once '../../src/facebook.php';
define('FACEBOOK_APP_ID',"xxx");
define('FACEBOOK_SECRET',"xxxxx");
define('REDIRECT_URI',"http://dev.example.com.au/php/work/redirectSimple.php");
$facebook = new Facebook(array(
'appId' => FACEBOOK_APP_ID,
'secret' => FACEBOOK_SECRET,
'cookie' => true
));
$user = $facebook->getUser();
if($user == 0)
{
$login_url = $facebook->getLoginUrl($params = array('redirect_uri' => REDIRECT_URI));
echo ("<script> top.location.href='".$login_url."'</script>");
}
else
{
echo ("<script> window.location.href='".REDIRECT_URI."'</script>");
}
And my redirected code ( redirectSimple.php ):
echo "\n WELCOME!";
require_once '../../src/facebook.php';
$facebook = new Facebook(array(
'appId' => "xxx",
'secret' => "xxxxx",
'fileUpload' => true,
'cookie' => true
));
$user = $facebook->getUser();
echo "\n user = ".$user;
$token = $facebook->getAccessToken();
echo "\n token = ".$token;
I've also tried these things on another machine with the same outcome.
So, Maybe it's an account or App settings issue?
Firstly, don't go looking for a popup with PHP, unless you are using Ajax, as PHP doesn't do popups, being server side. If you want the popup you need to use the JavaScript SDK.
Secondly, after a successful login, you are redirecting to another file. Personally I would use require_once rather than a redirect, as you have already created a Facebook object and if you redirect you will have to recreate it.
If you couple that with "try" and "catch" you can trap any Facebook errors which will give you a clue as to what is going on.
Other than that, as the other person said, check you aren't in sandbox mode in the app settings.
There's no code here to create a 'popup' - getLoginUrl() creates a url you can use as part of the server side flow - you need to redirect to this url.
Your co-worker is most likely not a developer or tester of your app, and so cannot see it (it's probably in sandbox mode)

How can I stop my site from being shown within Facebook?

I'm using Facebook to manage the login for my website. I also use the PHP SDK to call the Graph API to retrieve friend lists, comments, posts etc.
The problem I'm having is that I want the site to be standalone, so that the user follows a link from Facebook and then comes to the site.
It kind of works, but sometimes when the user follows the link, they see my site's index page in the Facebook canvas area. I haven't fully managed to reproduce this, so haven't nailed down the circumstances in which it happens. however, when it happens, if I click 'Back' in the browser, I get taken back to my own site.
It looks like the link takes the user from Facebook to my site, which then calls Facebook to check that the user is logged in, but then it doesn't return to my site for some reason. but as I say, I'm not sure.
Anyway, anyone have any ideas what the problem might be?
My login code is:
// Create new Facebook object
$facebook = new Facebook(array(
'appId' => APP_ID,
'secret' => APP_SECRET,
'cookie' => true, // enable optional cookie support
));
// Create login url, in case user is not logged in or session has expired
$loginUrl = $facebook->getLoginUrl($params = array('canvas' => 0, 'fbconnect' => 0, 'req_perms' => 'publish_stream', 'cancel_url' => 'http://www.pubfish.com'));
// Get current facebook session
$session = $facebook->getSession();
$me = null;
// Session based API call.
if ($session) { // If session exists, make sure it's still valid
try { // Get session to see whether it's valid
// User is logged in and has authorised application already
$uid = $facebook->getUser();
$me = $facebook->api('/me');
} catch (FacebookApiException $e) {
echo "<script type='text/javascript'>top.location.href = '".$loginUrl."';</script>";
error_log($e);
}
}else { // No session - so ask user to log in
$url=$facebook->getLoginUrl(array('canvas' => 1,'fbconnect' => 0));
echo ('<script type="text/javascript">top.location.href=\''.$url.'\';</script>');
}
Have you tried setting 'next', like this: $params = array('canvas' => 0, 'fbconnect' => 0, 'req_perms' => 'publish_stream', 'cancel_url' => 'http://www.pubfish.com', 'next'=>'http://www.pubfish.com')? If all else fails you can use this to break out of the canvas iframe:
<script>
$(document).ready (function () {
if (window != top) top.location.href = location.href;
});
</script>

Facebook App: Where do i put offline_access request?

I need my app to request the offline_access permission (detailed here), but as ever I'm baffled by the Facebook documentations.
It says I need a comma separated list of my permission demands, like 'publish_stream,offline_access' etc
where do i put this list in the interface below????
It's used with the API, as follows
$facebook = new Facebook(array(
'appId' => FACEBOOK_APP_ID,
'secret' => FACEBOOK_SECRET,
'cookie' => false,
));
$facebook_login_url = $facebook->getLoginUrl(array(
'next' => '',
'cancel_url' => '',
'req_perms' => 'email,publish_stream,status_update'
));
Where $facebook_login_url is the URL tha the user needs to follow to grant you access.
Does that help?
You can't do this with that interface. You need to set scope parameter when redirecting user to facebook.
x=y&scope=email,user_about_me,user_birthday,user_photos,publish_stream,offline_access
First define which permissions you will need:
$par['req_perms'] = "friends_about_me,friends_education_history,friends_likes,friends_interests,friends_location,friends_religion_politics,
friends_work_history,publish_stream,friends_activities,friends_events,
friends_hometown,friends_location,user_interests,user_likes,user_events,
user_about_me,user_status,user_work_history,read_requests,read_stream,offline_access,user_religion_politics,email,user_groups";
$loginUrl = $facebook->getLoginUrl($par);
Then, check if the user has already subscribed to app:
$session = $facebook->getSession();
if ( is_null($session) ) {
// no he is not
//send him to permissions page
header( "Location: $loginUrl" );
}
else {
//yes, he is already subscribed, or subscribed just now
echo "<p>everything is ok";
// write your code here
}

is there proper codeigniter library to work with facebook php sdk

I have searched Google for Libraries for Facebook, and have found this one: http://www.haughin.com/code/facebook/,
but it seems a bit outdated.
I wanted something for this one: https://github.com/facebook/php-sdk/
I have written my own wrapper for it meanwhile, but it seems like I'm having some issues with $_REQUEST['...']
You can use Official PHP Facebook SDK in Codeigniter easily. The only problem is Facebook SDK needs $_REGISTER and in Codeigniter you don't have it.(Because of the mod_rewrite)
Here's the little solution:
1- This is for the $_REGISTER problem. Use this before loading Facebook class:
parse_str( $_SERVER['QUERY_STRING'], $_REQUEST );
2- Facebook SDK has 2 files. Put them into one file and save it to your application/helper folder as facebook_helper.php. Then loading and using is such an ease like this:
$this->load->helper( 'facebook' );
$facebook = new Facebook( array( 'appId' => 'XXX', 'secret' => 'xxx' ) );
// ... The rest is not different. You can read Facebook SDK examples
So here's a trick I used to use facebook PHP sdk with my CodeIgniter app. From the SDK code, take Facebook.php and take out the FacebookApiException class, and put it in a new file called FacebookApiException.php. Now, I put facebook.php and FacebookApiException.php into the models folder, and used them as regular models.
Here is the code I used for authenticating users and providing access to an application via Facebook.
function facebook_login(){
# Creating the facebook object
$facebook = new Facebook(array(
'appId' => 'XXXXXXXXXXXXXXXXX',
'secret' => 'XXXXXXXXXXXXXXXXX',
'cookie' => true
));
# Let's see if we have an active session
$session = $facebook->getSession();
if(!empty($session)) {
# Active session, let's try getting the user info
try{
$uid = $facebook->getUser();
$param = array(
'method' => 'users.getinfo',
'uids' => $uid,
'fields' => 'uid, username, name, profile_url, pic_big',
'callback' => ''
);
$user = $facebook->api($param);
} catch (Exception $e){
$url = $facebook->getLoginUrl(array(
'req_perms' => 'user_about_me, email, status_update, publish_stream, user_photos',
'next' => site_url() . 'user/facebook_login',
'cancel' => site_url()
));
redirect($url);
}
if(!empty($user)){
# User info ok?
print_r($user);
// Add user oauth token and info to DB, and then redirect to some controller in your application.
redirect('/'); // redirect to homepage
} else {
# For testing purposes, if there was an error, let's kill the script
die("There was an error.");
}
} else {
# There's no active session, let's generate one
$url = $facebook->getLoginUrl(array(
'req_perms' => 'user_about_me,email,status_update,publish_stream,user_photos',
'next' => site_url() . 'user/facebook_login',
'cancel' => site_url()
));
redirect($url);
}
}
Hope this helps.
You can handle it in clear way by writing a small library by inheriting Facebook SDK class. Please follow my post on http://www.betterhelpworld.com/codeigniter/how-to-use-facebook-php-sdk-v-3-0-0-with-codeigniter to get it working.
There is also Facebook-Ignited.

Categories