Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/410.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 如何使用Cordova插件向Firebase发送Facebook身份验证详细信息&;Firebase模板_Javascript_Cordova_Firebase_Firebase Realtime Database_Firebase Authentication - Fatal编程技术网

Javascript 如何使用Cordova插件向Firebase发送Facebook身份验证详细信息&;Firebase模板

Javascript 如何使用Cordova插件向Firebase发送Facebook身份验证详细信息&;Firebase模板,javascript,cordova,firebase,firebase-realtime-database,firebase-authentication,Javascript,Cordova,Firebase,Firebase Realtime Database,Firebase Authentication,抱歉,这个问题有点长,因为我已经尝试解决这个问题一段时间了,我想确保我没有遗漏任何信息。我正在构建一个Cordova应用程序,并使用Firebase作为身份验证/数据库后端。近一周来,我一直在尝试使用“使用Facebook登录”按钮对Firebase用户进行身份验证,但一直无法使其正常工作 最初我在这里尝试了以下Firebase的示例:(我需要使用“高级:手动处理登录流”,因为它是Cordova Android和iOS应用程序),这个示例对我不起作用,因为指向Facebook SDK脚本(//c

抱歉,这个问题有点长,因为我已经尝试解决这个问题一段时间了,我想确保我没有遗漏任何信息。我正在构建一个Cordova应用程序,并使用Firebase作为身份验证/数据库后端。近一周来,我一直在尝试使用“使用Facebook登录”按钮对Firebase用户进行身份验证,但一直无法使其正常工作

最初我在这里尝试了以下Firebase的示例:(我需要使用“高级:手动处理登录流”,因为它是Cordova Android和iOS应用程序),这个示例对我不起作用,因为指向Facebook SDK脚本(//connect.Facebook.net/en_US/SDK.js)的链接不断抛出错误:

file://connect.facebook.net/en_US/sdk.js 未能加载资源:net::错误文件未找到

我尝试用几种方法修复此错误,例如:

  • 将其更改为(这导致错误:
    无法加载URL:此URL的域未包含在应用程序的域中。若要加载此URL,请将应用程序的所有域和子域添加到应用程序设置中的应用程序域字段。
  • 将相关链接添加到Facebook应用程序设置中的“有效OAuth重定向URI”和域列表中
  • 将文件存储在本地文件系统中(以及手机应用程序中的本地文件)
  • 包括我的index.html文件头中的整个SDK
这些尝试都没有奏效。因此,我决定在这里使用cordova插件facebook:

这是我使用插件从Facebook获取用户信息的代码:

function logInWithFacebook(){
    CordovaFacebook.login({
    onSuccess: function(result) {
         console.log(result);
         console.log(result.authToken);
         // Store or send the user auth/access key here?
         // Get user's name
         retrieveUserDetails(); 
    if(result.declined.length > 0) {
         alert("The User declined something!");
      }
   },
   onFailure: function(result) {
      if(result.cancelled) {
         alert("The user doesn't like my app");
      } else if(result.error) {
         alert("There was an error:" + result.errorLocalized);
      }
   }
});
}

function retrieveUserDetails(){
    // Now that the user has authroised the app, make request to CordovaFacebook plugin to get user's name
    CordovaFacebook.graphRequest({
        path: '/me',
        params: { fields: 'name' },
        onSuccess: function (userData) {
            console.log(userData);
            console.log(userData.name);
        // Here somehow send the retrieved username and send it to the Firebase function so that it's linked with the auth key.
        },
        onFailure: function (result) {
            if (result.error) {
                Error.log('error', 'There was an error in graph request:' + result.errorLocalized);
            }
        }
    });
}
我现在可以点击登录按钮,通过Facebook成功登录。该过程从Facebook返回用户身份验证/访问密钥和用户名

据我所知,Firebase文档()中的手动登录流示例获取从Facebook返回的密钥,将其转换为Firebase密钥,然后将用户新创建的Firebase密钥及其用户名输入Firebase的服务器

在下面的示例代码中,这似乎非常简单:

function checkLoginState(event) {
  if (event.authResponse) {
    // User is signed-in Facebook.
    var unsubscribe = firebase.auth().onAuthStateChanged(function(firebaseUser) {
      unsubscribe();
      // Check if we are already signed-in Firebase with the correct user.
      if (!isUserEqual(event.authResponse, firebaseUser)) {
        // Build Firebase credential with the Facebook auth token.
        var credential = firebase.auth.FacebookAuthProvider.credential(
            event.authResponse.accessToken);
        // Sign in with the credential from the Facebook user.
        firebase.auth().signInWithCredential(credential).catch(function(error) {
          // Handle Errors here.
          var errorCode = error.code;
          var errorMessage = error.message;
          // The email of the user's account used.
          var email = error.email;
          // The firebase.auth.AuthCredential type that was used.
          var credential = error.credential;
          // ...
        });
      } else {
        // User is already signed-in Firebase with the correct user.
      }
    });
  } else {
    // User is signed-out of Facebook.
    firebase.auth().signOut();
  }
}

function isUserEqual(facebookAuthResponse, firebaseUser) {
  if (firebaseUser) {
    var providerData = firebaseUser.providerData;
    for (var i = 0; i < providerData.length; i++) {
      if (providerData[i].providerId === firebase.auth.FacebookAuthProvider.PROVIDER_ID &&
          providerData[i].uid === facebookAuthResponse.userID) {
        // We don't need to re-auth the Firebase connection.
        return true;
      }
    }
  }
  return false;
}

FB.Event.subscribe('auth.authResponseChange', checkLoginState);
什么东西没有按你想要的方式工作

这个过程的前半部分工作正常,但我不知道如何处理从Facebook返回的accessToken。通过阅读文档,我认为Firebase应该将此令牌转换为Firebase访问令牌,然后用于将用户登录到Firebase(这也会触发上述AuthStateChanged函数)。从那里,我希望能够将从Facebook检索到的任何数据(用户名等)插入我的Firebase数据库。但主要问题是将Facebook accessToken转换为Firebase登录(我原始问题中的第二段代码是我尝试在何处执行转换/登录到Firebase)

因为我使用的是Cordova,所以这种方法(使用插件登录Facebook,然后处理accessToken的转换)似乎是登录Facebook的唯一方法。但是我完全不知道如何完成下半场

更新2

我已经从文档中删除了将Facebook令牌转换为Firebase令牌代码示例的部分,这样就不需要Facebook SDK了。而且它似乎在起作用。这是删除SDK相关部分后的代码:

// First, define the Facebook accessToken:
var FBaccessToken = result.accessToken;

// Build Firebase credential with the Facebook auth token.
var credential = firebase.auth.FacebookAuthProvider.credential(
    FBaccessToken);
// Sign in with the credential from the Facebook user.
firebase.auth().signInWithCredential(credential).then(function(user){

console.log("It looks like we signed into Firebase with the Facebook token correctly.");

}, function(error) {
    console.log("Something went wrong, user isn't signed into Firebase with the FB token.");
  // Handle Errors here.
  var errorCode = error.code;
  var errorMessage = error.message;
  // The email of the user's account used.
  var email = error.email;
  // The firebase.auth.AuthCredential type that was used.
  var credential = error.credential;
  // ...
});
我仍然需要添加用户来自Facebook的电子邮件,并尝试在登录Firebase时发送该电子邮件-这样我就可以在Firebase控制台中为用户提供一些标识符,但这是一个好的开始

第二次更新

以下代码在用户授权应用程序后成功从Facebook获取用户数据:

    CordovaFacebook.graphRequest({
    path: '/me',
    params: { fields: 'first_name,last_name,email,locale,gender,age_range,picture.width(200).height(200)' },
    onSuccess: function (userData) {
        console.log(userData)
        var first_name = userData.first_name;
        var last_name = userData.last_name;
        var email = userData.email;
        var locale = userData.locale;
        var gender = userData.gender;
        var min_age = userData.age_range.min;
        var profile_picture = userData.picture.data.url;

            // Enter user details into the Firebase database:
            firebase.database().ref('users/' + uid).set({
            first_name: first_name,
            last_name: last_name,
            email: email,
            locale: locale,
            gender: gender,
            min_age: min_age,
            profile_picture : profile_picture
        });
        console.log("Facebook user data should now be in the database!");   
    },
    onFailure: function (result) {
        if (result.error) {
            Error.log('error', 'There was an error in graph request:' + result.errorLocalized);
        }
    }
});
(这只是对上一次更新的一个回答,正如您了解的那样:))

如何从Facebook.login()获取用户电子邮件 查看,您可以在传递给
login
方法的对象上添加
permissions
属性

根据许可证,电子邮件的权限名称只是
“email”

我还没有测试,但我认为这应该可以:

CordovaFacebook.login({
    permissions: [ 'email' ],
    onSuccess: function(result) {
        console.log('email:', result.email);
        ...
    },
    onFailure: function(result) {
        ...
    }
});

我有很多问题。目前它是如何工作的?你希望它如何工作?什么东西没有按你想要的方式工作?请将我的问题的答案添加到您的问题中,并在此处发表评论,以便我可以再看一眼。您好@arnehugo感谢您查看我的问题!我已经在问题的底部添加了对您问题的回答,作为更新。我希望他们能帮上忙,再次感谢你的帮助!如果只为添加五段代码,会发生什么?这可能行得通。嗨@ArneHugo,我最初试图遵循文档,但该代码要求包含Facebook SDK脚本。我无法将其包括在内,因为这是一个Cordova应用程序,这样做总是会导致错误,我尝试用不同的方法(在我问题的第3段中列出)将其包括在内,但没有一个有效。我想也许有某种方法可以将当前登录方法的结果(Facebook访问密钥)插入到创建Firebase访问密钥的代码中,而不需要Facebook SDK?您好@ArneHugo我在尝试包含SDK时收到了相同的错误,所以这次我决定试着删掉需要它的部分代码,它似乎已经奏效了!我在问题的第二次更新中添加了它。Facebook用户现在出现在Firebase控制台的Authentication/Users下,但是在他们的ID旁边没有电子邮件,所以我也需要发送电子邮件。但目前看来问题已基本解决,谢谢您的帮助。:)你好@arnehugo谢谢你。在使用Facebook登录时成功请求电子邮件权限。它需要在完成后发出第二个插件请求,以便检索数据(我认为我无法在登录过程的响应中返回用户的数据)。我补充说
CordovaFacebook.login({
    permissions: [ 'email' ],
    onSuccess: function(result) {
        console.log('email:', result.email);
        ...
    },
    onFailure: function(result) {
        ...
    }
});