$facebook->getUser() always returns 0 [duplicate] - facebook

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Why is Facebook PHP SDK getUser always returning 0?
Am using the following code to authenticate Facebook uses and redirecting them to login page if not logged in or require permission. Problem is getUser() always returns 0 causing the code to get stuck in a redirecting loop. Any ideas?
include_once("facebook.php");
$app_id = 'xxxxxxxxxxxx';
$app_secret = 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxx';
// initialize facebook
$facebook = new Facebook(array(
'appId' => $app_id,
'secret' => $app_secret,
));
$user = $facebook->getUser();
echo $user;
if ($user) {
try {
$fbme = $facebook->api('/me');
} catch (FacebookApiException $e) {
error_log($e);
$user = null;
}
}
else
{
$loginUrl = $facebook->getLoginUrl(array('scope' => 'email'));
header('Location: '.$loginUrl);
}

After days of searching I found that I just wasn't adding a 'code' key value when using the Facebook API. The system needs it in order to validate
When you use the API function $facebook->getLoginUrl(); it takes you to a login-page that (when you authenticate properly) simply returns you to your own website with a code="x" parameter in the navigation bar. So when instantiating the Facebook Object you simply use a get request to nab this piece of information.
when your page reloads the Facebook API, make sure that one of its key values is
'code' => $_GET['code'],
sorted..
Really angry that I had to figure this out myself.. Look at the getLoginUrl() docs here http://developers.facebook.com/docs/reference/php/facebook-getLoginUrl/ and you'll find that nowhere does it specify what it returns, just that it "authorises" the app, whatever the hell that means.
Also on the main page of the PHP API docs found here http://developers.facebook.com/docs/reference/php/, it states that the minimum number of parameters required are an app secret and an appID. If this is the case, then why does adding the code sort my problem?
If I'm talking nonsense, please respond. I like to know the error of my ways :).

This is not a sdk related problem, SDK (3.1) working well. getUser() and PHP-SDK silently fails if _REQUEST like globals dropping by http server if misconfigured. I was using wrong-configured nginx and after tracing code ~3 hours solved this problem via vhost configuration change.

Related

Facebook Login error - Can't Load URL

