Facebook api work only for me - javascript

I'm creating frame app for facebook.
Following code work good for me:
function changeToHome() {
try {
var time = new Date();
FB.api("/me", {fields: "id,first_name,last_name,picture"}, function(response)
{
window.location = '#home';
var fname = encodeURIComponent(response.first_name);
var lname = encodeURIComponent(response.last_name);
var avatar = encodeURIComponent(response.picture.data.url);
var u = '?useradd='+response.id+"&fn="+fname+"&ln="+lname+"&p="+avatar+"&t="+time.getTime();
document.getElementById('game_frame').src=('drop.html'+u);
$.ajax({
url: 'stat-api.php'+u
}).done(function() {
//alert("done");
});
});
} catch(ex) {
//alert(ex);
}
}
But if i try to test it trought other acounts the facebook api doesn't work( I tried different browsers and got the same result.

Try to enable (or disable) sandbox mode.

Solved! It didn't authenticate my app! It was a reason.
Include folowing in window.fbAsyncInit = function() {...}
FB.getLoginStatus(function(response) {
if (response.status === 'connected') {
//var uid = response.authResponse.userID; //FACEBOOK_ID
//var accessToken = response.authResponse.accessToken;/ //ACCESS TOKEN
if (response.authResponse) {
// logged in and connected user, someone you know.
// YOUR CODE HERE
changeToHome()
}
}else {
attemptLogin();
}
});
function attemptLogin(){
FB.login(function(response) {
if (response.authResponse) {
// YOUR CODE HERE
changeToHome()
} else {
//if user didn't logged in or didn't authorize your application
}
}, {scope: 'offline_access,publish_stream,manage_pages,publish_actions,user_games_activity'}); //YOUR PERMISSION
}

Related

Social Login in Phonegap

