I'm implenting my fb app and it's connected to its own fb fanpage. I need to get a users info like username, id etc but when I click on my "Facebook authenticate" link, I end up going to a blank white page?
You can view my code in here: http://codepad.org/f0Tuh63v
error_reporting(E_ALL);
ini_set('display_errors', true);
require 'facebook/facebook.php';
$facebook = new Facebook(array(
'appId' => '1',
'secret' => '2',
));
// See if there is a user from a cookie
$user = $facebook->getUser();
if ($user) {
try {
// Proceed knowing you have a logged in user who's authenticated.
$user_profile = $facebook->api('/me');
print_r($user_profile);
} catch (FacebookApiException $e) {
echo '<pre>'.htmlspecialchars(print_r($e, true)).'</pre>';
$user = null;
}
}
else{
$loginUrl = $facebook->getLoginUrl(
array('scope' => 'user_about_me,user_birthday,email,publish_actions,offline_access,user_hometown,user_location',
'redirect_uri' => "https://domain.net/intro.php"
)
); // end of array
}
?>
<!DOCTYPE html>
<html xmlns:fb="http://www.facebook.com/2008/fbml">
<body>
<?php if ($user) { ?>
Your user profile is
<pre>
<?php print htmlspecialchars(print_r($user_profile, true)) ?>
</pre>
<?php } else { ?>
Facebook authenticate
<?php } ?>
<div id="fb-root"></div>
<script>
window.fbAsyncInit = function() {
FB.init({
appId: '<?php echo $facebook->getAppID() ?>',
cookie: true,
xfbml: true,
oauth: true,
status: true
});
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>
</body>
</html>
It's also here http://codepad.org/f0Tuh63v
What am I doing wrong?
Also is there a way to get the FB user id without using phpsdk or the js sdk? Or do I have to use these plugins?
I cannot see what's wrong with your code. But, If you are using Javascript, I can tell you an alternative for getting authenticated and then getting the info you require.
I used the following code behind my button, which authenticated my Facebook app and then redirected the user to my website. It worked for me.
<a class="fb-login-button" align="center" target="_blank" href="https://www.facebook.com/dialog/oauth?client_id=CLIENT_ID&response_type=token&scope=PERMISSION_1,PERMISSION_2&redirect_uri=YOUR_WEBSITE"> TEXT </a>
Then I extracted the token which was returned in the redirected URL.
var url_t; // Get the redirected URL.
access_token = url_t.split('=')[1].split('&')[0];
Then using the access token I sent the HTTP request for getting the required data. I used GRAPH API provided by facebook. For eg: For getting the first name of the user:
var xhr = new XMLHttpRequest();
var f_url_new = "https://graph.facebook.com/fql?q=SELECT%20name%20FROM%20user%20WHERE%20uid%20=%20me()&access_token=" + access_token;
xhr.open("GET", f_url_new , true);
xhr.onreadystatechange = function() {
if (xhr.readyState == 4) {
obj1 = JSON.parse(xhr.responseText);
var str = obj1.data[0].name.toString();
var n=str.split(" ");
document.getElementById("name").innerText = n[0];
}
}
xhr.send();
Hope it gives you some idea with regards to the alternatives. This is not the correct answer to your question, but can help in the thought process.
Related
I have a problem on Facebook App.
I want to make a fan-gate when any one enter the app url, Ex. apps.facebook.com/zoomcompetition/
I can't make it on the tab because it display blank.
but it works on the app url so I want to add fan-gate on the app appoint to Facebook Page.
This is the code
<?php
require 'src/facebook.php';
//require 'fbconfig.php';
require 'functions.php';
// Create An instance of our Facebook Application.
$facebook = new Facebook(array(
'appId' => ***************,
'secret' => **************,
));
// Get the app User ID
$user = $facebook->getUser();
if ($user) {
try {
// If the user is authenticated and logged-in
$user_profile = $facebook->api('/me');
//var_dump($user_profile);
} catch (FacebookApiException $e) {
error_log($e);
$user = null;
}
// If the user is authenticated then generate the variable for the logout URL
if ($user) {
$logoutUrl = $facebook->getLogoutUrl();
?>
<!-- Insert Logged in HTML here -->
Logout
<?php
//Always place this code at the top of the Page
session_start();
if (!isset($_SESSION['id'])) {
// Redirection to login page facebook
header("location: index.php");
}
echo ' Welcome '.$_SESSION['username']; // or whatever you want your user to see.
$varri = "http://www.*****.ps";
?>
<iframe src=<?php print $varri; ?> scrolling="auto" width=100% height=100% frameborder="0"> </iframe>
<?php
$user = $facebook->getUser();
if ($user) {
$ret_obj = $facebook->api('/me/feed', 'POST',
array(
'link' => 'https://www.************.com',
'picture' => 'http://www.*******************.jpg',
'caption' => "أهلا وسهلا!",
'message' => ' Welcome '.$_SESSION['username'],
'uid'=> $facebook->getUser()
));
}
?>
<?php
} else {
$loginUrl = $facebook->getLoginUrl();
}
if (!empty($user_profile )) {
$username = $user_profile['name'];
$uid = $user_profile['id'];
$email = $user_profile['email'];
$user = new User();
$userdata = $user->checkUser($uid, 'facebook', $username,$email,$twitter_otoken,$twitter_otoken_secret);
if(!empty($userdata)){
session_start();
$_SESSION['id'] = $userdata['id'];
$_SESSION['oauth_id'] = $uid;
$_SESSION['username'] = $userdata['username'];
$_SESSION['email'] = $email;
$_SESSION['oauth_provider'] = $userdata['oauth_provider'];
//header("Location: home.php");
?>
<!--<!DOCTYPE>
<HTML>
<head>
<script>
function run(){
window.location.href = '/facebook/home.php';
}
</script>
</head>
<body onLoad="run()">
</body>
</html> -->
<?php
}
} else {
die("There was an error.");
}
}
else {
// Generate a session if there is none.
$login_url = $facebook->getLoginUrl(array( 'scope' => ' read_stream, publish_stream, email'));
?>
<!DOCTYPE>
<HTML>
<head>
<script>
function run(){
window.location.href = '<?php echo $login_url ?>';
}
</script>
</head>
<body onLoad="run()">
</body>
</html>
<?php
}
?>
Can you help me to solve one of the following:
What do I need to make it not display "Blank" on the tab?
2- How can I make a fan-gate for specific Facebook Pae if any one go to App
url directly?
What do I need to make it not display "Blank" on the tab?
Generate some output instead of nothing, I’d guess …?
How can I make a fan-gate for specific Facebook Pae if any one go to App url directly?
You can redirect from the canvas page to a specific page/app combination via JavaScript (top.location.href = "FB-Address of your page/app id combo"). And to check whether you’re on the canvas page, the simplest way to do so is give it an extra GET parameter in the canvas page address, which you then can evaluate in your code.
I am working on website, in which i want integrate the facebook login with my website login system. I have integrated facebook-php-sdk in code. Login functionality work fine. Below are the points that I have issue...
Once logged out and click on login the facebook login screen not open.
Once logged out and refresh the page, the login deatils is displaying again. And login button disappears.
If the above two points will solved then how to maintain login session through out the website?
For above 2 points I have used the below code.
require 'src/facebook.php';
$facebook = new Facebook(array(
'appId' => YOUR_APP_ID,
'secret' => SECRET_KEY,
));
session_start();
if($_REQUEST['msg'] == 'logout'){
setcookie('fbsr_'.$facebook->getAppId(), '', (time() - 3600), '/', 'domain.com');
$sts = $facebook->destroySession();
session_destroy();
header("Location: index.php");
//echo '<meta http-equiv="refresh" content="2;url=index.php">';
}
$userId = $facebook->getUser();
if ($userId && !isset($_SESSION['fbdata'])) {
$_SESSION['fbdata'] = array("userid" => $userId);
}
<?php if ($userId) {
$userInfo = $facebook->api('/' + $userId); ?>
Welcome <?= $userInfo['name'] ?>
<?php } else { ?>
<div id="fb-root"></div>
<fb:login-button></fb:login-button>
<?php } ?>
<script type="text/javascript">
window.fbAsyncInit = function() {
FB.init({
appId : '<?= YOUR_APP_ID ?>',
status : true,
cookie : true,
xfbml : true,
oauth : true,
});
FB.Event.subscribe('auth.login', function(response) {
//window.location.reload();
});
};
(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));
</script>
<br />
<br />
Logout
I found the answer on my questions below.
1.Once logged out and click on login the facebook login screen not open.
Facebook cookies was not deleted or we can say was not removed from starage. For this I have used this below javascript
function removeCookie( name, path, domain) {
if ( getCookie( name ) )
{
document.cookie = name + '=' + ( ( path ) ? ';path=' + path : '') + ( ( domain ) ? ';domain=' + domain : '' ) + ';expires=Thu, 01-Jan-1970 00:00:01 GMT';
}
}
It works for me.
2.Once logged out and refresh the page, the login deatils is displaying again. And login button disappears.
The same reason as above question.
3.If the above two points will solved then how to maintain login session through out the website?
Maintain the fb id in session and when request coming for logout remove cookie and destroy the session.
I'm trying to get the Facebook user (current user) an U´m using the code:
$app_id = "xxx";
$app_secret = "yyy";
//** Get user information
//Create our application instance.
$facebook = new Facebook(array(
'appId' => $app_id,
'secret' => $app_secret,
));
// 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');....
// The $user_profile = $facebook->api('/me'); line throw an exception:
'message' => string 'An active access token must be used to query
'information about the current user.' (length=80)
'type' => string 'OAuthException' (length=14)
'code' => int 2500
Why?
It seems you did not go through the OAuth 2.0 authentication/authorization process as described at Authentication.
There are some examples there explaining how to do this. I am also using the PHP SDK but I chose to do the authentication through JavaScript on the client side which was easier for me. However, both approaches are explained in the documentation.
Updated: I use this code which is a combination of PHP and JavaScript, which works great for me. The only thing that isn't handled correctly here (AFAIK) is when a user reaches the application when he is not logged in to Facebook, that is, he reaches the application directly through the URL and not through Facebook. In that case a blank page is shown instead of a notification and a login button or something.
Anyway, this is my index.php in which I pass vars from my config.inc.php such as the success (application main page) and failure pages (user didn't grant perms) to JavaScript:
<?php
require 'include/config.inc.php';
//Check whether Facebook OAuth mechanism called back to this script with access_token or error
if (isset($_GET['expires_in']) && $_GET['expires_in']>0)
{
header('Location: '.$appname_canvasPage.$appname_successPage);
exit;
}
else if (isset($_GET['error']))
{
//echo 'querystr: '.$_SERVER['QUERY_STRING'];
header('Location: '.$appname_canvasPage.$appname_failurePage);
exit;
}
else
{
require 'include/header_metadata.inc.html';
?>
</head>
<body>
<div id="fb-root"></div>
<script>
var appname_canvasURI = '<?php echo $appname_canvasURI; ?>';
var appname_canvasPage = '<?php echo $appname_canvasPage; ?>';
var appname_successPage = '<?php echo $appname_successPage; ?>';
var appname_failurePage = '<?php echo $appname_failurePage; ?>';
var appname_fbPerms = '<?php echo $appname_fbPerms; ?>';
var appname_appid= '<?php echo $appname_appid; ?>';
window.fbAsyncInit = function()
{
FB.init({
appId : appname_appid, // App ID
channelUrl : appname_canvasPage+'/channel.html', // Channel File
status : true, // check login status
cookie : true, // enable cookies to allow the server to access the session
oauth : true, // enable OAuth 2.0
xfbml : true // parse XFBML
});
// Additional initialization code here
FB.getLoginStatus(function(response)
{
//console.log('getLoginStatus response: ',response);
if (response.authResponse)
{
//user is already logged in and connected
facebookCheckPerms(); // ensure all requires perms are available and if not request them
}
else
{
//app is not authorized or user is logged out
facebookOAuthRedirect();
}
});
};
// Load the SDK Asynchronously
(function()
{
var e = document.createElement('script');
e.type = 'text/javascript';
e.src = document.location.protocol + '//connect.facebook.net/en_US/all.js';
//e.src = "http://static.ak.fbcdn.net/connect/en_US/core.debug.js";
e.async = true;
document.getElementById('fb-root').appendChild(e);
}());
function facebookCheckPerms()
{
var hasReqPerms=true;
FB.api(
{
method: 'fql.query',
query: 'SELECT '+appname_fbPerms+' FROM permissions WHERE uid=me()'
},
function(response)
{
for(var key in response[0])
{
if(response[0][key]==0)
{
hasReqPerms=false;
}
}
if (hasReqPerms==false)
{
// user does not have required permissions, do OAuth 2.0 redirect to get permissions
facebookOAuthRedirect();
}
else
{
// user has required permissions, start the app.
//console.log('checkperms: user has required permissions, start the app');
top.location.href = appname_canvasPage+appname_successPage;
}
});
}
function facebookOAuthRedirect()
{
var redirectURL = 'https://www.facebook.com/dialog/oauth/?client_id='+appname_appid+'&scope='+appname_fbPerms+'&redirect_uri='+encodeURIComponent(appname_canvasURI)+'&response_type=token';
//console.log('redirectURL: '+redirectURL);
top.location.href = redirectURL;
}
</script>
<?php
}
?>
</body>
</html>
Here I am using Facebook Login button plugin and javascript sdk
I am able to successfully login and logout by using above.
When a first time user has gone through authentication process I need to store user basic information i.e. Facebook login name, email in my database.
Please suggest how I can do this.
<p><fb:login-button autologoutlink="true"></fb:login-button></p>
<div id="fb-root"></div>
<script>
window.fbAsyncInit = function () {
FB.init({ appId: '123456', status: true, cookie: true,
xfbml: true
});
};
(function () {
var e = document.createElement('script');
e.type = 'text/javascript';
e.src = document.location.protocol +
'//connect.facebook.net/en_US/all.js';
e.async = true;
document.getElementById('fb-root').appendChild(e);
} ());
</script>
Subscribe to the event auth.login. If you do this, Facebook will call your handler after a login as happened.
In that handler, use FB.api to call the Graph API to get any information you desire. For example calling /me as shown in the second example will get you basic information about the logged in user.
Now you have all the data in JavaScript. To send that up to your server, do a plain old XMLHttpRequest/AJAX request. Your JavaScript library probably makes this easy -- in jQuery this is jQuery.ajax() -- but worst case you can use XHR directly.
Now you have the data on your server and you can do whatever you want, like store it in the database. If you only want to store the data once, just check that you haven't already stored info about that user ID yet.
It's also possible to use a combination of PHP SDK and JS SDK, with the latter performing the login and the former storing data on the server. Something like:
<?php
require_once 'config.php';
require_once 'lib/facebook.php';
$facebook = new Facebook(array(
'appId' => FB_APP_ID,
'secret' => FB_APP_SECRET,
));
?>
<!DOCTYPE html>
<html xmlns:fb="http://www.facebook.com/2008/fbml">
<body>
<div id="fb-root"></div>
<script>
window.fbAsyncInit = function () {
FB.init({
appId:'<?php echo $facebook->getAppID() ?>',
cookie:true,
xfbml:true,
oauth:true
});
FB.Event.subscribe('auth.login', function (response) {
window.location = "showUser.php"; //redirect to showUser.php on Login
});
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>
<div class="fb-login-button" data-show-faces="true" data-width="200"
data-max-rows="1"></div>
</body>
</html>
And in showUser.php you have something like:
<?php
#showUser.php
require_once 'config.php';
require_once 'lib/facebook.php';
$facebook = new Facebook(array(
'appId' => FB_APP_ID,
'secret' => FB_APP_SECRET,
));
$user = $facebook->getUser();
if($user)
{
if ($user) {
try {
// Proceed knowing you have a logged in user who's authenticated.
$user_profile = $facebook->api('/me');
var_dump($user_profile); //You can now save this data
} catch (FacebookApiException $e) {
echo '<pre>'.htmlspecialchars(print_r($e, true)).'</pre>';
$user = null;
}
}
}
?>
There's a hole in that solution -- this means the user can make up any information he wants and post an XHR back to my server. The server is going to need to check with Facebook directly.
//very simple just change this line
fb:login-button autologoutlink="true"
//with this one
fb:login-button autologoutlink="true" onlogin='your_ajax_fun_that_store_in_db()'
function your_ajax_fun_that_store_in_db(){
FB.api('/me', function(response) {
$.post( "ajax/store_user_info.php",response, function( data ) {
//write you js code here !
//you can use the (response) from facebook directly in your store_user_info.php as it will be sent in POST array
});
});
}
//last thing when you face such a problem the first thing to do is to go back to facebook reference of fun.
Building an app with the Facebook JavaScript API that will embedded into a page using the new iframe method.
I want to detect if they have liked the current page. Usually I would use print_r($_REQUEST) in PHP but that doesn't seem to work when using an iframe.
There is also this option: http://developers.facebook.com/docs/reference/fbml/visible-to-connection/ but it says its deprecated and I have never liked this method as its fairly hacky.
What is the way t do it now? Prefer to use XFBML + JavaScript API but can use PHP if required.
We've done this several times, and it seems to work pretty well. It uses XFBML to generate a Like Button widget and the JS SDK to render XFBML and subscribe to Facebook events. Code sample below:
edit: Since you're looking to detect if the user is a fan when the page loads, and FB deprecated the feature to let you get it directly from them when the canvas is loaded by passing fb_page_id to the address query string, you'll need an application install for the user to test their fan-dom of your page. It certainly adds a lot of friction to your application, but it is what it is for now - I guess.
<?php
require 'facebook.php';
// Create our Application instance (replace this with your appId and secret).
$facebook = new Facebook(array(
'appId' => 'YOUR APP ID',
'secret' => 'YOUR APP SECRET',
'cookie' => false,
));
try
{
$session = $facebook->getSession();
if (empty($session['uid']))
{
throw new Exception("User not connected to application.");
}
$is_fan = $facebook->api(array(
'method' => 'fql.query',
'query' => "SELECT uid, page_id FROM page_fan WHERE uid = {$session['uid']}"
));
if (false == $is_fan || count($is_fan) == 0) // 0 results will be returned if the user is not a fan
{
$is_fan = false;
}
else
{
$is_fan = true;
}
}
catch (FacebookApiException $e)
{
/**
* you don't have an active user session or required permissions
* for this user, so rdr to facebook to login.
**/
$loginUrl = $facebook->getLoginUrl(array(
'req_perms' => 'user_likes'
));
header('Location: ' . $loginUrl);
exit;
}
?>
<html>
<head>
</head>
<body>
<? if (empty($is_fan)): //user is not a fan. ?>
<fb:like href="http://www.facebook.com/your-facebook-page"
show_faces="true"
width="400">
</fb:like>
<? else: ?>
Yay! You're a fan!
<? endif; >?
<div id="fb-root"></div>
<script src="http://connect.facebook.net/en_US/all.js" type="text/javascript">
</script>
<script type="text/javascript">
FB.init({
appId: '<?= FB_APP_ID; ?>',
cookie: true,
status: true,
xfbml: true
});
// Subscribe to the edge creation event, from Facebook
FB.Event.subscribe('edge.create', function(response)
{
alert("Congratulations! We are so excited that you are a fan now! woot!")
});
</script>
</body>
</html>
okay, finally got got everything formatted with straight markdown. that wasn't painful at all.. (sike) :|