I've gotten facebook login working using the new https://github.com/facebook/react-native-fbsdk, however I can't seem to get the user token which is usually returned in the response. Anyone found a way to get this information? The other SDK's https://github.com/magus/react-native-facebook-login returns it on the login request but the new FB sdk doesn't, and the documentation on the github page doesn't mention it anywhere.
Found the answer after some more digging. You need to use the fbsdkcore to access the user token. Heres how you use it.
var FBSDKCore = require('react-native-fbsdkcore');
var {
FBSDKAccessToken,
} = FBSDKCore;
var Login = React.createClass({
render: function() {
return (
<View>
<FBSDKLoginButton
onLoginFinished={(error, result) => {
if (error) {
alert('Error logging in.');
} else {
if (result.isCanceled) {
alert('Login cancelled.');
} else {
FBSDKAccessToken.getCurrentAccessToken((token) => {
console.log(token.tokenString);
})
}
}
}}
onLogoutFinished={() => console.log('Logged out.')}
readPermissions={[]}
publishPermissions={['publish_actions']}/>
</View>
);
}
});
You don't need a third party module (react-native-fbsdkcore)
The package (react-native-fbsdk) has instructions on it's Github page: https://github.com/facebook/react-native-fbsdk#usage
After you've logged the user in, you can fetch the access credentials as follows:
import { AccessToken } from 'react-native-fbsdk';
AccessToken.getCurrentAccessToken().then(data => {
console.log(data.accessToken.toString())
})
Related
I'm currently doing a project using react native where I need to let users to login using facebook. So I use React-native-fbsdk LoginButton component to let users to login and get the access token. Also part of the project needs let users to share links to their profiles.
In order to do that, I followed as GitHub repo of Facebook which says how to add ShareDialog. After adding both LoginButton and ShareDialog, I ran the app. Login was successful and I got the access token. But when I try to share a link, it asks me to login again. If I login with ShareDialog, it let me to share post and everything as expected.
But if I logout with LoginButton after login with ShareDialog too, both components perform logout successfully. Problem is Login does not handle for both components with single login.
Below is my code.
render() {
return (
<View style={styles.container}>
<LoginButton
publishPermissions={["publish_actions"]}
onLoginFinished={
(error, result) => {
if (error) {
alert("Login failed with error: " + error.message);
} else if (result.isCancelled) {
alert("Login was cancelled");
} else {
alert("Login was successful with permissions: " + result.grantedPermissions)
}
}
}
onLogoutFinished={() => alert("User logged out")}/>
<TouchableHighlight onPress={this.shareLinkWithShareDialog}>
<Text style={styles.shareText}>Share link with ShareDialog</Text>
</TouchableHighlight>
</View>
);
}
shareLinkWithShareDialog = () => {
const shareLinkContent = {
contentType: 'link',
contentUrl: 'https://www.sample.com/',
contentDescription: 'Test Sharing Description'
};
var tmp = this;
ShareDialog.canShow(shareLinkContent).then(
(canShow) => {
if (canShow) {
return ShareDialog.show(shareLinkContent);
}
}
).then(
(result) => {
if (result.isCancelled) {
alert('Share cancelled');
} else {
alert('Share success with postId: ' + result.postId);
}
},
(error) => {
alert('Share fail with error: ' + error);
}
);
}
Please help me here. I cannot identify what's wrong with this.
Note
I checked this using a Test User of Facebook and it also has all relevant permissions including manage_pages and test user has it's own Test Page too.
I got a similar problem and that was because I hadn't installed facebook app on my phone. Seems like your code is fine.
However I haven't used Test Page and Test User options in facebook but I hope they are no different than a normal user when it comes to functionalities. Just try to install the facebook app and run your app. Should be fine.
I have tried every way I can think and am running into the same issue all day.
I am building a react native mobile application. I am using firebase as my database and react-native-facebook-login package to log the user in.
Currently the package works fine, I enter the fb details and the correct data is being returned and the user is 'logged in', I can console log the result but trying to do anything else returns an error.
I have tried:
Passing an action (Redux) where I do the firebase login, error:
Cannot read property 'loginUser' of undefined
setState to the resulting data, error:
this.setState is not a function
I am not sure exactly how to do the firebase authenticate with credentials but am happy to figure that out later, I just need to be able to access the data in the first place!
My component:
...
class FBLoginWrapper extends Component {
state = { user: null };
render() {
return (
<FBLogin
buttonView={<FBSignInView />}
ref={(fbLogin) => { this.fbLogin = fbLogin }}
loginBehavior={FBLoginManager.LoginBehaviors.Native}
permissions={["email","user_friends"]}
onLogin={function (e) { this.props.loginUser(e); }}
onLoginFound={function (e) { this.setState({ user: e }); }}
/>
);
}
...
If you need more code let me know. I have included two different ways I have tried and failed under [onLogin] and [onLoginFound]. I will use one implementation for both when I have something that works.
Ideally I would like to call the action {this.props.loginUser(e)} but if I have to do it through a setState that is fine too at this point.
you should use the onLoginFinished property if you just need to access the data returned.
This is how I use the LoginButton in one of my apps:
AccessToken is part of the FBSDK package
const FBSDK = require('react-native-fbsdk');
const {
LoginButton,
AccessToken
} = FBSDK;
....
<View>
<LoginButton
publishPermissions={["publish_actions"]}
onLoginFinished={
(error, result) => {
if (error) {
alert("login has error: " + result.error);
} else if (result.isCancelled) {
alert("login is cancelled.");
} else {
AccessToken.getCurrentAccessToken().then(
(data) => {
let token = data.accessToken.toString();
global.storage.save({
key: 'loginState',
rawData: {
token: token
},
});
firestack.auth.signInWithProvider('facebook', token, '')
.then((user)=>{
Actions.tabbar({profile:user});
});
}
)
}
}
}
onLogoutFinished={() => alert("logout.")}/>
I put this issue in gist as well:
https://gist.github.com/yhagio/7561f34d12bc5edb9b5fe0fc1b4bb2b6
Github Repo : https://github.com/yhagio/meteor-tatter
Issue
When I click facebook login button, it opens the login popup, but
the URL in the popup always shows that client_id=undefined, and gives "Sorry, something went wrong".
I installed service-configuration and accounts-facebook meteor packages and configured as follows.
Also, cretead the app & added Facebook Login product in https://developers.facebook.com
Am I missing something?
Screenshot
The URL is like this:
https://www.facebook.com/v2.2/dialog/oauth?client_id=undefined&redirect_uri=http://localhost:3000/_oauth/facebook&display=popup&scope=public_profile&state=eyJsb2dpblN0eW...
In server https://github.com/yhagio/meteor-tatter/blob/master/imports/startup/server/index.js
import { Meteor } from 'meteor/meteor';
import { clientId, secret } from './secret.js';
Meteor.startup(() => {
ServiceConfiguration.configurations.upsert(
{ service: "facebook" },
{
$set: {
clientId: clientId,
loginStyle: "popup",
secret: secret
}
}
);
});
In client https://github.com/yhagio/meteor-tatter/blob/master/imports/ui/helpers/auth.js
import { Meteor } from 'meteor/meteor';
export default function auth() {
return new Promise((resolve, reject) => {
Meteor.loginWithFacebook({
requestPermissions: ['public_profile']
}, (err, user) => {
if (err !== null) return reject(err);
resolve(user);
});
});
}
Problem was that it should be appId instead of clientId. Even though the guide shows clientId. Ref: http://docs.meteor.com/api/accounts.html#service-configuration
i want to get email after login with my cordova application
but when i added a permission with Graph API Explorer , i found this
message
yes i added permission :
in my controller :
.controller("LoginController", function($scope, $cordovaOauth, $localStorage, $location) {
$scope.login = function() {
$cordovaOauth.facebook("app-id", ["email", "user_birthday","user_website", "user_location", "user_relationships"]).then(function(result) {
$localStorage.accessToken = result.access_token;});
.controller("ProfileController", function($scope, $http, $localStorage, $location) {
$scope.init = function() {
if($localStorage.hasOwnProperty("accessToken") === true) {
$http.get("https://graph.facebook.com/v2.2/me", { params: { access_token: $localStorage.accessToken, fields: "id,email,name,gender,email,location,website,picture,relationship_status", format: "json" }}).then(function(result) {
$scope.profileData = result.data;
//alert(JSON.stringify(result.data));
}, function(error) {
//alert("There was a problem getting your profile. Check the logs for details.");
console.log(error);
});
i found this result :
[![enter image description here][4]][4]
Users don't need an email to use Facebook afaik, and it may not be confirmed yet. The debug message is very clear about that. There is no guarantee to always get the Email, even with the email permission.
Just to make sure, test this API call: https://developers.facebook.com/tools/explorer/?method=GET&path=me%3Ffields%3Demail&version=v2.5
I am trying to get a list of all the pages the logged user an Admin of, but I am getting the error "An active access token must be used to query information about the current user". Here is the code I am using:
function login(){
FB.login(function(response) {
if (response.authResponse) {
$.get("https://graph.facebook.com/me/accounts", function(data) {
alert( "success" );
})
.done(function() {
alert( "second success" );
})
.fail(function(data) {
alert( "error" );
})
.always(function() {
alert( "finished" );
});
} else {
// not auth / cancelled the login!
}
}, { scope: "manage_pages" });
}
So in this code, after logging in, the call $.get("https://graph.facebook.com/me/accounts") throws the error.
UPDATE:
I am able to get the the list using FB.api("/me/accounts"). So how come I can't get it using this code? What am I doing wrong? Thanks.
Simple: You are not passing a user access token with your direct request:
$.get("https://graph.facebook.com/me/accounts", function(data) { ... });
instead of
var accessToken = "aoidhfgoafhgoidfhg"; // replace with real access token
$.get("https://graph.facebook.com/me/accounts?access_token=" + accessToken, function(data) { ... });
The FB SDK does this internally/automatically. What's not really clear to me is why you don't use the FB SDK here as well, if you're already using it for FB Login. That doesn't make much sense IMHO.