Open Auth Dialog in Facebook php SDK - php

I am integration Facebook connect in my website using php SDK.. Everything is working fine except that I want that instead of redirecting to facebook for authentication, I want to open OAuth Dialog.. Currently Im using following url for authentication,.. It redirects to facebook but doesn't open OAuth Dailog..
https://www.facebook.com/dialog/oauth?client_id=XXXXXXXXXXX&redirect_uri=http%3A%2F%2Fwww.setsail2nz.com.au%2Fmicrosite%2Ffbalbums.php%3Fpid%3D1&state=ad89eddd7f71e7337785f604710c97e8&scope=user_photos%2Cpublish_stream%2Cmanage_friendlists%2Cemail&display=popup
Any ideas?
EDIT:
I know how to do it with Facebook JS SDK.. But is there a way to do it with php?
Edit 2: Okay now im using JS SDK but still its not opening the dialog.. Here is my code
<div id="fb-root"></div>
<script>
window.fbAsyncInit = function() {
FB.init({
appId : 'XXXXXXXXXX', // App ID
status : true, // check login status
cookie : true, // enable cookies to allow the server to access the session
xfbml : true, // parse XFBML
oauth : true // enables OAuth 2.0
});
};
// Load the SDK Asynchronously
(function(d){
var js, id = 'facebook-jssdk', ref = d.getElementsByTagName('script')[0];
if (d.getElementById(id)) {return;}
js = d.createElement('script'); js.id = id; js.async = true;
js.src = "//connect.facebook.net/en_US/all.js";
ref.parentNode.insertBefore(js, ref);
}(document));
function fblogin()
{
FB.login(function(response)
{
alert(response);
},{perms: "user_photos,publish_stream,manage_friendlists,email"});
}
</script>

Use Javascript SDK
https://developers.facebook.com/docs/reference/javascript/
And FB.login, passing your required permissions

To answer your question about detecting the dialog response with PHP SDK:
The problem is that getloginURL only takes one URL parameter that it uses on success or error. I needed to detect if the user clicked OK or Cancel on the permissions dialog, so I could either redirect to a pre-permissions dialog page, or show the correct logged-in content.
All I did was check if 'error_reason' existed in the url parameters, and if the error was 'user_denied', and took appropriate action. There might be a better way, but this worked for me.
<?php
//Facebook Authentication
$user = $facebook->getUser();
//Get Login URL
$loginUrl = $facebook->getLoginUrl();
//User is logged in
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;
}
}
//User is not logged in
if (!$user) {
//Check if error_reason was generated and if the user denied login
if (isset($_REQUEST['error_reason']) && ($_REQUEST['error_reason']=='user_denied')) {
//user cancelled permissions dialog thus not logged in to app, redirect elsewhere
echo "<script type='text/javascript'>top.location.href = 'YOUR REDIRECT URL';</script>";
exit;
} else {
//user not logged in so initiate permissions dialog
echo "<script type='text/javascript'>top.location.href = '$loginUrl';</script>";
exit;
}
}
//get user basic description
$userInfo = $facebook->api("/$user");
?>

Related

editor is not able to create instant article in facebook

