Quickstart With Facebook the JavaScript SDK
http://developers.facebook.com/apps/
<!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();
} 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 : '{your-app-id}',
cookie : true, // enable cookies to allow the server to access
// the session
xfbml : true, // parse social plugins on this page
version : 'v2.2' // use version 2.2
});
// 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'));
// Here we run a very simple test of the Graph API after login is
// successful. See statusChangeCallback() for when this call is made.
function testAPI() {
console.log('Welcome! Fetching your information.... ');
FB.api('/me', function(response) {
console.log('Successful login for: ' + response.name);
document.getElementById('status').innerHTML =
'Thanks for logging in, ' + 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.
-->
<fb:login-button scope="public_profile,email" onlogin="checkLoginState();">
</fb:login-button>
<div id="status">
</div>
</body>
</html>
This code will load and initialize the JavaScript SDK in your HTML page. Use your app ID where indicated.
Now you can test your app by going to the URL where you uploaded this HTML. Open your JavaScript console, and you’ll see the testAPI()
function display a message with your name in the console log.
Congratulations, at this stage you’ve actually built a really basic page with Facebook Login. You can use this as the starting point for your own app, but it will be useful to read on and understand what is happening in the code above.
Create User Table
CREATE TABLE IF NOT EXISTS `usertable` (
`id` int(20) NOT NULL AUTO_INCREMENT,
`fbid` bigint(20) NOT NULL,
`fullname` varchar(60) NOT NULL,
`email` varchar(60) NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=1;?
Configuration File
########## app ID and app SECRET (Replace with yours) #############
$appId = 'xxxxxx'; //Facebook App ID
$appSecret = 'xxxxxxxxxxxxxx'; // Facebook App Secret
$return_url = 'http://yoursite.com/connect_script/'; //path to script folder
$fbPermissions = 'publish_actions,email'; //more permissions : https://developers.facebook.com/docs/authentication/permissions/
########## MySql details (Replace with yours) #############
$db_username = "xxxxxx"; //Database Username
$db_password = "xxxxxx"; //Database Password
$hostname = "localhost"; //Mysql Hostname
$db_name = 'database_name'; //Database Name
###################################################################
Login Button
<a href="#" rel="nofollow" class="fblogin-button" onClick="javascript:CallAfterLogin();return false;">Login with Facebook</a>
<div class="fb-login-button" data-max-rows="1" data-size="medium" data-show-faces="false" data-auto-logout-link="false" onlogin="javascript:CallAfterLogin();" scope="publish_actions,email"></div>
session_start();
include_once("include/config.php");
if(!isset($_SESSION['logged_in']))
{
echo '<div id="results">';
echo '<!-- results will be placed here -->';
echo '</div>';
echo '<div id="LoginButton">';
echo '<a href="javascript:void(0)" rel="nofollow" class="fblogin-button" onClick="javascript:CallAfterLogin();return false;">Login with Facebook</a>';
echo '</div>';
}
else
{
echo 'Hi '. $_SESSION['user_name'].'! You are Logged in to facebook, <a href="?logout=1">Log Out</a>.';
}
Here’s the javascript code.
<div id="fb-root"></div>
<script type="text/javascript">
window.fbAsyncInit = function() {
FB.init({
appId: '<?php echo $appId; ?>',
cookie: true,xfbml: true,
channelUrl: '<?php echo $return_url; ?>channel.php',
oauth: true
});
};
(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);}());
function CallAfterLogin(){
FB.login(function(response) {
if (response.status === "connected")
{
LodingAnimate(); //Animate login
FB.api('/me', function(data) {
if(data.email == null)
{
//Facbeook user email is empty, you can check something like this.
alert("You must allow us to access your email id!");
ResetAnimate();
}else{
AjaxResponse();
}
});
}
},
{scope:'<?php echo $fbPermissions; ?>'});
}
//functions
function AjaxResponse()
{
//Load data from the server and place the returned HTML into the matched element using jQuery Load().
$( "#results" ).load( "process_facebook.php" );
}
//Show loading Image
function LodingAnimate()
{
$("#LoginButton").hide(); //hide login button once user authorize the application
$("#results").html('<img src="img/ajax-loader.gif" /> Please Wait Connecting...'); //show loading image while we process user
}
//Reset User button
function ResetAnimate()
{
$("#LoginButton").show(); //Show login button
$("#results").html(''); //reset element html
}
</script>
Process Requests
session_start();
include_once("include/config.php"); //Include configuration file.
require_once('include/facebook.php' ); //include fb sdk
/* Detect HTTP_X_REQUESTED_WITH header sent by all recent browsers that support AJAX requests. */
if ( !empty($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest' )
{
//initialize facebook sdk
$facebook = new Facebook(array(
'appId' => $appId,
'secret' => $appSecret,
));
$fbuser = $facebook->getUser();
if ($fbuser) {
try {
// Proceed knowing you have a logged in user who's authenticated.
$me = $facebook->api('/me'); //user
$uid = $facebook->getUser();
}
catch (FacebookApiException $e)
{
//echo error_log($e);
$fbuser = null;
}
}
// redirect user to facebook login page if empty data or fresh login requires
if (!$fbuser){
$loginUrl = $facebook->getLoginUrl(array('redirect_uri'=>$return_url, false));
header('Location: '.$loginUrl);
}
//user details
$fullname = $me['first_name'].' '.$me['last_name'];
$email = $me['email'];
/* connect to mysql using mysqli */
$mysqli = new mysqli($hostname, $db_username, $db_password,$db_name);
if ($mysqli->connect_error) {
die('Error : ('. $mysqli->connect_errno .') '. $mysqli->connect_error);
}
//Check user id in our database
$UserCount = $mysqli->query("SELECT COUNT(id) as usercount FROM usertable WHERE fbid=$uid")->fetch_object()->usercount;
if($UserCount)
{
//User exist, Show welcome back message
echo 'Ajax Response :<br /><strong>Welcome back '. $me['first_name'] . ' '. $me['last_name'].'!</strong> ( Facebook ID : '.$uid.') [<a href="'.$return_url.'?logout=1">Log Out</a>]';
//print user facebook data
echo '<pre>';
print_r($me);
echo '</pre>';
//User is now connected, log him in
login_user(true,$me['first_name'].' '.$me['last_name']);
}
else
{
//User is new, Show connected message and store info in our Database
echo 'Ajax Response :<br />Hi '. $me['first_name'] . ' '. $me['last_name'].' ('.$uid.')! <br /> Now that you are logged in to Facebook using jQuery Ajax [<a href="'.$return_url.'?logout=1">Log Out</a>].
<br />the information can be stored in database <br />';
//print user facebook data
echo '<pre>';
print_r($me);
echo '</pre>';
// Insert user into Database.
$mysqli->query("INSERT INTO usertable (fbid, fullname, email) VALUES ($uid, '$fullname','$email')");
}
$mysqli->close();
}
function login_user($loggedin,$user_name)
{
/*
function stores some session variables to imitate user login.
We will use these session variables to keep user logged in, until s/he clicks log-out link.
*/
$_SESSION['logged_in']=$loggedin;
$_SESSION['user_name']=$user_name;
}
That’s it! I am sure this will help you make your own Ajax Facebook Login with PHP SDK version 4 with significant changes, Good luck.
0 Comments