I know this has been ask3d before but I have tried several of the posts but still cannot get it to work. I am being forced to use strict mode for url redirects and no matter what I put for the domain nothing works.
<?php
if(!session_id()){
session_start();
}
// Include the autoloader provided in the SDK
require_once __DIR__ . '/src/Facebook/autoload.php';
// Include required libraries
use Facebook\Facebook;
use Facebook\Exceptions\FacebookResponseException;
use Facebook\Exceptions\FacebookSDKException;
/*
* Configuration and setup Facebook SDK
*/
$appId = '********'; //Facebook App ID
$appSecret = '***************'; //Facebook App Secret
$redirectURL = 'https://www.themathouse.com/'; //Callback URL
$fbPermissions = array('email'); //Optional permissions
$fb = new Facebook(array(
'app_id' => $appId,
'app_secret' => $appSecret,
'default_graph_version' => 'v2.2',
));
// Get redirect login helper
$helper = $fb->getRedirectLoginHelper();
// Try to get access token
try {
if(isset($_SESSION['facebook_access_token'])){
$accessToken = $_SESSION['facebook_access_token'];
}else{
$accessToken = $helper->getAccessToken();
}
} catch(FacebookResponseException $e) {
echo 'Graph returned an error: ' . $e->getMessage();
exit;
} catch(FacebookSDKException $e) {
echo 'Facebook SDK returned an error: ' . $e->getMessage();
exit;
}
?>
On the facebook app I have themathouse.com as the app domain and https://www.themathouse.com as the Valid OAuth redirect URIs.
When I try logging in with facebook I get the following error:
Graph returned an error: Can't Load URL: The domain of this URL isn't included in the app's domains. To be able to load this URL, add all domains and subdomains of your app to the App Domains field in your app settings.
Any help would be greatly appreciated.
Make sure that your Redirect Url matches what is set in your App Settings, under Facebook Login -> Settings -> Valid OAuth redirect URIs
In this case, it seems to be https://www.themathouse.com/
EDIT: Also, as it seems that you are using the PHP SDK, make sure that you are using the currently latest version, 5.6.2, as this one fixed an issue present on 5.6.1 and older that may affect you.
THIS worked for me!! (after fiddling with a bunch of stuff suggested on various forums, to no avail)
I updated the 'FacebookRedirectLoginHelper.php' file:
https://github.com/facebook/php-graph-sdk/blob/5.x/src/Facebook/Helpers/FacebookRedirectLoginHelper.php and voila! Pesky login error fixed :)
(Oh, I also updated code for other recently changed files [within last few months or so] in the Facebook PHP/SDK, so you should also do this as well: https://github.com/facebook/php-graph-sdk). Good luck!
Update with the latest SDK, it will solve your problem.

Retrieving a facebookuserID

for my facebook quiz app I need to collect the facebookID of
each participating user. My app is in an iframe of another App.
The "facebook-files" I put in the third party folder.
In my controller I invoke it like so:
$this->ci->load->file(APPPATH.'/third_party/facebook.php');
// Connect to Facebook API
$this->facebook = new Facebook(array('appId' => $this->config->item('appkey'), 'secret' => $this->config->item('appsecret')));
It seems not possible to get the facebookID from a participant.
If try the this:
try {
$user_id = $this->facebook->api('/me');
//$signed_request = $_REQUEST["signed_request"];
//$user_id = $signed_request['user_id'];
//print_r( $user_id) ;
} catch ( FacebookApiException $e ) {
error_log( $e );
$user_id = 100;
}
the $user_id is 100.
Can you get me start how to retrieve the right facebookid ?
What would be the right way? Authentication process ?
Thanks in advance!
Ansgar
to get the Facebook ID with PHP you need to use the method $fb->getUser() : https://developers.facebook.com/docs/reference/php/facebook-getUser/
Although, for this to work, the user need to connect into your app. This can be achieve in multiple way, but if you only do it with PHP you can use the getLoginUrl method to get the URL where the user will be asked to accept to login with your app (https://developers.facebook.com/docs/reference/php/facebook-getLoginUrl/). This is also achievable with JS SDK (which is my personal preferred way)
All documentation on Login Dialog can be found here: https://developers.facebook.com/docs/opengraph/authentication/
The key concept here is that the user is anonymous until you ask them to connect in your app.

getUser() only returning 0 now; was working yesterday?

I have an app where the Facebook Login was working great as of yesterday. I switched to AWS EC2 to get a bigger server for some capacity planning for today.
Unfortunately, the Facebook Login is no longer working. In particular, after getting the access_token from the JavaScript authorization, the getUser() call returns only 0. The code is below.
Since the server is the only thing that has changed (and IP) is there some configuration related to my server that I'm missing/unaware of?
if(isset($_GET["access_token"])) {
$access_token = $_GET["access_token"];
$facebook = new Facebook(array(
'appId' => FACEBOOK_APP_ID,
'secret' => FACEBOOK_SECRET,
));
$facebook->setAccessToken($access_token);
$user = $facebook->getUser();
if($user) {
try {
$user_profile = $facebook->api('/me');
$user_name = $user_profile["name"];
$user_email = $user_profile["email"];
$fb_uid = $user_profile["id"];
$fb_access_token = $access_token;
} catch (FacebookApiException $e) {
$status_header = 'HTTP/1.1 500 Internal Server Error';
header($status_header);
header('Content-type: application/json');
echo json_encode(array('message' => 'Facebook Exception'));
exit;
}
} else {
$status_header = 'HTTP/1.1 500 Internal Server Error';
header($status_header);
header('Content-type: application/json');
echo json_encode(array('message' => 'Facebook user does not exist', 'access_token' => $access_token, 'user' => $user, 'fb' => $facebook));
exit;
}
}
Two possible ideas:
The Curl library you are using on that system is not working properly. Try doing the call from the shell using some of the examples that are scattered around FB's site.
I once moved an app to a different server and had FB API calls inexplicably not work -- on the exact same code, after an rsync -- despite updating the new server IPs to be in our whitelist. I surmise that either the Facebook Developer App whitelist updating feature is broken or that IP was banned permanently from all of Facebook's APIs. If all else fails, try moving to a different EC2 instance in a different availability zone to see if it works there.
p.s. At the time, I emailed Facebook's "contact me if you have any problems" developer rep to check if the IP updating might be broken, but of course I got no response from the helpful team over there.
Verify the FACEBOOK_APP_ID and FACEBOOK_SECRET values are the correct ones and that the url you are accessing the site from is set as the site url and site domain on the application settings page.
Otherwise verify the PHP SDK versions are the same and the PHP versions are the same. This may help narrow down the problem.

Facebook authentication with codeigniter (active access token must...)

I sign in with FB fine if I directly create a page at domain.com/someurl.php
The moment I copy the same code (inc html) into a view file with codeigniter and go to domain.com/login/someurl.html it doesn't work. By it doesn't work I mean, I get an exception if i try to access /me after signing into facebook.
The message reads "An active access token must be used to query information about the current user"...
In my controller i have my index function and all it does is load the view with the facebook login code.
I thought I may be doing something wrong but I copied the sample.php from the facebook sdk and paste it into the view file and the same thing happens. If i copy the sample code into the file at someurl.php it then works as expected...given the situation I suspected it may be something to do with codeigniter and possibly some config option I have that causes that behaviour...
I've been looking up the error for a while now and have found a few resources:
http://benbiddington.wordpress.com/2010/04/23/facebook-graph-api-getting-access-tokens/
Facebook access_token invalid?
Facebook authentication issue
https://github.com/facebook/php-sdk/wiki/AccessToken
but none of the suggested fixes have worked.
Right from the sample:
// Create our Application instance (replace this with your appId and secret).
$facebook = new Facebook(array(
'appId' => 'APPID',
'secret' => 'SHHHH',
));
// 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;
}
}
// Login or logout url will be needed depending on current user state.
if ($user) {
$logoutUrl = $facebook->getLogoutUrl();
} else {
$loginUrl = $facebook->getLoginUrl();
}
It doesn't work in the view and I'm stumped as to why or why none of the fixes or "precautions" such as not using type or ensuring the redirect url is the same etc, work.
EDIT:
I'm trying to avoid using domain.com/somefile.php and instead use a view file like every other page...
The issue has cropped up in other places such as the Elliot Houghin fb/CI library.
I found a solution documented in a tutorial here:
http://www.dannyherran.com/2011/02/facebook-php-sdk-and-codeigniter-for-basic-user-authentication/
The problem could be cause from one of several issues pointed out on a an issue on Elliot's github repo. I tried many of the suggested "fixes" but the one that seemed to help was not using the facebook instance as a class property. After trying the tutorial at the above link I tried a fresh install of CI again and created a facebook instance inside the function, the API calls with the FB SDK then worked and had no problems so far.
Bug report with suggested fixes #
https://github.com/elliothaughin/codeigniter-facebook/issues/5

Facebook API to retrieve wall feed

I've never done any facebook development and am working on a project which I only require to pull out wall stream from a certain user. Is there such an API I could use for this purpose?
Facebook exposes a generic API. You can write your own methods of accessing it, or you can use Facebook's libraries (if your preferred language is available). Check out the following link to get started:
Getting started
Well, if you're happy with JSON, just using the graph API is a good start.
e.g. https://graph.facebook.com/starbucks/feed
Not too hard to pull that down with Python and put the data in a table...
Though this is an old post, still i am putting in my reply. This might be helpful.
I am using php sdk and here is code for getting the users wall posts (includes posts by other users as well)
$facebook = new Facebook(array(
'appId' => '101874630007036',
'secret' => '2090c8d645ae93e7cacee2217cd3dc0c',
));
$user = $facebook->getUser();
// Login or logout url will be needed depending on current user state.
if ($user)
{
$logoutUrl = $facebook->getLogoutUrl();
}
else
{
$params = array('scope' => 'read_stream');
$loginUrl = $facebook->getLoginUrl($params);
}
if ($user)
{
$comments = $facebook->api('/me/home');
}
here $comments contains the wall post json data.