I am creating a code to create instant articles on facebook using PHP SDK. I have created a login using it, and added 'public_profile,email,manage_pages,pages_show_list,pages_manage_instant_articles' permissions.
When user click on login button, it is asking for all these permissions. If user is an admin of a page and he logs in using it, he is able to create instant article on that page. But when user having an editor role of that page, tries to login, he is being asked for all these permissions, and even if he allows for all these permissions, still he is not able to create an instant article. In error log, there is a error like below:
PHP Fatal error: Uncaught Facebook\Exceptions\FacebookAuthorizationException: (#200) Requires extended permission: pages_manage_instant_articles in ../facebook-php-sdk-v4-5.0.0/src/Facebook/Exceptions/FacebookResponseException.php:120
At first time of login, editor user was asked for all permissions and he approved all, but still this error occurred. Now when he tries to again login, he is not being asked for permissions. I have checked permissions for editor role user though "/me/permissions" endpoint. In response, "email, user_friends, pages_show_list, and public_profile" permissions have status "granted", but there is no any detail about "manage_pages and pages_manage_instant_articles" permissions.
For admin role users, all code is working fine and instant article also created using PHP SDK, but this issue comes only for editor role user.
Here is code which I have tried, I have not included my app-id, app-secret, page-id and article-html here:
<?php
session_start();
$page_id = '{page-id}';
$app_id='{app-id}';
$app_secret='{app-secret}';
require_once 'testing/facebook-php-sdk-v4-5.0.0/src/Facebook/autoload.php';
if(!isset($_GET['user'])){
?>
<!DOCTYPE html>
<html>
<head>
<title>Facebook Login JavaScript Example</title>
<meta charset="UTF-8">
</head>
<body>
<script>
// This is called with the results from from FB.getLoginStatus().
function statusChangeCallback(response) {
console.log('statusChangeCallback');
console.log(response);
// The response object is returned with a status field that lets the
// app know the current login status of the person.
// Full docs on the response object can be found in the documentation
// for FB.getLoginStatus().
if (response.status === 'connected') {
// Logged into your app and Facebook.
//testAPI();
var accessToken = response.authResponse.accessToken;
console.log('access token -: '+accessToken);
location.href="instant_article.php?user=logged_in";
} else if (response.status === 'not_authorized') {
// The person is logged into Facebook, but not your app.
document.getElementById('status').innerHTML = 'Please log ' +
'into this app.';
} else {
// The person is not logged into Facebook, so we're not sure if
// they are logged into this app or not.
document.getElementById('status').innerHTML = 'Please log ' +
'into Facebook.';
}
}
// This function is called when someone finishes with the Login
// Button. See the onlogin handler attached to it in the sample
// code below.
function checkLoginState() {
FB.getLoginStatus(function(response) {
statusChangeCallback(response);
});
}
window.fbAsyncInit = function() {
FB.init({
appId : <?= $app_id ?>,
cookie : true, // enable cookies to allow the server to access the session
xfbml : true, // parse social plugins on this page
version : 'v2.6' // use graph api version 2.5
});
// Now that we've initialized the JavaScript SDK, we call
// FB.getLoginStatus(). This function gets the state of the
// person visiting this page and can return one of three states to
// the callback you provide. They can be:
//
// 1. Logged into your app ('connected')
// 2. Logged into Facebook, but not your app ('not_authorized')
// 3. Not logged into Facebook and can't tell if they are logged into
// your app or not.
//
// These three cases are handled in the callback function.
FB.getLoginStatus(function(response) {
statusChangeCallback(response);
});
};
// Load the SDK asynchronously
(function(d, s, id) {
var js, fjs = d.getElementsByTagName(s)[0];
if (d.getElementById(id)) return;
js = d.createElement(s); js.id = id;
js.src = "//connect.facebook.net/en_US/sdk.js";
fjs.parentNode.insertBefore(js, fjs);
}(document, 'script', 'facebook-jssdk'));
</script>
<!--
Below we include the Login Button social plugin. This button uses
the JavaScript SDK to present a graphical Login button that triggers
the FB.login() function when clicked.
-->
<fb:login-button scope="public_profile,email,manage_pages,pages_show_list,pages_manage_instant_articles" onlogin="checkLoginState();">
</fb:login-button>
<div id="status">
</div>
</body>
</html>
<?php
}else{
$fb = new Facebook\Facebook([
'app_id' => $app_id,
'app_secret' => $app_secret,
'default_graph_version' => 'v2.6',
'default_access_token' => $app_id.'|'.$app_secret
]);
$oAuth2Client = $fb->getOAuth2Client();
$helper = $fb->getJavaScriptHelper();
$sr = $helper->getSignedRequest();
$user_id = $sr ? $sr->getUserId() : null;
if ( $user_id ) {
try {
// Get the access token
$accessToken = $helper->getAccessToken();
$_SESSION['user_token'] = (string) $accessToken;
} catch( Facebook\Exceptions\FacebookSDKException $e ) {
// There was an error communicating with Graph
echo "SDK error: ".$e->getMessage();
unset($_SESSION['user_token']);
} catch(Facebook\Exceptions\FacebookResponseException $e) {
// When Graph returns an error
echo 'Graph returned an error: ' . $e->getMessage();
unset($_SESSION['user_token']);
}
if (! isset($accessToken)) {
echo 'No cookie set or no OAuth data could be obtained from cookie.';
unset($_SESSION['user_token']);
}else{
if($accessToken->isExpired()){
unset($_SESSION['user_token']);
echo "<script>location.href='instant_article.php'</script>";
exit;
}
}
if(!isset($_SESSION['user_token'])){
echo "<script>location.href='instant_article.php'</script>";
exit;
}
try {
// Exchanges a short-lived access token for a long-lived one
$userToken = $oAuth2Client->getLongLivedAccessToken($accessToken);
$long_token = $userToken->getValue();
} catch(Facebook\Exceptions\FacebookSDKException $e) {
// There was an error communicating with Graph
echo 'SDK error: '.$e->getMessage();
exit;
}
/*$res_perms = $fb->get('/me/permissions?access_token='.$long_token,$long_token,'','v2.6');
echo "<pre>";
print_r($res_perms);
exit;*/
$res_page = $fb->get('/'.$page_id.'?fields=access_token',$long_token,'','v2.6');
$page_info = $res_page->getDecodedBody();
$page_token = $page_info['access_token'];
$article_html = '{ html of article goes here}';
if(trim($article_html) != ""){
$page_params = array(
'access_token'=>$page_token,
'html_source'=>$article_html,
'development_mode'=>true
);
$res_article = $fb->post('/'.$page_id.'/instant_articles',$page_params,$page_token);
}
}
}
?>
It would be great if anyone can help me for this.

facebook php sdk to make login and logout?

I am trying to login a website by using facebook. For that I have taken the help of Facebook php SDK. For now my code looks like this
<div id="fb-root"></div>
<script type="text/javascript">
//<![CDATA[
window.fbAsyncInit = function() {
FB.init({
appId : 'xxxxxxxxxxxxxx', // App ID
channelURL : '', // Channel File, not required so leave empty
status : true, // check login status
cookie : true, // enable cookies to allow the server to access the session
oauth : true, // enable OAuth 2.0
xfbml : false // parse XFBML
});
};
// logs the user in the application and facebook
function login(){
FB.getLoginStatus(function(r){
if(r.status === 'connected'){
window.location.href = 'fbconnect.php';
}else{
FB.login(function(response) {
if(response.authResponse) {
//if (response.perms)
window.location.href = 'fbconnect.php';
} else {
// user is not logged in
}
},{scope:'email'}); // which data to access from user profile
}
});
}
// Load the SDK Asynchronously
(function() {
var e = document.createElement('script'); e.async = true;
e.src = document.location.protocol + '//connect.facebook.net/en_US/all.js';
document.getElementById('fb-root').appendChild(e);
}());
//]]>
</script>
<?php
require_once 'src/facebook.php'; //include the facebook php sdk
$facebook = new Facebook(array(
'appId' => 'xxxxxxxxxxxxxx', //app id
'secret' => 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx', // app secret
));
$user = $facebook->getUser();
if ($user) { // check if current user is authenticated
try {
// Proceed knowing you have a logged in user who's authenticated.
$user_profile = $facebook->api('/me'); //get current user's profile information using open graph
}
catch(Exception $e){}
}
?>
<a href='#' onclick='login();'>Facebook Login</a>
Now with this code I can do login easily. But after this I need two more things.
Make a logout after login. So how can I make a logout function here
so that when a user will click on logout he will be logout from both
facebook and the site at a time.
How to get user info after login like his name, email id etc.
So can someone kindly tell me how to do this? I am just a newbie in facebook app. So any help and suggestions will be raelly appreciable. Thanks
To get the Logout URL u can try this:
$fbUserId = $facebook->getUser();
if ($fbUserId) {
$host = $_SERVER['HTTP_HOST'];
$params = array('next' => "http://{$host}/project/page.php");
$logoutUrl = $facebook->getLogoutUrl($params);
}
For Getting the User Details you can try this
try {
$user_profile = $facebook->api('/me');
} catch (FacebookApiException $e) {
return false;
}
return $user_profile;

PHP error when trying to integrate facebook PHP SDK

I’m new to PHP and tying to set up a page as so users can login using Facebook PHP SDK and JavaScript SDK. I keep getting the fallowing error and I don’t seem to be able to find a solution.
I saw a similar post in here but I couldn’t give solution to the error.
Parse error: syntax error, unexpected T_STRING, expecting ',' or ';' in /homepages/9/d321009915/htdocs/kno_login/login.php on line 2
Here is my code:
<?php
echo '<div id='fb-root'></div>';
require_once("facebook.php");
$config = array();
$config['appId'] = 'some id';
$config['secret'] = 'something here';
$facebook = new Facebook($config);
?>
<script>
window.fbAsyncInit = function() {
FB.init({
appId : '293441190799565', // App ID
channelUrl : '//www.reyesmotion.com/kno_login/channel.html', // Channel File
status : true, // check login status
cookie : true, // enable cookies to allow the server to access the session
xfbml : true // parse XFBML
});
// Here we subscribe to the auth.authResponseChange JavaScript event. This event is fired
// for any authentication related change, such as login, logout or session refresh. This means that
// whenever someone who was previously logged out tries to log in again, the correct case below
// will be handled.
FB.Event.subscribe('auth.authResponseChange', function(response) {
// Here we specify what we do with the response anytime this event occurs.
if (response.status === 'connected') {
// The response object is returned with a status field that lets the app know the current
// login status of the person. In this case, we're handling the situation where they
// have logged in to the app.
testAPI();
} else if (response.status === 'not_authorized') {
// In this case, the person is logged into Facebook, but not into the app, so we call
// FB.login() to prompt them to do so.
// In real-life usage, you wouldn't want to immediately prompt someone to login
// like this, for two reasons:
// (1) JavaScript created popup windows are blocked by most browsers unless they
// result from direct interaction from people using the app (such as a mouse click)
// (2) it is a bad experience to be continually prompted to login upon page load.
FB.login();
} else {
// In this case, the person is not logged into Facebook, so we call the login()
// function to prompt them to do so. Note that at this stage there is no indication
// of whether they are logged into the app. If they aren't then they'll see the Login
// dialog right after they log in to Facebook.
// The same caveats as above apply to the FB.login() call here.
FB.login();
}
});
};
// Load the SDK asynchronously
(function(d){
var js, id = 'facebook-jssdk', ref = d.getElementsByTagName('script')[0];
if (d.getElementById(id)) {return;}
js = d.createElement('script'); js.id = id; js.async = true;
js.src = "//connect.facebook.net/en_US/all.js";
ref.parentNode.insertBefore(js, ref);
}(document));
// Here we run a very simple test of the Graph API after login is successful.
// This testAPI() function is only called in those cases.
function testAPI() {
console.log('Welcome! Fetching your information.... ');
FB.api('/me', function(response) {
console.log('Good to see you, ' + response.name + '.');
});
}
</script>
<!--
Below we include the Login Button social plugin. This button uses the JavaScript SDK to
present a graphical Login button that triggers the FB.login() function when clicked.
Learn more about options for the login button plugin:
/docs/reference/plugins/login/ -->
<?php
echo '<fb:login-button show-faces="true" width="200" max-rows="1"></fb:login-button>';
?>
Just change the outer single quotes to double
echo "<div id='fb-root'></div>";

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

Possible duplicate of facebook Uncaught OAuthException: An active access token must be used to query information about the current user
But I did not get a proper solution.
I am using facebook sdk with codeigniter it is working properly. but sometimes it throws exception OAuthException: An active access token must be used to query information about the current user.
Here is the code of Controller file
$config = array(
'appId' => 'XXXXXXX',
'secret' => 'XXXXXXXXXXXXXXXXXXXXXXXXXX',
'fileUpload' => true,
);
$this->load->library('facebook/Facebook', $config);
$fbme = null;
$user = $this->facebook->getUser();
if ($user) {
try {
$fbme = $this->facebook->api('/me');
} catch (FacebookApiException $e) {
error_log($e);
$user = null;
}
}
//if user is logged in and session is valid.
if ($fbme){
//do some stuff...
//redirecting to user home page (my site's)
}
In view file, I am using js sdk. Code for view file is
<div id="fb-root"></div>
<script type="text/javascript">
var button2;
window.fbAsyncInit = function() {
FB.init({ appId: 'XXXXXXXX',
status: true,
cookie: true,
xfbml: true,
oauth: true});
function updateButton(response) {
button1 = document.getElementById('fb-login'); //login button
button2 = document.getElementById('fb-logout'); //logout button
if (response.authResponse) {
//user is already logged in and connected
button2.onclick = function() {
FB.logout(function(response) {});
};
} else {
//user is not connected to your app or logged out
button1.onclick = function() {
FB.login(function(response) {
if (response.authResponse) {
} else {
//user cancelled login or did not grant authorization
}
}, {scope:'email,user_birthday,user_about_me,user_likes,user_interests,user_education_history,user_work_history'});
}
}
}
// run once with current status and whenever the status changes
FB.getLoginStatus(updateButton);
FB.Event.subscribe('auth.login', function(response) {
window.location.reload();
});
FB.Event.subscribe('auth.logout', function(response) {
window.location.reload();
});
};
(function() {
var e = document.createElement('script'); e.async = true;
e.src = document.location.protocol
+ '//connect.facebook.net/en_US/all.js';
document.getElementById('fb-root').appendChild(e);
}());
</script>
PROBLEM:
Sometimes the it throws "OAuthException: An active access token must be used to query information about the current user." to the error log file.
Case: user is logged in facebook and has already authenticated my app
If a user is logged in facebook and authenticated my app and tries to logged in to my site,
rather redirecting the user to my site (php sdk is not working in this case), it is loading the view file. In view file also I am checking whether the user is logged in in facebook or not. (in view) if the user is logged in it will reload the page, same controller script will run and it redirects the user to user's home page(php sdk is working in this case.).
But first time it is not working. Don't know where I am making the mistake.
Also that logout button (in view file) is also sometimes not working. Means on clicking it is not logging out the user from facebook. (It is only happening in one of my colleague's browser. She is using chrome in windows 7)
I was having a similar problem while using PHP-SDK + JS-SDK together. I temporarily solved it by removing the FB.init "cookie:true" option.
By some reason that I couldn't find, an invalid signedRequest cookie is being shared between PHP and JS, then, the valid access_token of the PHP Session was being override with an invalid access_token, thus, destroying the previously valid PHP token.
The difference between my problem and yours is that you're logging via JS and trying to access the same session on PHP (I was doing it backwards, logging on PHP and trying to use the JS-SDK).
This bug is apparently fixed on this pull request:
https://github.com/facebook/facebook-php-sdk/pull/48

Facebook API Logout of my app but not facebook

How do I make a logout using Facebook's api log me out of my app (a website), but keep me logged into facebook.com?
This logs me in alright:
window.fbAsyncInit = function()
{
FB.init({
appId : '<?= APP_ID ?>',
status : true,
cookie : true,
xfbml : true,
oauth : true,
});
FB.Event.subscribe('auth.login', function(response)
{alert(response);
window.location = 'http://reviewsie.com/accounts/facebook';
});
};
(function(d)
{
var js, id = 'facebook-jssdk'; if (d.getElementById(id)) {return;}
js = d.createElement('script'); js.id = id; js.async = true;
js.src = "//connect.facebook.net/en_US/all.js";
d.getElementsByTagName('head')[0].appendChild(js);
}(document));
But then I click logout on my site which I kill my session to my app. Then when you click on the fb:login-button again, it just opens and closes and doesn't do anything because I'm still connected to facebook. I want it to redirect.
But if when I logout I also use Facebook::logoutUrl it logs me out of my app AND facebook which is not what I want.
A bit late but might help someone. You can revoke app permissions which effectively logs them out of your app. Here's the code:
FB.api('/me/permissions', 'delete', function(response) {
console.log(response.status); // true for successful logout.
});
This works for me:
window.fbAsyncInit = function() {
FB.getLoginStatus(function(response) {
FB.api("/me/permissions", "delete", function(response){
});
});
}
Are you sure you want to only logout of your app, and not fb too, if you logged in using fb? What kind of app could want to do something like that? And why? What's the benefit of doing so?
But if you really want to (hack), in index.php:
<?php
require 'init.php'; // general init
require 'init_fb.php'; // sets $fb_id if logged in to fb
if (isset($fb_id) and !isset($_SESSION['do_not_auto_login'])) {
echo "<a href='/logout'>Logout</button>";
include 'app.php';
return;
}
if (isset($_SESSION['do_not_auto_login'])
echo "<a href='/re_login'>FB Login</button>";
else include 'html_and_js_fb_login_code_and_button.php';
include 'startpage.php';
?>
and in logout.php:
$_SESSION['do_not_auto_login'] = true;
// destroy-code
and in re_login.php:
unset($_SESSION['do_not_auto_login']);
header("location: /"); // re-direct back to index.php
Not perfect, but works somewhat good. Hope you get the hack!
But still, why?? If you don't think your user would like to come back, ask "How to remove my fb-app from user?" or something instead or try #DMCS's answer.. Why?
You need to use destroySession for Facebook to do
www.example.com?act=logout
<?php
php sdk blah blah
if($_GET['act'] =='logout'){
$facebook->destroySession();
}
$params = array(
'scope' => 'read_stream, friends_likes',
'redirect_uri' => 'https://www.myapp.com/post_login_page'
);
$loginUrl = $facebook->getLoginUrl($params);
?>
Maybe you need to set param to make it redirect.
When the user is logged into your app, send an HTTP DELETE call to /me/permissions using their current access token. This will log them out of your app requiring them to re-authenticate if they want to play some more. Also be sure to destroy the php session using normal php session clearing code.

Categories