I am already using this script but I didn't get hometown and location when I use API the hometown and location is undefined message appears please give example code and how to get user mobile number in Facebook API:
function login() {
FB.login(function(response) {
if (response.authResponse) {
// connected
testAPI();
} else {
// cancelled
}
}, { scope: 'email,user_birthday,user_location,user_hometown' });
}
function testAPI() {
console.log('Welcome! Fetching your information.... ');
FB.api('/me', function(response) {
console.log('Good to see you, ' + response.name + '.' + ' Email: ' + response.email + ' Facebook ID: ' + response.id);
//console.log('Good to see you, ' + response.name + '.');
var userfirstName=response.first_name;
var lastName=response.last_name;
var useremail=response.email;
var usersex=response.gender;
var userbithday=response.birthday;
var hometown= response.hometown.name;
var location= response.location.name;
alert(hometown);
});
}
<fb:login-button show-faces="false" width="200" max-rows="1" scope="email,user_birthday,user_location,user_hometown" onclick="testAPI();" onlogin="Log.info('onlogin callback')">
Sign Up with Facebook
</fb:login-button>
but can't get hometown and location, please help give any example.
You are using wrong permissions, try this:
{ scope: 'email,user_birthday,user_location,user_hometown' }
Another thing, to access the hometown use this:
var hometown= response.hometown.name;
Also, instead of /me; mention explicitly the fields you want using the fields parameter; just like: /me?fields=hometown
Graph API Explorer
Related
I am implementing Google log in for the first time as described here and here.
I am using HTML with Javascript.
The problem that needs solving is as follows: How can I, after the initial login, on a different page (say a landing page, or portal that the user sees after logging in), check if the user is logged in? Is there a service I can call to check the user's login in status with my app key or something similar?
I assume I would have to include the google API on each page.
Login Page Code:
Script In Head (Code from Google's tutorial listed above):
<head>
....
<script src="https://apis.google.com/js/platform.js" async defer></script>
<script>
function onSignIn(googleUser)
{
var profile = googleUser.getBasicProfile();
console.log('ID: ' + profile.getId());
console.log('Name: ' + profile.getName());
console.log('Image URL: ' + profile.getImageUrl());
console.log('Email: ' + profile.getEmail());
alert(profile.getName());
}
function logout()
{
alert('logging out');
var auth2 = gapi.auth2.getAuthInstance();
auth2.signOut().then(function () {
console.log('User signed out.');
});
}
...
</head>
Code In Body (1st line from Google's tutorial listed above, 2nd line to trigger logout test)
<body>
...
<div class="g-signin2" data-onsuccess="onSignIn"></div>
<div onmousedown="logout()">Logout</div>
...
</body>
Is there some way I can include the google API on another page, and then call some check login status function? Or another way to concretely tell if the user is logged in or out?
You do not need to store anything on local storage. The library allows you to check if the user is logged in or not using the isSignedIn.get() on the auth2 of the gapi object.
Load the JavaScript library, make sure you are not deferring the load :
<script src="https://apis.google.com/js/platform.js"></script>
Then initialize the library and check if the user is logged in or not
var auth2;
var googleUser; // The current user
gapi.load('auth2', function(){
auth2 = gapi.auth2.init({
client_id: 'your-app-id.apps.googleusercontent.com'
});
auth2.attachClickHandler('signin-button', {}, onSuccess, onFailure);
auth2.isSignedIn.listen(signinChanged);
auth2.currentUser.listen(userChanged); // This is what you use to listen for user changes
});
var signinChanged = function (val) {
console.log('Signin state changed to ', val);
};
var onSuccess = function(user) {
console.log('Signed in as ' + user.getBasicProfile().getName());
// Redirect somewhere
};
var onFailure = function(error) {
console.log(error);
};
function signOut() {
auth2.signOut().then(function () {
console.log('User signed out.');
});
}
var userChanged = function (user) {
if(user.getId()){
// Do something here
}
};
Don't forget to change the app id
You can stringify a custom userEntity object and store it in sessionStorage where you can check it anytime you load a new page. I have not tested the following but it should work (doing something similar with WebAPI tokens in the same way)
function onSignIn(googleUser)
{
var profile = googleUser.getBasicProfile();
console.log('ID: ' + profile.getId());
console.log('Name: ' + profile.getName());
console.log('Image URL: ' + profile.getImageUrl());
console.log('Email: ' + profile.getEmail());
var myUserEntity = {};
myUserEntity.Id = profile.getId();
myUserEntity.Name = profile.getName();
//Store the entity object in sessionStorage where it will be accessible from all pages of your site.
sessionStorage.setItem('myUserEntity',JSON.stringify(myUserEntity));
alert(profile.getName());
}
function checkIfLoggedIn()
{
if(sessionStorage.getItem('myUserEntity') == null){
//Redirect to login page, no user entity available in sessionStorage
window.location.href='Login.html';
} else {
//User already logged in
var userEntity = {};
userEntity = JSON.parse(sessionStorage.getItem('myUserEntity'));
...
DoWhatever();
}
}
function logout()
{
//Don't forget to clear sessionStorage when user logs out
sessionStorage.clear();
}
Of course, you can have some internal checks if the sessionStorage object is tampered with. This approach should work with modern browsers like Chrome and Firefox.
To check is user Signed-in use:
gapi.auth2.getAuthInstance().isSignedIn.get()
Adding on to Joseph's answer above, you can then get information about the user by calling auth2.currentUser.get().getBasicProfile().
if (auth2.isSignedIn.get()) {
googleUserProfile = auth2.currentUser.get().getBasicProfile()
console.log('ID: ' + googleUserProfile.getId());
console.log('Full Name: ' + googleUserProfile.getName());
console.log('Given Name: ' + googleUserProfile.getGivenName());
console.log('Family Name: ' + googleUserProfile.getFamilyName());
console.log('Image URL: ' + googleUserProfile.getImageUrl());
console.log('Email: ' + googleUserProfile.getEmail());
}
From the docs: https://developers.google.com/identity/sign-in/web/people
according to the link from Phyrik post (https://developers.google.com/identity/sign-in/web/people) -
google stopped supporting the Sign-In Javascript web auth API:
We are discontinuing the Google Sign-In JavaScript Platform Library for web. The library will be unavailable for download after the March 31, 2023 deprecation date. Instead, use the new Google Identity Services for Web.
By default, newly created Client IDs are now blocked from using the older Platform Library, existing Client IDs are unaffected. New Client IDs created before July 29th, 2022 can set plugin_name to enable use of the Google Platform Library.
I have created a custom action that I want to allow users to post to their timeline with e.g. {User} read {Article}. I can get this to work fine when I do a post using the sample URL like this :
FB.api('/me/fbsite:actionname' +
'?object=http://samples.ogp.me/356694057772404&access_token=abc','post'
But when I replace the sample URL with my own URL I get the error 'The session was invalidated explicitly using an API call'. Can anybody please advise?
EDIT : Changed my Javascript to this, but I now get 'Invalid OAuth Access Token' :
<script type="text/javascript">
function redeem() {
FB.api('/me/fbsite:actionname' +
'?object=http://samples.ogp.me/356694057772404&access_token=\' + <%=UserManager.Current.FB.accessToken %> + \'', 'post',
function (response) {
var msg = 'Error occured';
if (!response || response.error) {
if (response.error) {
msg += "\n\nType: " + response.error.type + "\n\nMessage: " + response.error.message;
}
alert(msg);
}
else {
alert('Post was successful! Action ID: ' + response.id);
}
});
}
That might be because you are using the same access token in same session. So try logging out and log back in, get a new FB access token, and try the query using the new access token you got, that should work as expected.
I have integrated Facebook login in my website using javascript SDK.. Everything is working fine except for the auth dialog box, which is showing only once for a user.Next time when the user logs it redirects without showing the auth dialog box.I want to show the auth dialog box each time the user logs.
This is the code I am using
window.fbAsyncInit = function() {
FB.init({
appId : 'xxxxxxxx',
status : true,
cookie : true,
xfbml : true,
oauth : true
});
if (window!=window.top) {
FB.Canvas.setAutoResize();
};
FB.getLoginStatus(function(response) {
if (response.authResponse) {
window.FBlogin = function(){
FB.login(function(response) {
if (response.authResponse) {
FB.api('/me', function(response) {
console.log('Good to see you, ' + response.name + '.');
var query = FB.Data.query('select name,username, email, hometown_location, sex, pic_square from user where uid={0}', response.id);
query.wait(function(rows) {
//document.getElementById('name').innerHTML = '<img src="' + rows[0].pic_square + '" alt="" />';
var name=rows[0].name;
var email=rows[0].email;
var uid=response.id;
var username=rows[0].username;
var pic=rows[0].pic_square;
});
});
}
else {
alert("error");
}
}, {scope: 'email'});
};
}
else {
var authbox = document.getElementById('FBauth');
authbox.innerHTML="";
var a = document.createElement('a');
a.setAttribute("href","javascript:void();");
a.setAttribute("onclick","FBlogin();");
authbox.appendChild(a);
window.FBlogin = function(){
FB.login(function(response) {
if (response.authResponse) {
FB.api('/me', function(response) {
console.log('Good to see you, ' + response.name + '.');
var query = FB.Data.query('select name,username, email, hometown_location, sex, pic_square from user where uid={0}', response.id);
query.wait(function(rows) {
var name=rows[0].name;
var email=rows[0].email;
var uid=response.id;
var username=rows[0].username;
var pic=rows[0].pic_square;
});
});
}
}, {scope: 'email'});
};
}
});
FB.Event.subscribe('auth.login', function () {
FB.api('/me', function(response) {
console.log('Good to see you, ' + response.name + '.');
var query = FB.Data.query('select name,username,email, hometown_location, sex, pic_square from user where uid={0}', response.id);
query.wait(function(rows) {
var name=rows[0].name;
var uid=response.id;
var email=rows[0].email;
var username=rows[0].username;
var pic=rows[0].pic_square;
var page='';
$('<input />').attr({'type':'hidden', 'id':'fbname','value':email}).appendTo('#fbaccess');
});
})
});
FB.Event.subscribe('auth.logout', function(response) {
});
};
Everything is working fine except for the auth dialog box, which is showing only once for a user.Next time when the user logs it redirects without showing the auth dialog box.
If the user is already connected to your app and has given all of the requested permissions – then this is the intended behavior.
Calling FB.login again in this situation will open the popup, and close it again immediately.
I want to show the auth dialog box each time the user logs.
I can’t see the benefit of an app behaving in such a way.
Anyways, there is a parameter to explicitly request that the user re-authenticate: auth_type=reauthenticate. This will force the user to re-enter their password. See https://developers.facebook.com/docs/authentication/reauthentication/#client-side for details.
But I’m not sure that this is what you actually want.
Another way could be to delete permissions via your app, and then have them requested again via the scope parameter. That should bring up the Auth dialog again. For details on that, see https://developers.facebook.com/docs/reference/api/user/#permissions
In this script
function fql(){
FB.api('/me', function(response) {
var query = FB.Data.query('select uid, name, email from user where uid={0}', response.id);
query.wait(function(rows) {
document.getElementById('name').innerHTML =
'Your name: ' + rows[0].name + "<br />" +
+ rows[0].email + "<br />" + rows[0].uid;
});
});
}
Function returns name and pic, but email value is NaN. App requires basic data and email (it was set in app properties/Auth dialog) but i cant get user email.
When I tested this query in Facebook test console, I've got email field with correct value.
Check that in Test Console and on your site you use the same application id and ensure that user have granted the email permission to your application!
This can be done with simple Graph API call:
FB.api('/me/permissions', function(response){
if (response && response.data){
var userPermissions = response.data.shift();
if (userPermissions.email){
alert('User is granted email permission');
} else {
alert('User is NOT granted email permission');
}
} else {
// No response or results from the Graph API
}
});
Couple of things you should be aware of!
FB.Data.* is gone! It's deprecated, undocumented and should not be used anymore! It's just a matter of time for it to disappear from the JavaScript SDK code...
You just doesn't want extra call just to figure the id of current user (most chances that you already have it, just check FB.getUserID()), in FQL use me() to refer to current user.
Rewrite your usage of FB.Data.* and query.wait with:
FB.api('/fql', {q:'YOUR_FQL_QUERY_HERE'}, function(response){
var rows = response.data;
});
In your case same results may be received by Graph API call without usage of FQL:
FB.api('/me', {fields: 'id,name,email'}, function(response){
// response -> {id: UID, name: 'User Name', email: 'user#email.dz'}
console.log(response);
});
Here is my code::
//if user is logged in - do this
function login() {
FB.api('/me', function(response) {
document.getElementById('fb-info-block').innerHTML =
"Welcome, " + response.name + ".<br /><br />" +
"<fb:like href = 'www.whitbreaddesign.com' show_faces = 'false' width = '100' action = 'like' colorscheme = 'light'></fb:like>";
});
}
Can someone tell me how to add the users facebook profile within this code...I already figured out how to retrieve their name with "Welcome, "+ response.name+"
Any ideas..thanks a bunch...
document.getElementById('something').innerHTML = '<img src="http://graph.facebook.com/' + response.id + '/picture" />';
You need to list fields you are interested in as a second parameter to FP.api:
FB.api("/me", {fields: "id,name,picture"}, function(response) {
console.log(response.id, response.name, response.picture);
});
Here is a list of all available fields
You could use the FBML tag for profile pics:
var profile_pic_html = '<fb:profile-pic></fb:profile-pic>';
Just add that anywhere on the page, and as long as you have FB Connect's xd_receiver setup, that will show the currently logged in user's profile pic. To show profile pics by UID use:
var profile_pic_html = '<fb:profile-pic uid="'+some_uid+'" ></fb:profile-pic>';
You need to call
FB.XFBML.Parse() so that your updated FBML can be parsed into HTML by facebook's javascript.
You may be missing that.
Maybe just use XFBML?:
<fb:name uid="loggedinuser" use-you="no"></fb:name>
<fb:profile-pic uid="loggedinuser" size="square" facebook-logo="true"></fb:profile-pic>
Here's an example: http://fbrell.com/xfbml/account-info
you should use "me.id" instead of "response.id":
document.getElementById('something').innerHTML = '<img src="http://graph.facebook.com/' + me.id + '/picture" />';