Facebook Cancelled Permissions Redirect - php

So I'm having a bit of trouble when a user declines an app's permissions.
When the user accepts the permissions, they are redirected to the app just fine. When the user clicks Cancel/Decline, it should redirect them to the main Page, but instead it loops and asks them to accept the permissions again.
I am using the PHP API and the following is my code:
// Development
$app_id = 'XXXXXXXX';
$app_secret = 'YYYYYYYYYY';
$app_url = 'LINK_TO_FACEBOOK_PAGE_TAB';
$cancelUrl = 'LINK_TO_FACEBOOK_PAGE';
$GRAPH_URL = "https://graph.facebook.com/";
$scope = 'publish_actions';
// Init the Facebook SDK
$facebook = new Facebook(array(
'appId' => $app_id,
'secret' => $app_secret,
));
// Get the current user
$user = $facebook->getUser();
// Get the users token
$token = $facebook->getAccesstoken();
// If the user has not installed the app, redirect them to the Login Dialog
if(isset($_REQUEST['error']))
{
if(isset($_REQUEST['error_reason']) && $_REQUEST['error_reason']=='user_denied')
{
echo "<script>top.location.href='{$cancelUrl}'</script>";
}
}
if (!$user) {
$loginUrl = $facebook->getLoginUrl(array(
'scope' => $scope,
'redirect_uri' => $app_url,
'display' => 'page',
));
print('<script> top.location.href=\'' . $loginUrl . '\'</script>');
}
Any assistance with this would be greatly appreciated.

