CodeIgniter and Facebook Connect - facebook

I am trying to integrate my Codeigniter website with the Facebook PHP SDK. What I want to do is let a user share an article from my site on their facebook wall, if they are logged into a facebook account. My library appears to load correctly, but everytime I try to do something, I get some kind of error... primarily with the auth. getUser does not appear to return the correct results. I set up my facebook application and set the config vars for my library, but no luck. It says I am not logged into facebook. When I click on the "login" anchor, the link takes me to the same page, but with the facebook url, and doesn't ask me to login with the app. Here's my code:
function facebook($article_id){
$config = array(
'appId' => '276870792431073',
'secret' => '8d49eee575413fb9a8063d22f65dbf6a'
);
$this->load->library('facebook', $config);
$user = $this->facebook->getUser();
if($user){
try {
$user_profile = $this->facebook->api('/me');
} catch (FacebookApiException $e){
error_log($e);
$user = null;
}
}
if($user){
$article = $this->article->fetch_article($article_id);
$config = array(
'message' => 'I just read an '.anchor('articles/'.url_title($article['title']).'/'.$article_id, 'article').' on '.anchor('', 'TrackTheOutbreak.com').'!',
);
$this->facebook->api('/me/feed', 'post', $config);
} else {
$data['MESSAGE_TITLE'] = 'Authentication Error';
$data['MESSAGE_TEXT'] = 'You must be logged into an existing Facebook account to use this feature. Click '.anchor($this->facebook->getLoginUrl(), 'here').' to login.';
$this->parser->parse('error_body.tpl', $data);
}
}

In order to access a users information and post anything to their wall you first need to get a access token from them. To do that you need to make sure that you have gained their permission through Facebook's FB_login (and then Open Graph). I would double check with this guide and make sure that you have everything set up properly to post to their timeline.
https://developers.facebook.com/docs/reference/javascript/FB.login/
I hope this helps

Related

Redirect to Index page when Facebook PHP SDK Access Token is Expired

I'm working on a site that uses the Facebook PHP SDK. It is working great, and after 2 hours, whenever I try to get onto one of the general pages on the site, I get...
Fatal error: Uncaught OAuthException: An active access token must be used to query information about the current user.
If I go back to the index page, I get a new access token and everything works properly again...for 2 hours.
What code can I put on my webpages to redirect to the index page when the access token has expired?
Thanks for helping this noob.
You must redirect user to page that has authorized code.
If your user not deauthorized app , the Oauth dialog isn't appear.
For more information go to
Access Token & Handling
You can put a try / catch block in your code.
Put each Facebook API call in such block and if an exception occurs you can redirect the user to the right resource by header('Location: <url>');:
try {
# FB API call
}
catch(OAuthException e) {
header('Location: <url>');
}
Have a file that goes like this and include it in your webpages.
$facebook = new Facebook(array(
'appId' => "app id",
'secret' => "app secret",
));
$user = $facebook->getUser();
$loginUrl = $facebook->getLoginUrl();
if ($user) {
try {
$me = $facebook->api('/me');
} catch (FacebookApiException $e) {
error_log($e);
}
}
else {
echo "<script type='text/javascript'>top.location.href = '$loginUrl';</script>";
}

facebook app oauth error (can not be displayed in frame)

