Trying to retrieve facebook user email using facebook connect for cordova 3.2 - facebook

I'm developing an android app wherein it requires to be logged into the app via facebook. I'm using facebook connect for cordova 3.2 and its working fine.But the problem is I'm not able to get the user's email address. I tried scope : email , permissions : 'email', but it simply does not work.I have installed facebook sdk for android the cordova 3.2 version and configured that with my project. I call the facebook login uri with a button click event.
var facebookConnect;
$("#facebookfbtn").unbind("click").click(function () {
facebookConnect.login(loginCallback, true);
});
document.addEventListener("deviceready", deviceready, false);
function deviceready(){
facebookConnect = window.plugins.facebookConnect;
}
loginCallback = function(result){
alert(result);
if(result == "OPENED")
{
facebookConnect.me(meCallback);
}
}
logoutCallback = function(result){
alert(result);
}
meCallback = function(result){
alert(JSON.stringify(result));
//var test = JSON.stringify(result);
alert('Good to see you, ' + result.name + '!' + '\n'+ 'Your Details :'+ '\n'+'Location:'+result.location+'\n'+'Email: '+result.email);
}
statusCallback = function(result){
alert(result);
}

Related

Meteor facebook login - user is not show in SignIn space

I try to add Facebook login function on my app, it work but I have some problems
I start with:
meteor add accounts-password
meteor add accounts-ui
meteor add service-configuration
meteor add accounts-facebook
Then I write a test app on facebook, adding login and get my appId and secret
I copy documentation's code to configure settings (server side) and I put my appId and secret
ServiceConfiguration.configurations.upsert(
{ service: "facebook" },
{
service : "facebook",
appId: '123456789012345678',
secret: '123456789012345678123456789012345678123456789012345678',
loginStyle : "popup",
requestPermissions: ['email','user_friends']
}
);
I try to login with facebook and I have (showing in console.log) all the data I need (the picture is the picture profile in facebook), but the SignIn name is nto show in the top of the app
When I signin with a normal email password login I have no problem
The problem was in this function:
Accounts.onCreateUser(function(options, user) {
var imgAvatar = "/img/user.png";
var username = "NewPlayer_" + Math.floor(Math.random() * (9000 - 1000) + 1000);
if (user.hasOwnProperty('services') && user.services.hasOwnProperty('facebook') ) {
imgAvatar = "http://graph.facebook.com/" + user.services.facebook.id + "/picture/?type=small";
username = user.services.facebook.name;
}
return user;
});
I discover the correct way to use this function in this post
Accounts.onCreateUser((function(_this) {
return function(options, user) {
options = {
username: 'pippo'
}
return Object.assign({}, user, options);
};
})(this));

Handling Facebook/Google login with ngCordovaOauth in Ionic + Firebase

I'm trying to implement Firebase authentication with angularfire signInWithCredential method for my Ionic app. As I'm using Firebase 3.x SDK, the methods signInWithRedirect and signInWithPopup are not yet supported on mobile devices. Thus I'm using the plugin ngCordovaOauth.
var ref = firebase.database().ref().child("users");
$scope.users = $firebaseArray(ref);
$cordovaOauth.facebook("//removed_client_id", [ "public_profile", "email"]).then(function(result) {
var credentials = firebase.auth.FacebookAuthProvider.credential(result.access_token);
$scope.authObj.$signInWithCredential(credentials).then(function(authData) {
var existUser = $scope.users.$getRecord(authData.uid);
if(existUser == null){
$scope.user = {
uid: authData.uid,
displayName: authData.displayName,
avatar: authData.photoURL,
email: authData.email,
contact: "0000000000",
provider: "facebook"
}
firebase.database().ref("users/" + authData.uid).set($scope.user);
}
$rootScope.result = authData;
$state.go("menu.home");
}, function(error) {
console.error("ERROR: " + error);
});
}, function(error) {
console.log("ERROR: " + error);
});
The problem that I'm facing is I have no idea what the structure of 'authdata' is as I couldn't find any documentation for the same. With sigInWithPopup, firebase returns 'result' object; contents of which can be accessed like 'result.user.uid', 'result.user.displayName' or 'result.user.email'. How can I achieve the same here as I'm trying to store the user profile when he logs in for the first time? Any help? I'm testing on android device. Thank you!
signInWithCredential returns a promise that resolves with a firebase.User same as signInWithEmailAndPassword and all other sign in apis.
Check the docs for more info on firebase.User:
https://firebase.google.com/docs/reference/js/firebase.User

Facebook login on cordova app shows blank white screen

