Facebook synchronisation with php - get facebook data - facebook

I have problem with authorization of my facebook application. When I run my application normally on my local web server process goes like this:
**Get facebook user->If user is not logged on -> Redirect user on facebook login page**
**Get facebook user->If user is logged on -> Redirect user to authorize my facebook application->everything goes right without problems**
When I host my application on facebook using iframe, second process is not working (user never get show the authorization window), and I get following exception:
Error validating access token: User xxxxxxx has not authorized application xxxxxxx.
I'm using CodeIgniter PHP framework, and this is my PHP code:
$this->load->library('facebook');
$user = null;
$user_profile = null;
$user = $this->facebook->getUser();
if ($user) {
try {
// Proceed knowing you have a logged in user who's authenticated.
$access_token = $this->facebook->getAccessToken();
$user_profile = $this->facebook->api($user);
}
catch (FacebookApiException $e) {
show_error(print_r($e, TRUE), 500);
}
}
else{
$data = array(
'redirect_uri' => 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx','scope'=>'email');
$access_token = $this->facebook->getAccessToken();
redirect($this->facebook->getLoginUrl($data));
}
$data['facebook']=$user_profile;
$this->load->view('templates/header');
$this->load->view('pages/prijavaKlasicnoFacebook', $data);
$this->load->view('templates/footer');
}

You can not load the OAuth dialog in an iframe – security reasons.
You have to load it into the top-most window instance – so no server-side redirect, but a client-side “redirect” using top.location.href = "…";
Get your script to output this JS snippet (including the correct login URL) inside an otherwise empty document.

You should also provide "Read Stream" and "Publish Data" in your scope.

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>";
}

CodeIgniter and Facebook Connect

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

Facebook PHP SDK - OAuthException - OAuth2

How are you supposed to deal with people who signed into Facebook a while ago. Come to your site you should them a continue link (because you detect that they are already logged into Facebook) and then on the page you direct them to you get this error.
Fatal error: Uncaught OAuthException: An active access token must be used to query information about the current user. thrown in /var/www/html/lib/base_facebook.php on line 1039
I don't understand how you are supposed to prevent this? Does this have something to do with the signed info that you give back to Facebook to get an access_token? Seems like this signed info can expire (it has an issued_at date). What is the correct way to handle this in your website's flow?
Are you expected to write code like this:
<?php
$user = $facebook->getUser();
try {
// attempt to do a call just to see if you are going to have this issue
$profile = $facebook->api('/me');
} catch (Exception $e) {
$user = false;
}
if ($user) { ?>
Begin
<?php } else { ?>
<fb:login-button scope="email" size="large">Connect</fb:login-button>
<?php } ?>
Instead of this:
<?php
$user = $facebook->getUser();
if ($user) { ?>
Begin
<?php } else { ?>
<fb:login-button scope="email" size="large">Connect</fb:login-button>
<?php } ?>
Getting the $user back from the Facebook SDK only seems to tell you there is a cookie. And not if that will actually work when you go to do the API calls.
UPDATE:
So my only problem with this method is ... when the user does have a cookie on my site, but the API call fails - I show them the connect button. User clicks the connect button, it quickly appears and disappears. Because it wasn't a true 'auth.login' that just occured, the user will not get sent to my start.php page via JavaScript redirect. How do others handle this? I'm stumped. Please tell me if there are other flaws with how I'm attempting to do this.
Try passing the access token to the API call that verifies that the user has authorized your application. Below is what I do, and it should help to alleviate the OAuthException you're getting.
$user = $facebook->getUser();
if($user) {
$access_token = $facebook->getAccessToken();
$params = array('access_token' => $access_token);
try {
$me = $facebook->api("/me", $params);
} catch(FacebookApiException $e) {
$user = null;
}
}
if($me) {
// proceed with authenticated user with an active access token.
}
Are you expected to write code like this:
Yes, you will have to handle the OAuthException.
But rather than using FBML login button, you can redirect the user to facebook login url for your application. You can get the url by using function getLoginUrl provided by Facebook PHP SDK. See getLoginUrl for more information.
For your email permissions you can use following array:
$params = array( 'scope' => 'email' );
Once successfully logged in, the user will be redirected back to the application page which redirected him to facebook login.

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.

Facebook session in an iframe application breaks ajax calls

I've a facebook application, which conncets to facebook via the PHP-SDK.
$facebook = new Facebook(array(
'appId' => FACEBOOK_APP_ID,
'secret' => FACEBOOK_SECRET_KEY,
));
$user = $facebook->getUser();
if ($user) {
try {
$user_profile = $facebook->api('/me');
} catch (FacebookApiException $e) {
error_log($e);
$user = null;
}
}
Everything is fine, I let the browser open and don't respond to my app. After a while I try to send a form in the app via ajax. It seems that the session is invalid? Facebook will authorize my app again load the ajax url into the browsers address bar and attach the new session param to that url and breaks the app.
Is there anything I could do to pretend facebook to "reload" or pass the ajax/form action to the browser address bar? Before every request is processed I check whether the user is still active or not, that might be the problem?
$user = $facebook->getUser();
if ($user != 0) {
if($this->userProfile == null){
try {
// Proceed knowing you have a logged in user who's authenticated.
$this->userProfile = $facebook->api('/me');
} catch (FacebookApiException $e) {
error_log($e);
$user = null;
}
}
}else{
$this->userProfile = null;
}
if ($this->userProfile != null) {
$filterChain->run();
} else {
$loginUrl = $facebook->getLoginUrl(
array('scope' => 'publish_stream','redirect_uri' => 'REDIRECT_URI'));
}
echo("<script> top.location.href='" . $loginUrl . "'</script>");
Should I use an other approch?
Thanks in advance!
You really shouldn't be processing ajax calls the same way as regular page fetches. Generally if something like an expired session happens within an ajax process you want to send an error code back to the main page and let it handle it at the top level.
I'm guessing that the info you send back from this ajax request gets immediately parsed as HTML? Which means that if you send back a <script>top.location=xxx</script> block, it gets executed and redirects the browser to the new location. Again that's probably not the best way to handle things, but it would still work if the redirect_uri were set appropriately (to the url of the page as a whole). Because the getLoginUrl() is called while within the ajax page, the redirect_uri is set to that url instead, so after the new authorization is completed that's where the browser is sent back to (at the top level now). So while probably not the best overall structure, a quick workaround would be to override the redirect_uri setting when you are within an ajax call, and make it point to the parent page instead of itself.