I just wanted to create a FB app. I went to developers.facebook.com/apps, set up a new app, created a new folder on my server, copied an old (working) app into the folder, changed the app id, secret, canvas page and canvas url in my configuration file... and it did not work.
It displayed an error: "this content can not be displayed in frame".
I would be grateful if you could help me. Thanks.
I copy here my config file: (I intentionally removed the app id and secret here.)
// Facebook App ID/API Key
$appId = '';
// Facebook App Secret
$secret = '';
// Facebook Canvas Page
$redirect_uri = 'https://apps.facebook.com/appname/';
// Facebook Canvas URL
$canvas_url = 'https://myhost.com/appname/';
// Facebook App Permissions
$scope = 'email, publish_actions';
// Configure Facebook connection
require 'facebook.php';
$facebook = new Facebook(array(
'appId' => $appId,
'secret' => $secret,
'cookie' => true,
));
$user = $facebook->getUser();
$loginUrl = $facebook->getLoginUrl(array(
'redirect_uri' => $redirect_uri,
'scope' => $scope,
));
$logoutUrl = $facebook->getLogoutUrl();
if ($user) {
try {
$user_profile = $facebook->api('/me');
} catch (FacebookApiException $e) {
$user = null;
}
} else {
header("Location: $loginUrl");
}
You should use JavaScript to redirect the user to the login URL using top.location = '{url}', and then use the login redirect url to send them back to your application. Facebook doesn't allow you to use facebook within an iframe, that why you are seeing that error message - pretty self explanatory.
It displays a "this content can not be displayed in frame" errormessage.
And what about this message gives you trouble understanding?
You can't call the auth dialog in an iframe, because it would enable phishing if the user can’t check the sites address.

Facebook Connect works offline, but not online "This webpage has a redirect loop"

Access to my developed website is done using facebook connect.
Everything is OK offline, but not online. I get a navigation error (using Chrome) "This webpage has a redirect loop" :
The webpage at https://www.facebook.com/dialog/oauth?client_id=209633612480053&redirect_uri=http%3A%2F%2Fwww.bluward.com%2Faccess%2Flogin_facebook&state=299262ddf89afbf382452df89c9a2ce8&scope=email%2C+user_birthday%2C+user_about_me%2C+user_location%2C+publish_stream&fbconnect=1#= has resulted in too many redirects. Clearing your cookies for this site or allowing third-party cookies may fix the problem. If not, it is possibly a server configuration issue and not a problem with your computer.
Here is the PHP code (using CodeIgniter framework):
public function login()
{
// Get the FB UID of the currently logged in user
$uid = $fb->getUser();
// If the user has already allowed the application, you'll be able to get his/her FB UID
if($uid) {
try {
$profile = $fb->api(array(
'method' => 'users.getinfo',
'uids' => $uid,
'fields' => 'uid, first_name, last_name, pic_square, pic_big, sex, birthday_date, current_location, email'
));
// Only the first user.
$profile = $profile[0];
} catch (FacebookApiException $e) {
return false;
}
// Do stuff when already logged in.
return $profile;
} else {
// If not, let's redirect to the ALLOW page so we can get access
redirect($this->getLoginUrl(array(
'scope' => 'email, user_birthday, user_about_me, user_location, publish_stream',
'fbconnect' => 1
)));
}
}
And depending on the profile info, I check if the user already exists on database, then log him/her, and if not exists on database, signup him/her.
Update:
When I clear Facebook cookies, the redirect to login page is successful, and I'm able to fill email/password.
Unfortunately, when I click "log in" button, I get the same error message as I displayed above.
It looks like your using and older version? Here is how i would handle issue with php-sdk 3.1.1 "the most current version".
require 'src/facebook.php';
$facebook = new Facebook(array(
'appId' => '135669679827333',
'secret' => 'xxxxxxxxxxxxxxxxxxxxxxxxxxxx'
));
$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) {
error_log($e);
$user = null;
}
}
if ($user) {
$logoutUrl = $facebook->getLogoutUrl();
} else {
$params = array(
scope => 'read_stream,publish_stream,publish_actions,read_friendlists',
//redirect_uri => $url
);
$loginUrl = $facebook->getLoginUrl($params);
echo '<script> top.location.href=\''.$loginUrl.'\'</script>';
};

facebook php-sdk providing same functionality as javascript FB.getLoginStatus

