Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/433.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/node.js/38.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 在React Native中登录Facebook_Javascript_Node.js_Facebook_Reactjs_React Native - Fatal编程技术网

Javascript 在React Native中登录Facebook

Javascript 在React Native中登录Facebook,javascript,node.js,facebook,reactjs,react-native,Javascript,Node.js,Facebook,Reactjs,React Native,我正在用React Native开发一个应用程序,我想用Facebook实现登录 我在Node.js中有一个API,我在其中处理用户登录的逻辑等 我使用passport.js让用户通过Facebook或传统电子邮件登录 我正在使用SafariView在我的API中打开一个URL,它只是我应用程序中的一个常规“WebView” 我已尝试使用以下代码: class FacebookButton extends Component { componentDidMount() { // Ad

我正在用React Native开发一个应用程序,我想用Facebook实现登录

我在Node.js中有一个API,我在其中处理用户登录的逻辑等

我使用passport.js让用户通过Facebook或传统电子邮件登录

我正在使用
SafariView
在我的API中打开一个URL,它只是我应用程序中的一个常规“WebView”

我已尝试使用以下代码:

class FacebookButton extends Component {
  componentDidMount() {
    // Add event listener to handle OAuthLogin:// URLs
    Linking.addEventListener('url', this.handleOpenURL);

    // Launched from an external URL
    Linking.getInitialURL().then((url) => {
      if (url) {
        this.handleOpenURL({ url });
      }
    });
  }

  componentWillUnmount() {
    Linking.removeEventListener('url', this.handleOpenURL);
  }

  handleOpenURL({ url }) {
    // Extract stringified user string out of the URL
    const [, user_string] = url.match(/user=([^#]+)/);

    this.setState({
      // Decode the user string and parse it into JSON
      user: JSON.parse(decodeURI(user_string))
    });

    if (Platform.OS === 'ios') {
      SafariView.dismiss();
    }
  }

  openURL(url) {
    if (Platform.OS === 'ios') {
      SafariView.show({
        url: url,
        fromBottom: true,
      });
    } else {
      Linking.openURL(url);
    }
  }

  render() {
    return (
      <Button
        onPress={() => this.openURL('https://mywebsite.com/api/auth/facebook')}
        title='Continue with Facebook'
        ...
class FacebookButton扩展组件{
componentDidMount(){
//添加事件侦听器以处理OAuthLogin://URL
Linking.addEventListener('url',this.handleOpenURL);
//从外部URL启动
Linking.getInitialURL()。然后((url)=>{
如果(url){
this.handleOpenURL({url});
}
});
}
组件将卸载(){
Linking.removeEventListener('url',this.handleOpenURL);
}
handleOpenURL({url}){
//从URL中提取字符串化的用户字符串
const[,user#u string]=url.match(/user=([^#]+)/);
这是我的国家({
//解码用户字符串并将其解析为JSON
user:JSON.parse(decodeURI(用户字符串))
});
如果(Platform.OS==='ios'){
SafariView.disclose();
}
}
openURL(url){
如果(Platform.OS==='ios'){
SafariView.show({
url:url,
自下而上:没错,
});
}否则{
Linking.openURL(url);
}
}
render(){
返回(
这个.openURL('https://mywebsite.com/api/auth/facebook')}
title='continuewithfacebook'
...
所以我想我必须在URL
https://mywebsite.com/api/auth/facebook
然后将用户发送到类似于
OAuthL的urlogin://...
,但我不完全确定如何使用它

有人能帮我朝正确的方向走吗

import { LoginManager, AccessToken } from 'react-native-fbsdk'; // add this file using npm i react-native-fbsdk
创建函数

const onFacebookButtonPress = async () => {

// Attempt login with permissions
const result = await LoginManager.logInWithPermissions(['public_profile', 'email']);

if (result.isCancelled) {
  throw 'User cancelled the login process';
}

// Once signed in, get the users AccesToken
const userInfo = await AccessToken.getCurrentAccessToken();

if (!userInfo) {
  throw 'Something went wrong obtaining access token';
}
console.log('user info login', userInfo)
// Create a Firebase credential with the AccessToken
const facebookCredential = auth.FacebookAuthProvider.credential(userInfo.accessToken);
setGoogleToken(userInfo.accessToken)

// Sign-in the user with the credential
return auth().signInWithCredential(facebookCredential)
.then(() => {
    //Once the user creation has happened successfully, we can add the currentUser into firestore
    //with the appropriate details.
    console.log('current User @@@@', auth().currentUser);

    var name = auth().currentUser.displayName
    var mSplit = name.split(' ');
    console.log("mSplit ",mSplit);

    let mUserDataFacebook = {
        user_registration_email: auth().currentUser.email,
        user_registration_first_name: mSplit[0],
        user_registration_last_name: mSplit[1],
        registration_type: 'facebook',
        user_registration_role: "Transporter",
        token: userInfo.accessToken,
        user_image : auth().currentUser.photoURL,
        
    };
    console.log('mUserDataFacebook',mUserDataFacebook)
    LoginWithGoogleFacebook(mUserDataFacebook) /// Call here your API 
      
    firestore().collection('users').doc(auth().currentUser.uid) //// here you can add facebook login details to your firebase authentication.
    .set({
        fname: mSplit[0],
        lname: mSplit[1],
        email: auth().currentUser.email,
        createdAt: firestore.Timestamp.fromDate(new Date()),
        userImg: auth().currentUser.photoURL,
    })
    //ensure we catch any errors at this stage to advise us if something does go wrong
    .catch(error => {
        console.log('Something went wrong with added user to firestore: ', error);
    })
  })
 
}
在button press on FaceBookButton press()上调用此函数

对于android,需要在中设置并添加facebook id android/app/src/main/res/values/strings.xml文件 把这两行加起来

你的FACEBOOK账号 fbYOUR\u FACEBOOK\u ID//不要删除此字符串值中的fb

/////////////在AndroidMainfest.xml文件中添加此代码

//////////此代码加载项MainApplication.java文件

导入com.facebook.FacebookSdk

导入com.facebook.appevents.AppEventsLogger

/////////添加代码build.gradle文件

实现'com.facebook.android:facebook安卓sdk:[5,6]

创建函数

const onFacebookButtonPress = async () => {

// Attempt login with permissions
const result = await LoginManager.logInWithPermissions(['public_profile', 'email']);

if (result.isCancelled) {
  throw 'User cancelled the login process';
}

// Once signed in, get the users AccesToken
const userInfo = await AccessToken.getCurrentAccessToken();

if (!userInfo) {
  throw 'Something went wrong obtaining access token';
}
console.log('user info login', userInfo)
// Create a Firebase credential with the AccessToken
const facebookCredential = auth.FacebookAuthProvider.credential(userInfo.accessToken);
setGoogleToken(userInfo.accessToken)

// Sign-in the user with the credential
return auth().signInWithCredential(facebookCredential)
.then(() => {
    //Once the user creation has happened successfully, we can add the currentUser into firestore
    //with the appropriate details.
    console.log('current User @@@@', auth().currentUser);

    var name = auth().currentUser.displayName
    var mSplit = name.split(' ');
    console.log("mSplit ",mSplit);

    let mUserDataFacebook = {
        user_registration_email: auth().currentUser.email,
        user_registration_first_name: mSplit[0],
        user_registration_last_name: mSplit[1],
        registration_type: 'facebook',
        user_registration_role: "Transporter",
        token: userInfo.accessToken,
        user_image : auth().currentUser.photoURL,
        
    };
    console.log('mUserDataFacebook',mUserDataFacebook)
    LoginWithGoogleFacebook(mUserDataFacebook) /// Call here your API 
      
    firestore().collection('users').doc(auth().currentUser.uid) //// here you can add facebook login details to your firebase authentication.
    .set({
        fname: mSplit[0],
        lname: mSplit[1],
        email: auth().currentUser.email,
        createdAt: firestore.Timestamp.fromDate(new Date()),
        userImg: auth().currentUser.photoURL,
    })
    //ensure we catch any errors at this stage to advise us if something does go wrong
    .catch(error => {
        console.log('Something went wrong with added user to firestore: ', error);
    })
  })
 
}
在button press on FaceBookButton press()上调用此函数

对于android,需要在中设置并添加facebook id android/app/src/main/res/values/strings.xml文件 把这两行加起来

你的FACEBOOK账号 fbYOUR\u FACEBOOK\u ID//不要删除此字符串值中的fb

/////////////在AndroidMainfest.xml文件中添加此代码

//////////此代码加载项MainApplication.java文件

导入com.facebook.FacebookSdk

导入com.facebook.appevents.AppEventsLogger

/////////添加代码build.gradle文件


实现'com.facebook.android:facebook android sdk:[5,6)

我会使用官方sdk,它工作正常:但我需要登录以与网站上已注册的用户同步,因此我想我必须让它通过API?不确定你的意思,登录后你会得到用户id,你可以检查用户是否已注册。与构建自定义解决方案相同首先,在客户端通过sdk进行授权,获取令牌,然后将令牌传递给服务器,通过令牌查找用户社交id(u应该存储)如果它存在-授权HIM我会使用官方sdk,它可以正常工作:但我需要登录以与网站上已注册的用户同步,因此我想我必须通过API进行登录?不确定你的意思,登录后你会获得用户id,你可以检查用户是否已注册。与b相同构建自定义解决方案。首先,通过客户端上的sdk传递授权并获取令牌,然后将令牌传递到服务器,并通过令牌(u应存储它)查找用户社交id,如果存在,则授权他