Check if user is over 18 using Facebook Graph API - facebook-graph-api

I'm using Facebook to login users to a website. At the moment I'm using the example code by facebook(below). This works fine and returns the user name with a success message but I need to check if they are over 18 or not using age_range graph api call. However I can't work out from the developer docs how to do this. Can anyone help?
<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>
<fb:login-button scope="public_profile,email" onlogin="checkLoginState();">
</fb:login-button>
<div id="status">
</div>

Figured it out. I changed
/me
to
/me?fields=age_range
Then I get the minimum age range value like this
response.age_range.min
So I can do
if(response.age_range.min >=18){
//if user age range is greater or equal to 18 do something here
}
I hope this is helpful to someone else.

Related

'statusChangeCallback' is not defined Facebook Javascript SDK Login Error

For New Developers who are trying to integrate facebook login and authentication in their websites, they might receive the error if they'll simply try to copy the tutorial from Facebook Help for Developers.
Error is : Uncaught ReferenceError: statusChangeCallback is not defined
Code:
<script>
function checkLoginState() {
FB.getLoginStatus(function (response) {
statusChangeCallback(response);
});
}
(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 = "https://connect.facebook.net/en_US/sdk.js";
fjs.parentNode.insertBefore(js, fjs);
}(document, 'script', 'facebook-jssdk'));
window.fbAsyncInit = function () {
FB.init({
appId: '<Your App ID>',
cookie: true,
xfbml: true,
version: 'v2.12'
});
FB.AppEvents.logPageView();
};
</script>
<fb:login-button scope="public_profile,email"
onlogin="checkLoginState();">
</fb:login-button>
<div id="status"></div>
The solution is that new developers are forgetting to write success callback function in their code. The problem occurs when they try to copy the code from Facebook's Guide that comes immediately after Facebook App Registration.
In your HTML define a div with id status <div id="status"></div> just before the <script> tag.
Please include the javascript method below for the API to work. I have written some console.log verbose text. You can delete this text and replace with yours.
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.
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 + '!';
});
} else {
// The person is not logged into your app or we are unable to tell.
document.getElementById('status').innerHTML = 'Please log ' +
'into this app.';
}
}

Can't Get Email from Facebook Login