This problem has been bugging me for a long time and I can't seem to find the solution, all the settings in my Facebook Developer panel are configured correctly, Site URL, App Domain and OAuth URLs.
When I run my app on my iPhone (I have it installed through iTunes) and click the authentication button I am successfully prompted with this screen:
However, after logging in, I am faced with a blank white screen instead of being redirected to my main.html page.
I am using the OpenFB plugin along with Parse and the Facebook Graph API to authenticate and store my users data, here is my login code:
login.html:
$('.facebookLogin').click(function(){
Parse.User.logOut(); // log current user out before logging in
login();
});
function login() {
openFB.login(function(response) {
if(response.status === 'connected') {
console.log('Facebook login succeeded');
Parse.FacebookUtils.logIn("email", { // permission request to use email
success: function(user) {
if (!user.existed()) {
FB.api('/me', function(response) {
var firstName = response.first_name;
var lastName = response.last_name;
var email = response.email;
var user_id = response.id;
user.set("firstName",firstName);
user.set("lastName",lastName);
user.set("email",email);
user.save();
});
window.location.href= "main.html";
}
else {
window.location.href= "main.html";
}
},
error: function(user, error) {
alert("User cancelled the Facebook login or did not fully authorize.");
}
});
}
else {
alert('Facebook login failed: ' + response.error);
}
}, {scope: 'email'});
}
oauthcallback.html:
<html>
<body>
<script>
// redirects to main page
window.location.href= "main.html";
</script>
</body>
</html>
Note: I have added main.html, login.html and oauthcallback.html to the Valid OAuth redirect URIs list on my panel.
Check that your site is using SSL with a valid certificate.
There might be an error trying to redirect from a non-secure site to an encrypted site.

PhoneGap 3.3 using Phonegap Facebook Connect plugin, getLoginStatus always returns unknown

I'm trying to implement Phonegap Facebook Connect plugin via PhoneGap build and FB.getLoginStatus ALWAYS returns "unknown" even though I'm logged into Facebook and have granted access to my app. Here's my code:
JAVASCRIPT CODE:
document.addEventListener("deviceready", onDeviceReady, false);
function onDeviceReady()
{
FB.init
({
appId: 'XXXXX',
status: true, // check login status
cookie: true, // enable cookies to allow the server to access the session
xfbml: false, // parse XFBML
oauth : true ,// enable OAuth 2.0
useCachedDialogs: false,
nativeInterface : CDV.FB
});
FB.getLoginStatus(function (response)
{
alert('FB.getLoginStatus');
if (response.status === 'connected')
{
alert('DUDE: connected to facebook');
}
else if (response.status === 'not_authorized')
{
alert('DUDE: not authorized for facebook');
}
else
{
alert('DUDE: not logged in to facebook: ' + response.status);
}
}, true);
}
CONFIG.XML:
<gap:plugin name="com.phonegap.plugins.facebookconnect">
<param name="APP_ID" value="XXXXXXX" />
<param name="APP_NAME" value="APP NAME" />
</gap:plugin>
Any ideas on why facebook auth status is unknown? Thanks.
You need to go through "Facebook Requirements and Set-Up" In Facebook Connect plugin
in Android:
If you plan on rolling this out on Android, please note that you will need to generate a hash of your Android key(s) and submit those to the Developers page on Facebook to get it working. Furthermore, if you are generating this hash on Windows (specifically 64 bit versions), please use version 0.9.8e or 0.9.8d of OpenSSL for Windows and not 0.9.8k. Big ups to fernandomatos for pointing this out!
step detail:
1. generate a hash key(s) How to create Android Facebook Key Hash?
2. insert your hash key on facebook app setting panel( Settings ) (add Android platform and insert Key Hashes)
3. Go to Account > Edit Setting > Signing Key's tab in Adobe phonegap build then Click 'add a key...' upload your keystore file to make a Android buuiding key
4. select your android key to build app in phonegap build.
reference link:
login + logout + login = fail #1
This worked for me use the plug with the and the example
https://github.com/Wizcorp/phonegap-facebook-plugin/blob/a5c6be9/README.md
You can't relay on cookies and need to pass the access token by yourself.
Here is what you need to do:
1) Client side (note that I am using the older version of the plugin where the FB js was patched instead of new functions):
Pass the user id and accesstoken to the server:
FB.login(function(response) {
if (response.authResponse) {
// Use userID on authResponse because FB.getUserID() works in the browser but return null on device
var userId = response.authResponse.userID;
// Or use FB.getAccessToken()
var accessToken = response.authResponse.accessToken;
//use userId and accessToken to pass to the server (form or ajax call)
}
}
2) Server Side (php)
//Get the accessToken from the request
$accessToken = $_REQUEST['accessToken'];
$facebook = new Facebook(array(
'appId' => '<YOUR APP ID>',
'secret' => '<YOUR APP SECRET>'
));
$facebook->setAccessToken($accessToken);
//Now you have the right session setup and can call Graph API
$fbUser = $facebook->api('/me')