I am stuck with Social login (Facebook, Google and twitter) through Phonegap.
I have googled and found so many solutions, but they don't work on either platform (i.e: android or iOS).
Does any one have implemented social login in his/her app using phonegap?
If any one could provide me the running code, that would be appreciated.
Thanks,
Sabir
I know it's probably late to answer your particular question but I have had the same issue - all of the current (September 2016) scripts, snippets and libraries for social login in PhoneGap/Cordova that I have tried did not work so I made some simple functions from scratch which may still be useful to people ending up here. You can use them to log the user in with LinkedIn, Facebook and Google(+). I have also made some simple functions that retrieve some basic user information from the access token that is returned by logging the user in with the given network. You can examine the functions but they usually save the token or/and the user data to localStorage for later usage. They have been tested in September 2016 and work perfectly. I hope that this would help other people who also land on failing snippets around the web.
You can just insert the code and use the functions whenever you want. It requires jQuery and PhoneGap's InAppBrowser (besides having made apps/clients in the social media in order to fill the app id and app secret).
As a side note, it is not the best move to store the client secret directly in the PhoneGap application as the source can be viewed by malevolent people.
The code can be refactored at many places, so feel free to do that, but it does the trick. You may also have to handle cases where the user cancels the login process.
var facebookLogin = function(appId, appSecret, successCb,errCb) {
/*$.get("https://graph.facebook.com/oauth/access_token?client_id=" + appId + "&client_secret=" +appSecret + "&grant_type=client_credentials", function(res) {
if (res.indexOf("access_token=") !== -1) {
successCb(res.replace("access_token=", "").trim());
}
else {
errCb(res);
}
})
*/
var ref = window.open("https://www.facebook.com/dialog/oauth?display=popup&response_type=token&client_id="+appId+"&redirect_uri="+"http://anyurlhere.com", "_blank", "location=no");
ref.addEventListener("loadstop", function(evt) {
if (evt.url.indexOf("anyurlhere.com") !== -1) {
if (evt.url.indexOf("#access_token") !== -1) {
localStorage.fbToken = evt.url.split("#access_token=")[1];
ref.close();
ref.addEventListener("exit", function() {
successCb(localStorage.fbToken);
})
}
}
})
}
var linkedinLogin = function(appId,appSecret,successCb,errCb) {
var ref = window.open("https://www.linkedin.com/oauth/v2/authorization?response_type=code&client_id="+appId+"&redirect_uri="+(encodeURI("http://anyurlhere.com"))+"&state=987654321&scope=r_basicprofile", "_blank", "location=no");
ref.addEventListener("loadstop", function(evt) {
if (evt.url.indexOf("anyurlhere.com") !== -1) {
if (evt.url.indexOf("code=") !== -1) {
var code = evt.url.split("code=")[1];
code = code.split("&")[0];
//TODO: get actual token to access user profile
$.post("https://www.linkedin.com/oauth/v2/accessToken", {"grant_type": "authorization_code", "code": code, "redirect_uri":encodeURI("http://anyurlhere.com"), "client_id":appId,"client_secret":appSecret}, function(data) {
for (key in data) {
if (key == 'access_token') {
localStorage.linkedinToken = data[key];
ref.close();
ref.addEventListener("exit", function() {
successCb(localStorage.linkedinToken);
})
}
}
})
}
}
})
}
var googleLogin = function(appId, appSecret, successCb, errCb) {
var ref = window.open("https://accounts.google.com/o/oauth2/v2/auth?response_type=token&client_id=" + appId + "&redirect_uri="+encodeURI("http://anyurlhere.com")+"&scope="+encodeURIComponent("email profile")+"&state=profile", "_blank", "location=no");
ref.addEventListener("loadstop", function(evt) {
if (evt.url.indexOf("anyurlhere.com") !== -1) {
if (evt.url.indexOf("access_token=") !== -1) {
var accessToken = evt.url.split("access_token=")[1];
accessToken = accessToken.split("&")[0];
localStorage.gToken = accessToken;
ref.close();
ref.addEventListener("exit", function() {
successCb(localStorage.gToken);
})
}
}
})
}
var getGoogleInfo = function(successCb, errCb) {
//get basic user profile
$.get("https://www.googleapis.com/oauth2/v1/userinfo?alt=json&access_token=" + localStorage.gToken, function(userInfo) {
successCb(userInfo);
})
}
var getFacebookInfo = function(successCb, errCb) {
//get basic user profile-name
$.get("https://graph.facebook.com/me?fields=email,name,picture&access_token=" + localStorage.fbToken, function(userInfo) {
var myInfo = {};
if (userInfo.name) {
myInfo.name = userInfo.name;
}
if (userInfo.email) {
myInfo.email = userinfo.email;
}
if (userInfo.picture) {
myInfo.picture = userInfo.picture.data.url;
}
localStorage.myInfo = JSON.stringify(myInfo);
successCb(myInfo);
// localStorage.myInfo = myInfo;
})
}
//get basic data for linked in
var getLinkedinInfo = function(successCb, errCb) {
$.ajax({
url: "https://api.linkedin.com/v1/people/~?format=json",
headers: {
"Authorization": "Bearer " + localStorage.linkedinToken
},
success: function(userInfo) {
var myInfo = {};
if (userInfo.firstName && userInfo.lastName) {
myInfo.name = userInfo.firstName + " " + userInfo.lastName;
}
if (userInfo.headline) {
myInfo.linkedinHeadline = userInfo.headline;
}
localStorage.myInfo = JSON.stringify(myInfo);
successCb(myInfo);
},
fail: function(err) {
alert(err);
for (key in err) {
alert(key);
alert(err[key]);
}
}
})
}
//example of logging in the user with Google + and getting his/her data
googleLogin("93-54932-423-fkfew.apps.googleusercontent.com", "", function(accessToken) {
getGoogleInfo(function(userInfo) {
var myInfo = {};
alert(userInfo.name);
if (userInfo.email) {
myInfo.email = userInfo.email;
}
if (userInfo.name) {
myInfo.name = userInfo.name;
}
if (userInfo.given_name) {
myInfo.firstName = userInfo.given_name;
}
if (userInfo.familyName) {
myInfo.familyName = userInfo.family_name;
}
if (userInfo.picture) {
myInfo.picture = userInfo.picture;
}

Retrieve data from facebook api for a user

Hey so I am having a hard time understanding how to retrieve data from a user who logs in to my site, I am currently using the javascript sdk but I am trying to figure out how to request the user's data correctly and then how to send it to my server side... I thought it might be something like
req.body.id
for the facebook user id, but I do not think that is it...
Here is the javascript code on my login page.
script(src='//connect.facebook.net/en_US/all.js')
div#fb-root
script.
window.fbAsyncInit = function() {
// init the FB JS SDK
FB.init({
appId: 'blank', // App ID from the app dashboard
//channelUrl:'//WWW.YOUR_DOMAIN.COM/channel.html', // Channel file for x-domain comms
status : true, // Check Facebook Login status
xfbml : true, // Look for social plugins on the page
cookie: true
});
};
(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));
function authUser() {
FB.login(checkLoginStatus, {scope:'email, user_likes'});
function checkLoginStatus(response) {
if(response && response.status == 'connected') {
alert('User is authorized');
document.getElementById('loginButton').style.display = 'none';
console.log('Access Token: ' + response.authResponse.accessToken);
var uid = response.authoResponse.userID;
var accessToken = response.authoResponse.accessToken;
testAPI();
getFBData ();
} else {
alert('User is not authorized');
document.getElementById('loginButton').style.display = 'block';
}
}
}
function testAPI() {
console.log('Welcome! Fetching your information.... ');
FB.api('/me', function(response) {
console.log('Good to see you, ' + response.name + '.' + response.id);
});
};
function getFBData () {
FB.api('/me', function(data){
alert(data.first_name + data.last_name + data.id);
})
};
function fbLogout() {
FB.logout(function (response) {
//window.location.replace("http://stackoverflow.com"); is a redirect
window.location.reload();
});
}
div.centerContent
form(method="POST", action="/login")
fieldset
legend Login
input(type="email", name="email", placeholder="Email", maxlength="20", value= "")
br
input(type="password", name="password", id="password", placeholder="Password", maxlength="20", value= "")
br
input.btn.btn-primary(type="submit", name="login", value="Login")
a(href="/")
button.btn(type="button") Cancel
<fb:login-button show-faces="true" width="200" max-rows="1"></fb:login-button>
button#fbLogout(type="button", onclick="fbLogout()") Logout of FB
button#fbLogin(type="button", onclick="authUser()") Login to FB
It is in jade but it should be readable.
Any help or direction on how to actually grab a user's info(in particular I am looking for a profile picture, access token, user id, first and last name)
Thanks.
EDIT:
I am using node.js and mongodb on the backend
There are many issues with your code.
The biggest one I think is that you don't use the reponse inside the callback!
Others are just wrong spelling of variables like authResponse and authoResponse.
Try this:
function authUser() {
FB.login(checkLoginStatus, {scope:'email, user_likes'});
function checkLoginStatus(response) {
if(!response || response.status !== 'connected') {
alert('User is not authorized');
document.getElementById('loginButton').style.display = 'block';
} else {
alert('User is authorized');
document.getElementById('loginButton').style.display = 'none';
console.log('Access Token: ' + response.authResponse.accessToken);
//This has to be in your callback!
var uid = response.authResponse.userID;
var accessToken = response.authResponse.accessToken;
testAPI();
getFBData();
}
}
}
function testAPI() {
console.log('Welcome! Fetching your information.... ');
FB.api('/me', function(response) {
console.log('Good to see you, ' + response.name + '.' + response.id);
});
};
function getFBData () {
FB.api('/me', function(data){
alert(data.first_name + data.last_name + data.id);
})
};
function fbLogout() {
FB.logout(function (response) {
//window.location.replace("http://stackoverflow.com"); is a redirect
window.location.reload();
});
}
The first thing I can tell from your code is that your login function should be made asynchronous like this:
FB.login(function(response) {
var uid = response.authoResponse.userID;
var accessToken = response.authoResponse.accessToken;
}, {scope: 'email,user_likes'});
Also, when you mention that you would like to pass FB user info to the server side, when a user logs in on the client side, the server side information should already be accessible through the FB PHP SDK. The documentation for this can be found here: https://developers.facebook.com/docs/reference/php/
An example of a PHP call that would provide you with the user info on the server is:
$me = $Facebook->api('/me');

Use user credentials to login to facebook using javascript sdk

I am using Javascript sdk with a facebook app to create login page for user.
FB.login prompts the user to enter facebook username and password. I have saved all the info such as user_id, Access_token, and all info. However, when the user logout. I want to login to facebook without the need to re-enter username and password again. i want to use the user-id and access token to login directly using the javascript API.
Thanks
function updateButton(response) {
button = document.getElementById('fb-auth');
userInfo = document.getElementById('user-info');
testbut = document.getElementById('test');
var rr = getResponse("user_profile.xml");
if(rr != null)
{
response = rr;
}
if (response.authResponse) {alert('me/permissions/?access_token='+
response.authResponse.accessToken);
FB.api('me/permissions/?access_token='+ response.authResponse.accessToken
,function(response)
{
for (var name in response) {
alert(response.data);
}
alert(response);
});
//user is connected
FB.api('/me', function(info) {
login(response, info);
});
button.onclick = function() {
FB.logout(function(response) {
logout(response);
});
};
} else {
//user is not connected
button.innerHTML = 'Login';
button.onclick = function() {
FB.login(function(response) {
if (response.authResponse) {
FB.api('/me', function(info) {
login(response, info);
});
} else {
//user cancelled login or did not grant authorization
showLoader(false);
}
},
{scope:'email,user_birthday,status_update,publish_stream,user_about_me'});
}
}
}
// run for the current status and whenerve it is changed
FB.getLoginStatus(updateButton);
FB.Event.subscribe('auth.statusChange', updateButton);
};
(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 login(response, info){
if (response.authResponse) {
ajaxFunction(response);
var accessToken = response.authResponse.accessToken;
userInfo.innerHTML = '<img src="https://graph.facebook.com/' + info.id
+ "<br /> Your Access Token: " + accessToken;
button.innerHTML = 'Logout';
document.getElementById('other').style.display = "block";
}
}
function logout(response){
userInfo.innerHTML = "";
document.getElementById('debug').innerHTML = "";
document.getElementById('other').style.display = "none";
}
You have to store User access token in your database to user for next time.
Here is some small hint to pass access token using javascript sdk
FB.api('me/permissions/?access_token=Your access token',function(response){console.log(response)});
Chiming in a bit late, but my guess is you are trying to login using an expired or invalidated short-term access token. For future logins, you should convert the short-term access token to a long-term access token, good for about 60 days. The conversion to a long-term token needs to happen on your server as it requires your app-secret. Details are here. The long-term token is what you should be storing in your database (or similar) for future use.

Facebook oauth javascript redirect resulting in endless loop

I want to redirect users to the oauth page if they have removed any of the permissions my app requires.
For some reason the below code results in an endless loop when I try to redirect from the FB.api callback function. Any ideas how I can fix this?
var perms = ['publish_actions', 'email', 'user_birthday', 'user_location'],
permsString = perms.join(','),
permissionsUrl = 'https://www.facebook.com/dialog/oauth';
permissionsUrl += '?client_id=' + config.facebook.appId;
permissionsUrl += '&redirect_uri=' + encodeURI(canvasUrl);
permissionsUrl += '&scope=' + permsString;
FB.getLoginStatus(function (response) {
if (response.status === 'connected') {
FB.api('/me/permissions', function(response) {
// using underscore here...
var keys = _.keys(response.data[0]),
diff = _.difference(perms, keys);
// send the user through the auth again if they've removed any of the perms we need
if (diff.length) {
window.location.href = permissionsUrl; // results in an endless redirect loop
// window.location.href = 'http://randomwebsite.com'; // does redirect successfully!!!!
}
});
}
}, true);
It's been a while since I did this but from memory I solved it with something like this:
var redirectMe = function (link) {
window.location.href = link;
};
FB.getLoginStatus(function (response) {
if (response.status === 'connected') {
FB.api('/me/permissions', function(response) {
if (true) {
redirectMe('http://www.browsehappy.com');
}
});
}
}, true);

"FB is not defined" in Internet explorer (Facebook API)

I get this error "FB is not defined" when i try to run this code in Internet Explorer:
FB.getLoginStatus(function(response) {
if (response.status === 'connected') {
var accessToken = response.authResponse.accessToken;
var uid = response.authResponse.userID;
share(accessToken,uid);
} else {
FB.login(function(response) {
if (response.authResponse) {
FB.api('/me', function(user) {
var uid = user.id;
var name = user.name;
var email = user.email;
var gender = user.gender;
var birthday = user.birthday;
var username = user.username;
var link = user.link;
});
} else {
alert('Du skal acceptere');
}
}, {scope: 'email', display: 'iframe'});
}
});
Anyone have any idea how I can fix this. It's working in every other browser than Internet Explorer 7&8
From the fiddle, the reason you cannot get it to work in IE7 and 8 is because of the trailing space in the comma separated list of oauth : true,} in your FB.init(). Some browsers are forgiving of this syntax error, but others like IE are not. Fix the syntax issue and you should be fine.

Categories

Resources