Correct way of adding Facebook login to the Website - facebook

I want to add Facebook login to my website, My script is working fine but I am not sure this way is correct or not, can you someone verify and suggest If I am doing wrong. And I have few questions.
Script:
function statusChangeCallback(response)
{
if (response.status === 'connected') {
testAPI();
} else if (response.status === 'not_authorized') {
console.log('still not authorized!');
} else {
console.log("not connected, not logged into facebook, we don't know");
}
}
window.fbAsyncInit = function() {
FB.init({
appId : 'APP_ID',
cookie : true,
xfbml : true,
version : 'v2.8'
});
checkLoginState();
FB.AppEvents.logPageView();
};
(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'));
function checkLoginState() {
FB.getLoginStatus(function(response) {
statusChangeCallback(response);
});
}
function testAPI() {
console.log('Welcome! Fetching your information.... ');
FB.api('/me', { fields: 'name,email,gender' }, function(response) {
console.log('Successful login for: ' + response.name);
document.getElementById('status').innerHTML =
'Thanks for logging in, ' + response.name + '!';
window.location.replace('http://www.example.com');
});
}
Button display:
<div class="fb-login-button" data-onlogin="checkLoginState()" data-max-rows="1" data-size="medium" data-button-type="login_with" data-show-faces="false" data-auto-logout-link="false" data-login-text="Sign in with Facebook"></div>
After successful login, I want to redirect to members-only.php by passing id, email. In the above script I have written window.location.replace('http://www.example.com'); instead example.com, can i give my php file name?
appId can be seen by every body, will that be fine? or we need to keep it as secret?
If the user is coming for the first time, what details we need to register in our database? and from second time how can we identify that user?
Thanks in advance.

window.location.replace('http://www.example.com/members-only.php');
It is no problem to make the App ID public. Just be careful with Access Tokens and the App Secret. They are not meant to be public.
You only need the ID to identify the user. The rest is up to you, if you want to cache it.

Related

Reacts Facebook login - using ES6

Having looked at this: Implement Facebook API login with reactjs
I am trying to create a Reactjs component for Facebook login.
I am using ES6 and I keep getting: "Cannot read property 'parentNode' of undefined"
Code:
'use strict';
import React from 'react';
import addons from 'react/addons'
export default class Login extends React.Component {
constructor(props) {
super(props);
this.handleClick = this.handleClick.bind(this);
this.checkLoginState = this.checkLoginState.bind(this);
this.statusChangeCallback = this.statusChangeCallback.bind(this);
this.testAPI = this.testAPI.bind(this);
}
render() {
return (
<div class="fb-login-button" data-max-rows="1" data-size="medium" data-show-faces="false" data-auto-logout-link="false"></div>
);
} // Render
componentDidMount() {
window.fbAsyncInit = function() {
FB.init({
appId : 'xxx',
cookie : true, // enable cookies to allow the server to access
// the session
xfbml : true, // parse social plugins on this page
version : 'v2.3' // use version 2.1
});
// 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) {
this.statusChangeCallback(response);
}.bind(this));
}.bind(this);
// 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.
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 + '!';
});
}
// This is called with the results from from FB.getLoginStatus().
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.
this.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.
checkLoginState() {
FB.getLoginStatus(function(response) {
this.statusChangeCallback(response);
}.bind(this));
}
handleClick() {
FB.login(this.checkLoginState());
}
} // Component
Any idea?
Thanks
Found the solution.
You have to add at least: <script></script> in your template, outside your component.
This error is caused because the code trying to do something with <script> but he can't found it.
On the second line of the code snippet below, the variable fjs is being initialized to an undefined value, which is then references in fjs.parentNode.
// Load the SDK asynchronously
(function(d, s, id) {
var js, fjs = d.getElementsByTagName(s)[0];
// ... code ...
fjs.parentNode.insertBefore(js, fjs);
}(document, 'script', 'facebook-jssdk'));

When I try facebook login in localhost, it is worked but real server doesn't work

When I try facebook login in localhost, it is worked but real server doesn't work.
When I try facebook login in localhost, it is worked but real server doesn't work.
When I try facebook login in localhost, it is worked but real server doesn't work.
<!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 : '1530295003876175',
cookie : true, // enable cookies to allow the server to access
// the session
xfbml : true, // parse social plugins on this page
version : 'v2.1' // use version 2.1
});
// 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, ' +'<br/>'+ response.name +'<br/>'+ response.email + '!';
});
}
</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>
<b>This is only for server </b>
1) Go to http://developers.facebook.com
2) MyApps click
3) Create Apps
4) Add Platform (web/mobile/etc)
5) Quick Start for Website : ente`enter code here`r your site name or website url
[generate bleow api id and code its copy and user page then ]
example:
<script>
window.fbAsyncInit = function() {
FB.init({
appId : '6417187378599749',
xfbml : true,
version : 'v2.2'
});
};
(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>
6) Tell us about your website: Write/enter your website url/ domain name
7) Next button click
8) choose loging box/like box/etc
9) chosse up code demo and use
I had same issue. Facebook login works at local server but real server it return 0 as user id. The solution for this was, in the url use www.test.com instead of test.com, where test.com is your domain. It will solve your issue.
Thanks

Facebook login returning nothing