I am using javascript sdk to know if user is login and connected to our web-site' application by using FB.getLoginStatus() function.
I want to know if php-sdk provides me details about the user logged into facebook.
If user is logged in facebook and connected to our application, i have to make them to directly logged into our site.
How can this be done using php sdk.
Thanks in advance.
You can do the following:
$user_details=$fb->api_client->users_getInfo($fb_user, array('last_name','first_name','pic_square'));
And yes they do have a similar thing to the FB.getLoginStatus() :)
$params = array(
'ok_session' => 'https://www.myapp.com/',
'no_user' => 'https://www.myapp.com/no_user',
'no_session' => 'https://www.myapp.com/no_session',
);
$next_url = $facebook->getLoginStatusUrl($params);
Found it here: https://developers.facebook.com/docs/reference/php/facebook-getLoginStatusUrl/
Just check the Example/Usage at the GitHub-Page:
https://github.com/facebook/facebook-php-sdk
according to documentation ( https://github.com/facebook/facebook-php-sdk ), after doing:
require 'facebook-php-sdk/src/facebook.php';
$facebook = new Facebook(array(
'appId' => 'YOUR_APP_ID',
'secret' => 'YOUR_APP_SECRET',
));
// Get User ID
$user = $facebook->getUser();
To check if the user is still logged in on facebook (kind of FB.getLoginStatus) you need to:
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;
}
}
As noted by #DMCS this function should be used:
http://developers.facebook.com/docs/reference/php/facebook-getLoginStatusUrl/
You generate an url: $next_url = $facebook->getLoginStatusUrl();
redirect the user to this url: header('Location: '.$next_url);
the user will be returned by FB with session information (POST) about the login status
the SDK will parse the return $_POST info
use $facebook->getUser(); to get the userid (if logged in)
So far so good. The only problem is, this function (point 4) is broken since the transition to oAuth2.0 by Facebook, see also this bug report:
http://developers.facebook.com/bugs/295348980494364
So please let FB know that you have the same issue by adding a reproduction.
Cheers!

How to avoid my this facebook app api login page?

I got a problem regrading with my apps which is once I go to my apps, it sure will show me a login page instead of allow page?
it always display the login page 1st then only display allow page, I had tried other apps, if I am 1st time user, It sure will appear the allow page only, it did not show me the login page.
my question is how to I avoid my login page direct go to allow page?
here is my login page picture
here is my apps link
https://apps.facebook.com/christmas_testing/
here is my facebook php jdk api coding
<?php
$fbconfig['appid' ] = "XXXXXXXXXXXXX";
$fbconfig['secret'] = "XXXXXXXXXXXXX";
$fbconfig['baseUrl'] = "myserverlink";
$fbconfig['appBaseUrl'] = "http://apps.facebook.com/christmas_testing/";
if (isset($_GET['code'])){
header("Location: " . $fbconfig['appBaseUrl']);
exit;
}
if (isset($_GET['request_ids'])){
//user comes from invitation
//track them if you need
header("Location: " . $fbconfig['appBaseUrl']);
}
$user = null; //facebook user uid
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
$user = $facebook->getUser();
$loginUrl = $facebook->getLoginUrl(
array(
'scope' => 'email,publish_stream,user_birthday,user_location,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>';
}
?>
This is an effect of the new auth dialog features facebook recently rolled out.
There are two "allow/login" screens when using this new dialog :
Regular permissions such as - user_about_me, user_birthday, user_photos.
Extended permissions such as - read_insights, offline_access, publish_actions.
Each will display its own dialog. First the regular permissions will appear and after that the extended permissions will appear (if you have requested extended permissions)... This happens when the user first logs in, and possibly later if you want decide to add additional permissions to your app.
Taken from the Open Graph Beta › Auth Dialog
The updated Auth Dialog will display a set of user and friends permissions on the first dialog, and other extended permissions (if any) on a second dialog screen.
You can disable this feature and go back to the older auth dialog by changing the setting inside your app. Goto the advanced tab in the settings of your app and uncheck the Enhanced Auth Dialog check-box.
On the scope parameter, add 'offline_access' permission. With this,the user grant permission to the application even if the user is offline. The access_token that you will get is non-expiry.