I am working on putting Facebook login on my site. I'm not a very strong javascript coder, but usually find the code I need and, after some work and trial and error, get the results I need.
I got the login script working and the only thing I need (I think--remember javascript isnt my strong point so maybe you see some flaws here that I don't) is to obtain the email address from the login call. I have added 'email' to the scope and tried to access email from the response object as well as the user object. I know that email is valid because I am testing with my FB account and it was validated with email, not phone. But it comes up as undefined.
You'll see the spot where I am trying to get it in the myfacebooklogin function.
Anyone know how/why I cant access the email?
Also, does this code look solid?
Lastly, how would you best handle the session/state? In ASP (what the site is coded in--classic, not .NET) I use the session object if the person logged in traditionally. If they log out, I just set the session variable to "".But with this, would you just authenticate every page and use that as the session, or would you use the FB login to create an ASP session and use that?
Below is all of the code. The only other pieces are in the HTML body--a button to the myfacebooklogin function and a div that gets written to (which was part of the code I found so I left it in).
Thanks!
<script>
// 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'));
window.fbAsyncInit = function() {
FB.init({
appId : 'myAppId',
cookie : true, // enable cookies to allow the server to access
// the session
xfbml : true, // parse social plugins on this page
version : 'v2.8' // use graph api version 2.8
});
// 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.
//second parameter of FB.getLoginStatus is "true" to force a roundtrip to FB.
//if "true" not set, result will come from cache
//set "true" only when needed to save performance (for example, on login page)
FB.getLoginStatus(function(response) {
statusChangeCallback(response);
},true);
};
// 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();
alert('1');
} 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.';
alert('2');
} 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.';
alert('3');
}
}
function myFacebookLogin() {
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 + '.');
alert(response.name);
alert(response.id);
//alert(response.mail);
});
// FB.api('/me', function(user) {
// console.log(user.name + ': ' + user.email);
// alert(user.email);
// });
} else {
console.log('User cancelled login or did not fully authorize.');
}
}, {scope: 'public_profile, email', return_scopes: true}); //scope: 'publish_actions'
}
</script>
You need pass the fields in the url "/me" like:
FB.api('/me?fields=name,id,email', function(response) {

Django - How to setup and test facebook login before going to production?

So I am trying to add Facebook Login to my page but I am having some difficulties. I am trying to figure out how to test these features in development before I go to production but I don't completely understand how to do that.
I have followed the facebook api instructions so I think I have something that should work but I can't test. That code is below:
<script>
function fb_login() {
FB.login( function() {}, { scope: 'email,public_profile' } );
}
// 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 : '************',
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>
My App ID is correct in my application.
Here is my login button:
<img src="../../static/textchange/facebookloginbutton.png" border="0" alt="" height="42px;">
</div>
I made my own so I could choose another image.
So now when I try to login I get this error:
"Given URL is not allowed by the Application configuration: One or more of the given URLs is not allowed by the App's settings. It must match the Website URL or Canvas URL, or the domain must be a subdomain of one of the App's domains."
So I believe I have to choose another domain of some sort to test it? But I don't understand what I am supposed to choose? Do I have to start "hosting" so I can use a real domain? Can I do it locally?
I would appreciate any help in pushing me in the right direction.
Thanks.
You can configure your Valid OAuth redirect URIs under Client OAuth Settings in the Facebook Developers dashboard to allow whatever URL you are using locally. Or set the site URL to use your local URL.
your site URL should be http://localhost:8000/. I think the http:// matters
$scope.login = function() {
FB.login(function(resp) {
var args = { signed_request: resp.authResponse.signedRequest };
$http.get('/auth/facebook/callback', args).then(function(resp) {
// handle success
});
}, {scope: 'email,user_friends,user_location'});
};

facebook connect SDK sample: how to retrieve location and birthday?

I am using the offcial sample from facebook: it works fine, except I cannot retrieve the birthday and location.
<!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 : 'xxx',
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?fields=id,first_name,last_name,gender,location,email,birthday', {fields: 'name, email,gender,first_name,last_name,location,birthday' }, function(response) {
console.log(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 show-faces="false" scope="public_profile,email,user_birthday,user_location" size="medium" onlogin="checkLoginState();">Connect with facebook</fb:login-button>
<div id="status">
</div>
</body>
</html>
This works fine but no borthday nor location in response.
I spent a lot of time and it looks that nowdays to retrieve these informations I need to nowdays to REVIEW the application before accessing these data
https://developers.facebook.com/docs/facebook-login/review/what-is-login-review
Is this correct: do I need to submit the application for review or is it something wrong I am doing ?
Yes, it's true, and it's all in the docs:
https://developers.facebook.com/docs/facebook-login/review
https://developers.facebook.com/docs/apps/review
But, if you're using the an admin/tester/developer of the said app, you are able to give and test these permission with your app. Only if third parties will need to access the app, you'll need to pass Login Review.

Access token doesn't contain any scopes

I want to get a list of my friends with their name, current location and profile picture. I executed the query and the access token (with the required scope parameters) in the GRAPH API explorer tool and it works fine --> https://developers.facebook.com/tools/explorer?method=GET&path=me%2Ffriends%3Ffields%3Dname%2Clocation%2Cpicture
But everytime I execute the application, I get an access token without the required scope (it has none). How can I send my scopes to the access token?
Scope I want to give to the access token: Scopes: friends_location user_location user_relationships
I work in a localhost environment.
<html>
<head></head>
<body>
<div id="fb-root"></div>
<script src="//connect.facebook.net/en_US/all.js"></script>
<script js.src = "//connect.facebook.net/en_US/all/debug.js"></script>
<script>
var accessToken
var uid
window.fbAsyncInit = function() {
FB.init({
appId : '493774134048550', // App ID
channelUrl : '//localhost/Facebook', // 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.
uid = response.authResponse.userID;
accessToken = response.authResponse.accessToken;
console.log(uid);
console.log(accessToken);
testAPI(function(response) {
// handle the response
uid = response.authResponse.userID;
accessToken = response.authResponse.accessToken;
console.log(uid);
console.log(accessToken);
}, {scope: 'friends_location, user_location, user_relationships'});
} 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();
FB.login(function(response) {
// handle the response
uid = response.authResponse.userID;
accessToken = response.authResponse.accessToken;
console.log(uid);
console.log(accessToken);
}, {scope: 'friends_location, user_location, user_relationships'});
} 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();
FB.login(function(response) {
// handle the response
uid = response.authResponse.userID;
accessToken = response.authResponse.accessToken;ยต
console.log(uid);
console.log(accessToken);
}, {scope: 'friends_location, user_location, user_relationships'});
}
}, {scope: 'friends_location, user_location, user_relationships'});
};
// 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);
//});
///me/friends?fields=name,location,picture&accesstoken=CAACEdEose0cBAFhNXAYgMjfAPWNxGZAdNdEJ6s2GAyIQp4zicpV0ZBZCeVINbiLvIxaFl33N0I1gZAZArREsHmOGiqQX2HPaNZCiU4W4Nq3VA12TrreKfeOtFSMvmZC8c1qYqu85NZAzzWDXWH5foXIWfPFk1ZBScNbAZD
FB.api('/'+uid+'/friends?fields=name,location,picture&accesstoken='+accessToken, function(response) {
//FB.api('/'+uid+'/friends?fields=name,location,picture&accesstoken=CAACEdEose0cBAJayThSg77Ydil76EM0W4zuJ9l29yKoIxlu6g37ZAX1CWQhpTStBL48xoX5g0Bbe8Va4wr6qqT2ft5tZBoNDZCWFYF7TtwmBnTDOSGWruOp0pSS9Ws1phfl5wiFbHeZAyUbdZBDdx3GLBHeysn6EZD', function(response) {
var teller1 = 0;
console.log('Good to see you, ' + response.name + '.');
console.log(response.data);
for (var i=0;i<response.data.length;i++)
{
if(response.data[i].name && response.data[i].location && response.data[i].picture){
console.log(response.data[i].name);
console.log(response.data[i].location.name);
console.log(response.data[i].picture.data.url);
teller1++;
}
//<img border="0" src="console.log(response.data[0].picture.data.url)">
}
console.log(teller1); //aantal gebruikers met naam, locatie en picture
console.log(response.data.length); //aantal gebruikers in totaal
});
}
//Logout
function fbLogout() {
FB.init();
FB.logout(function (response) {
//Do what ever you want here when logged out like reloading the page
window.location.reload();
});
}
</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/ -->
<fb:login-button show-faces="true" width="200" max-rows="1"></fb:login-button>
<span id="fbLogout" onclick="fbLogout()"><a class="fb_button fb_button_medium"><span class="fb_button_text">Logout</span></a></span>
</body>
</html>
Replace the code under response.status === 'connected' with this. Remove all other parts in the original code where the scope was added. (you only have to add it here)
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.
if(accessToken)
{
// alert("Connected WITH accesToken");
testAPI();
}
else{
// alert("Connected WITHOUT accesToken");
FB.login(function(response) {
// handle the response
uid = response.authResponse.userID;
accessToken = response.authResponse.accessToken;
console.log(uid);
console.log(accessToken);
}, {scope: 'friends_location, user_location, user_relationships'});
}