phonegap - using external site as app - facebook login

I'm building a app site running through phone gap. Phone gap simply checks the user has internet connection and loads an external web app into the frame. I can navigat through the site fine with no blibs but as soon as I try the login to Facebook (either PHP redirect or javascript SDK) the app suddenly gets its navbar back or opens a new window (javascript SDK).
Is there anyway I can prevent this?
regards
It took some doing but using the ChildBrowser plugin, I've managed to login! (this is for android) I've used some code from a facebook connect plugin which didnt work for me, re wrote some stuffs so I could understand it and now works. Chears Juicy Scripter!
var fb_success = 'https://www.facebook.com/connect/login_success.html';
var fb_logout = 'https://www.facebook.com/connect/login_failed.html';
var fb_logout_ = 'http://m.facebook.com/logout.php?confirm=1&next=' + fb_logout;
var authorize_url = '';
var my_client_id = '##################';
var my_secret = '######################';
var my_type = 'user_agent';
var my_display = 'touch';
var token = false;
var fb_code = false;
var device_ready = false;
var ajax_url = '';
function logged_in(){
// alert('do what you need to do!');
}
function fb_force_logout(){
}
function fb_auth_check(){
console.log('fb_auth_check()');
if( fb_code !== false ) {
console.log('ajax test instigated...');
ajax_url = 'https://graph.facebook.com/oauth/access_token?client_id=' + encodeURIComponent(my_client_id) + '&client_secret=' + encodeURIComponent(my_secret) + '&code=' + encodeURIComponent(fb_code) + '&redirect_uri=' + fb_success;
$.ajax({
url: ajax_url,
type: 'POST',
success: function(html){
token = html.split("=")[1];
console.log('success! token = ' + token);
window.plugins.childBrowser.close();
fb_init();
},
error: function(error) {
console.log('there was an error...' + ajax_url);
window.plugins.childBrowser.close();
}
});
}
}
function fb_track_redirects(loc){
console.log('redirect tracked... ' + loc);
if ( loc.indexOf(fb_success) >= 0 || loc.indexOf(fb_success) > -1 ) {
fb_code = loc.match(/code=(.*)$/)[1]
console.log('success redirect... fb_code=' + fb_code);
fb_auth_check();
window.plugins.childBrowser.close();
} else if ( loc.indexOf(fb_logout) >= 0 || loc.indexOf(fb_logout) > -1 ) {
window.plugins.childBrowser.close();
}
}
function inner_init(){
console.log('inner_init()');
if( token === false ) {
console.log('token was false...');
authorize_url += "https://graph.facebook.com/oauth/authorize?";
authorize_url += "client_id=" + encodeURIComponent(my_client_id);
authorize_url += "&redirect_uri=" + encodeURIComponent(fb_success);
authorize_url += "&display=" + encodeURIComponent(my_display);
authorize_url += "&scope=publish_stream,offline_access";
console.log('instigated location change...');
window.plugins.childBrowser.onLocationChange = function(loc){
fb_track_redirects(loc);
}
console.log('open Facebbok login window');
window.plugins.childBrowser.showWebPage(authorize_url);
}else{
logged_in();
}
}
function fb_init(){
console.log('fb_init()');
if( device_ready === false ) {
console.log('first device run...');
document.addEventListener("deviceready", function(){
device_ready = true;
console.log('device ready...');
inner_init();
}, false);
}else{
inner_init();
}
}
$(document).ready(function(){
$('#login').bind('click', function(){
fb_init();
return false;
})
});
</script>
This is how it works for all apps native or web without patching the SDK code.
This is probably can be done, but will require digging into code. The question is do you really need it? This is a desired behavior.
You can try to use PhoneGap Facebook plugin and enable Single Sign On so native Facebook App if exists will be opened instead of browser to authenticate the user.
BTW,
Apps that are just external sites wrapped mostly rejected in app store.
Update:
Where is some points that may be also helpful in answer (by Facebook employee) to similar question How can I use an access token to circumvent FB.login().
Also have a look on ChildBrowser PhoneGap plugin (and Example).