You're doing this here:
if (!$user) {
If you don't want to redirect users who've already rejected the request, check for the presence of the error parameters Facebook uses to tell you the user has rejected the request, and don't send them back to the auth dialog if you see them.
At a very basic level, this should work and be easy to test provided your redirect_uri parameter in the login dialog brings the user back to the same page you're doing the user checking on:
if (!$user) {
if ($_REQUEST['error_reason'] == 'user_denied') {
//explain why you need them to log in
} else {
$loginUrl = $facebook->getLoginUrl(array( [...]
}
}

Related

How to fix "(#200) The user hasn't authorized the application to perform this action" error while posting on facebook wal

I am getting "(#200) The user hasn't authorized the application to perform this action" error when posting message on user's facebook wall. I am using facebook graph API. I have also set the "publish_actions" permission in the scope, but didn't working. My code is
require 'facebook/facebook.php';
$facebook = new Facebook(array(
'appId' => APP_ID,
'secret' => APP_SECRET,
));
$user = $facebook->getUser();
if ($user) {
$accessToken = $facebook->getAccessToken();
try {
//create message with token gained before
$post = array(
'access_token' => $accessToken,
'message' => 'Test message'
);
$res = $facebook->api('/me/feed', 'POST', $post);
} catch (FacebookApiException $e) {
error_log($e);
$user = null;
}
} else {
# There's no active session, let's generate one
$login_url = $facebook->getLoginUrl(array(
'scope' => 'publish_actions'
));
header("Location: " . $login_url);
}
Can you please suggest me what i am missing in the code or in the app?
Since you mentioned that it does work for Admins, but not for anyone else, it´s very clear what the problem is: You need to go through Login Review with publish_actions - else, that permission will only work for users with a role in the App.
All the information you need about Login Review is in the docs: https://developers.facebook.com/docs/facebook-login/review

Facebook App canvas Page not loading

I keep getting this error when I try to use my app I created for Facebook. When I go the the url for the app it take me to the login page, but when I log in I get a pop up box with the error.
App Not Setup: The developers of this app have not set up this app
properly for Facebook Login.
Every time I click ok it just reloads the popup again.
I have already changes the satatus to Live under status and review in my dashboard.
When I log into my account on facebook, it works fine, but I suppose this is because I am set as an admin for the app on the dashboard.
But other users get the problem above.
The code used:
require_once('facebook-php-sdk/src/facebook.php');
$facebook= new Facebook(array(
'appId' => $this->config->item('app_id'),
'secret' => $this->config->item('app_secret'),
'allowSignedRequest' => true,
));
$_REQUEST += $_GET;
$user = $facebook->getUser();
if ($user) {
try {
$user_profile = $facebook->api('/me?fields=picture.width(100).height(100),first_name,last_name,username,email');
} catch (FacebookApiException $e) {
$user = null;
}
} else {
$login_url = $facebook->getLoginUrl(array(
'scope' => 'email'
));
redirect($login_url, 'refresh');
}
This code is in my controller of my codeigniter application which I built the app.
How do I fix this?
UPDATE:
After I added the app as a canvas app this error seemed to go away, however there is still a problem.
I added the Facebook app platform and entered the canvas url, secure canvas url etc.
When I go to the app at the canvas page https://apps.facebook.com/MyApp/ - it work fine as I am a app administrator I guess.
However when an external user goes to the canvas page it just remain blank, but if a user goes to the canvas url http://apps.mydomain.com/MyAPP the app asks for their permissions and works fine as a website.
It just remains blank to users on the canvas page. Why doesn't the canvas page ask for permission?
Help Please.
EDIT:
require_once('facebook-php-sdk/src/facebook.php');
$facebook= new Facebook(array(
'appId' => $this->config->item('app_id'),
'secret' => $this->config->item('app_secret'),
'allowSignedRequest' => true,
));
$_REQUEST += $_GET;
$user = $facebook->getUser();
if ($user) {
try {
$user_profile = $facebook->api('/me?fields=picture.width(100).height(100),first_name,last_name,username,email');
} catch (FacebookApiException $e) {
$user = null;
}
} else {
$login_url = $facebook->getLoginUrl(array(
'scope' => 'email'
));
require_once('facebook-php-sdk/src/facebook.php');
$facebook= new Facebook(array(
'appId' => $this->config->item('app_id'),
'secret' => $this->config->item('app_secret'),
'allowSignedRequest' => true,
));
$_REQUEST += $_GET;
$user = $facebook->getUser();
if ($user) {
try {
$user_profile = $facebook->api('/me?fields=picture.width(100).height(100),first_name,last_name,username,email');
} catch (FacebookApiException $e) {
$user = null;
}
} else {
$login_url = $facebook->getLoginUrl(array(
'scope' => 'email'
));
echo("<script> top.location.href='" . $login_url . "'</script>");
}
Why doesn't the canvas page ask for permission?
Because you are redirecting inside of the iframe, but the FB login dialog does not want to be displayed in (i(frames) – for the obvious reason, that that would lead to a lot of phishing, since users are supposed to see that the page they are entering their login credentials too is actually the real FB site.
So you have to redirect within the top window instance, via JavaScript:
top.location.href = '…';

Login with facebook suddenly stopped working

Suddenly login with facebook in my web application stopped working.
The following is code of my login page for website. i am using facebook php sdk which was working fine till 5 hours back now it stopped.
I am confused and want to know what the hell happen to it as i am not able to solve it since last 5 hours. I have removed my php code connecting to database and query code to make it look simple.
I take only two scopes that is email and publish_stream
output of below code is hello your fb user id is
<?php
require_once 'include/data.php';
//check to see if they're logged in
if(isset($_SESSION['logged_in'])) {
header("Location: index.php");
}
$site_url = "http://example.com/facebook.php";
require_once ('phpsdk/src/facebook.php');
// Create our application instance
$facebook = new Facebook(array(
'appId' => 'xxxxxxxxxxxxxxxx',
'secret' => 'xxxxxxxxxxxxxxxxxxxxxxxxxxx',
'allowSignedRequest' => false
));
// Get User ID
$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){
// Get logout URL
$logoutUrl = $facebook->getLogoutUrl(array(
'redirect_uri' => 'http://example.com/logout.php',
));
}else{
// Get login URL
$loginUrl = $facebook->getLoginUrl(array(
'scope' => 'email, publish_stream',
'redirect_uri' => $site_url,
));
}
// checking
if(!$user) {
//echo "<a href='$loginUrl' >Login</a>";
header("Location:$loginUrl");
} else {
// echo "<a href='$logoutUrl' >Logout</a><br />";
$f_name = mysqli_real_escape_string($GLOBALS["___mysqli_ston"], $user_info['first_name']);
$l_name = mysqli_real_escape_string($GLOBALS["___mysqli_ston"], $user_info['last_name']);
$fb_email = $user_info['email'];
$fb_uid = $user_info['id'];
echo "hello your fb user id is $fb_uid"; // just sample to check
}
?>
The lifetime of the FB token is valid for just 2 hours. From the FB Docs...
When retrieving a Facebook access token, an expiration time associated
with the access token is also typically returned. If this expiration
time is exceeded, your application will need to obtain a new access
token (which will also have a new expiration time associated with it).
However you can exchange the token and get a new one that has an extended validity say 60 days.. Something like this..
$this->getUrl('graph', '/oauth/access_token'), array(
'client_id' => $this->getAppId(),
'client_secret' => $this->getAppSecret(),
'grant_type'=>'fb_exchange_token',
'fb_exchange_token'=>$this->getAccessToken()
)
More information regarding this can be found here

Same facebook problems ... OAuthException: An active access token must be used to query information about the current user

So this is working fine... But when I refresh the page twice(or click on two pages who include this script fast) it gives this error
OAuthException: An active access token must be used to query information about the current user.
Any ideas?
<?php
$app_id = '***************';
$app_secret = '**************';
$app_namespace = '****************';
$app_url = 'http://apps.facebook.com/' . $app_namespace . '/';
$scope = 'email,publish_actions';
// Init the Facebook SDK
$facebook = new Facebook(array(
'appId' => $app_id,
'secret' => $app_secret,
));
// Get the current user
$user = $facebook->getUser();
// If the user has not installed the app, redirect them to the Login Dialog
if (!$user) {
$loginUrl = $facebook->getLoginUrl(array(
'scope' => $scope,
'redirect_uri' => $app_url,
));
print('<script> top.location.href=\'' . $loginUrl . '\'</script>');
}
if ($user) {
try {
// Proceed knowing you have a logged in user who's authenticated.
$user_profile = $facebook->api('/me', 'POST');
} catch (FacebookApiException $e) {
error_log($e);
$user = null;
}
}
//<img src="https://graph.facebook.com/?php echo $user; ?/picture">
//?php print_r($user_profile); ?
?>
I personally find it easier to manage the access_token myself. Facebook's Graph API secures protected endpoints by requiring that an access_token be passed in. The PHP SDK abstracts this away, but I have never been comfortable with Facebook handling the information because sometimes it just doesn't work. This isn't to say that the library is bad, but only that I haven't been using it correctly. Keep this caveat in mind.
It looks like you're working with a Facebook Canvas App. When the user successfully authenticates for the first time, Facebook will send an access_token in $_GET. At this point, you should save this to your database, since that access token is good for 3 months or so.
At the point, from then on, you can pass in the access_token in the call parameters:
try {
$user_profile = $facebook->api('/me', 'POST', array(
"access_token" => '' // access token goes here
));
} catch (FacebookApiException $e) {
// error handling
}
Given that Facebook is returning the error that you need an access token in order to call the /me resource, it looks like $facebook->getUser(); is returning something. You may want to double-check what it is.
While I'm here, you're using this logic:
if (!conditional) {
// do something
}
if (conditional) {
// do something else
}
Confusing. Use else:
if (conditional) {
// do something
} else {
// do something else
}

facebook php api allows login, logging out and logging back gives me An active access token must be used to query information

After authenticating a user and posting to their wall, it gives the user a choice to logout or continue back to the homepage logged in. If they logout and try to log back in, I get this error.
Fatal error: Uncaught OAuthException: An active access token must be used to query
information about the current user. thrown in ...
If they stay logged in they are fine.
After logging out the script using FB.logout from the jdk it is setting the $_SESSION['active'][$access_token] to null, so when I come to connect page again from the facebook login, I get a above for-mentioned error. However the script is not clearing out the userdata
$user = $facebook->getUser(); returns the previous userID, which I assume is part of my problem.
Here is the code
<?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' => '162628977190080',
'secret' => '**MADE PRIVATE**',
'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', 'email');
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,email',
'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: ../facebook_result.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' => 'read_stream,email',
'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();
}
?>
Solved it by getting rid of the a lot of the php and using the javascript sdk, took less than three hours to rewrite to do what I wanted.

Categories