I looked all over and I can't seem to find the solution to this. I am trying to implement Facebook login to my website and I am having one hell of a time doing so.
I have implemented the Facebook graph api and I have the login part built in but I can't get anything to return from it to handle it.
You can see what I mean on < phiride.com > (I don't know if that's bad netiquette to post the url on this website, if so sorry!)
I used the code given to get a return -->
<script>
FB.api('/me', function(response) {
console.log(JSON.stringify(response));
});
</script>
Absolutely nothing is printed to the screen and I can't find anyway to handle the information. I'm sure this is a simple beginner mistake but any help would be greatly appreciated.
Did you generate the html and script via their website.
https://developers.facebook.com/docs/plugins/login-button
This is what you need to do in order to make API calls work:
Initialize the JavaScript SDK
Authorize the user
Initialize the JavaScript SDK
<script>
window.fbAsyncInit = function() {
FB.init({
appId : 'your-app-id',
xfbml : true,
version : 'v2.1'
});
};
(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>
Authorize the user
FB.login(function(response) {
if (response.authResponse) {
console.log('Welcome! Fetching your information.... ');
FB.api('/me', function(response) {
console.log('Good to see you, ' + response.name + '.');
console.log('Your Email: ' + response.email);
}, {scope: 'email'});
} else {
console.log('User cancelled login or did not fully authorize.');
}
});
Only call FB.login on user interaction (on click) to make sure it does not get blocked by the browser - it has to get called AFTER FB.init too. You can also check if a user is already authorized by using FB.getLoginStatus right after FB.init.
Sources:
https://developers.facebook.com/docs/javascript/quickstart/v2.1
https://developers.facebook.com/docs/reference/javascript/FB.login/v2.1
https://developers.facebook.com/docs/reference/javascript/FB.getLoginStatus

Permission to access emails and facebook

I create a app that use login on Facebook, but I can not capture the user's email address, I know I need to use scope, but do not know how. How can I do this?
This is my code:
window.fbAsyncInit = function() {
FB.init({
appId : '<?= $this->getAppId(); ?>', // App ID
channelUrl : '//WWW.YOUR_DOMAIN.COM/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
oauth : true
});
FB.Event.subscribe('auth.authResponseChange', function(response) {
// Here we specify what we do with the response anytime this event occurs.
if (response.status === 'connected') {
testAPI();
} else if (response.status === 'not_authorized') {
FB.login()
} else {
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 + '.');
console.log( response.email);
});
}
You pass in any additional permissions you want as an argument (comma-separated for multiple permissions) to FB.login(). IN your case, you want email:
FB.login(function(response) {
// handle the response
}, {scope: 'email'});
The FB JS SDK Documentation very clearly explains this. Please take the time to read it.
I resolved the problem, when use FB.Event.subscribe, we need put the permissions in html and not in FB.login() function, using this way:
fb:login-button show-faces="true" perms="email,user_birthday" width="200" max-rows="1
Thanks

FB.Event.subscribe('auth.login') won't trigger everytime ?

<div id="fb-root"></div>
<script>
window.fbAsyncInit = function() {
FB.init({
appId : 'MY_APP_ID',
status : true,
cookie : true,
xfbml : true
});
FB.Event.subscribe('auth.login', function(response) {
$.ajax({
url: "http://example.com/fbconnect",
success: function(){
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>
<div class="fb-login-button" data-perms="email,user_birthday,user_hometown,user_location">Login with Facebook</div>
It's working with only two cases.
1- when a user is NOT logged in and log in to facebook it triggers.
2- when a user is logged in but didn't authorize the app yet it triggers.
the third scenario which is not working is when a user is logged in and He is already authorized the app the FB.Event.subscribe('auth.login) won't trigger !!!
I encountered the same thing as you and I found a function, "getLoginStatus", that might be of interest for you.
When the user is already logged in and has granted your app all the permissions, then there is no need to log in again and therefore the event won't be triggered.
However, if the response of the "getLoginStatus" is "connected" you can do the stuff you want to do when the user is already logged in and has granted your app all the permissions.
The complete script might look something like this:
<script>
window.fbAsyncInit = function() {
FB.init({
appId : 'APPID', // App ID
channelUrl : 'CHANNEL_URL', // Channel File
status : true, // check login status
cookie : true, // enable cookies to allow the server to access the session
xfbml : true // parse XFBML
});
FB.getLoginStatus(function(response) {
if (response.status === 'connected') {
// the user is logged in and connected to your
// app, and response.authResponse supplies
// the user's ID, a valid access token, a signed
// request, and the time the access token
// and signed request each expire
var uid = response.authResponse.userID;
var accessToken = response.authResponse.accessToken;
FB.api('/me', function(response) {
if (response.name != undefined ) {
console.log("Welcome, " + response.name);
}
});
} else if (response.status === 'not_authorized') {
// the user is logged in to Facebook,
// but not connected to the app
} else {
// the user isn't even logged in to Facebook.
}
});
// Additional initialization code here
};
// Load the SDK Asynchronously
(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>
Got the exact same issue here and it's driving me nuts. Not liking the Facebook Javascript SDK atm.
It's really complex with the status check in FB.init() and makes it even harder when you put facebook comments on the page...
A workaround I just tested is to have your own login button and use the FB.login() method, there you can hook in to the callback (this replaces your code for the auth.login event).
window.fbAsyncInit = function () {
FB.init({
...
});
$('#fb-login-button-custom').show().click(function () {
var scopeList = $(this).data('scope');
FB.login(function (response) {
alert('FB.login callback');
console.log(response);
document.location.href = document.location.pathname + '?fblogin=1';
}, { scope: scopeList });
});
});
That default login event is actually only triggered when the user authorizes your application. So when loging out the user, you could revoke the authorization. But then every time they log in they have to 'allow' the app.
Using FB.Event.subscribe('auth.statusChange', handleStatusChange); will notify you status changes..
hope it helps