如何使用Firebase在Flutter中进行电话验证?

时间:2018-05-04 18:18:53

标签: firebase flutter

我搜索了很多网站,但我没有找到使用Firebase在Flutter中实现手机身份验证的方法。谁能告诉我怎么做?

7 个答案:

答案 0 :(得分:1)

很抱歉迟到了。我已经忽略了扑朔迷离的GitHub存储库的所有电子邮件。最后,Flutter-Team添加了电话身份验证。这是firebase-auth插件的链接。请参见实现的功能there。在flutter仍处于alpha-beta版本之前,我已经提出了这个问题。当时尚未实施。现在,我认为这可能对其他人也有帮助,请在此处发布。再次,很抱歉您的回复很晚。

答案 1 :(得分:1)

当前不推荐使用_signInPhoneNumber,请使用以下命令:

try {
    AuthCredentialauthCredential = PhoneAuthProvider.getCredential(verificationId:verificationsCode: smsCode);

    await _firebaseAuth
      .signInWithCredential(authCredential)
      .then((FirebaseUser user) async {
         final FirebaseUser currentUser = await _firebaseAuth.currentUser();
         assert(user.uid == currentUser.uid);
         print('signed in with phone number successful: user -> $user');
    }
}

答案 2 :(得分:1)

使用flutter_otp包轻松地通过OTP发送SMS。优点是:

  1. 您可以发送自定义的OTP消息。
  2. OTP可以在任何范围内生成。

使用示例:

 import 'package:flutter_otp/flutter_otp.dart';

 ...

 FlutterOtp myOtpObj = FlutterOtp();
 myOtpObj.sendOtp('7975235555');

 ...

 // you can check as follows
 bool correctOrNot = myOtpObj.resultChecker(<OTP entered by user>);

检出flutter_otp存储库here

答案 3 :(得分:1)

以下是步骤:-

  1. 根据电话号码获取OTP:-

    void sendOTP(String phoneNumber, PhoneCodeSent codeSent,
          PhoneVerificationFailed verificationFailed) {
        if (!phoneNumber.contains('+')) phoneNumber = '+91' + phoneNumber;
        _firebaseAuth.verifyPhoneNumber(
            phoneNumber: phoneNumber,
            timeout: Duration(seconds: 30),
            verificationCompleted: null,
            verificationFailed: verificationFailed,
            codeSent: codeSent,
            codeAutoRetrievalTimeout: null);   }
    
  2. 使用codeSent函数检索verify_id并将其传递到OTP屏幕

    void codeSent(String verificationId, [int forceResendingToken]) {
    Navigator.push(
        context,
        MaterialPageRoute(
            builder: (context) => Otp(
                  phoneNumber: _phoneNumber,
                  verificationId: verificationId,
                )));
    }
    
  3. 根据Verification_id和OTP获取用户

    Future<bool> verifyOTP(String verificationId, String otp) async {
    AuthCredential credential = PhoneAuthProvider.getCredential(
      verificationId: verificationId,
      smsCode: otp,
    );
    AuthResult result;
    try {
      result = await _firebaseAuth.signInWithCredential(credential);
    } catch (e) {
      // throw e;
      return false;
    }
    print(result);
    (await result.user.getIdToken()).claims.forEach((k, v) {
      print('k= $k and v= $v');
    });
    if (result.user.uid != null) return true;
    return false;
    }
    

有关更多详细信息,请观看下面的video

https://youtu.be/e5M3EwJJYS4

答案 4 :(得分:0)

我有同样的问题,但我正在构建一个Ionic应用程序。

你可以在网上做firebase手机认证。 这个想法是:

  • 获取用户的电话号码并发送到网页。
  • 创建recaptchaVerifier

    var recaptchaVerifier = new firebase.auth.RecaptchaVerifier('recaptcha-container');
    
  • 使用电话号码登录用户:

    firebase.auth().signInWithPhoneNumber(phoneNumber, recaptchaVerifier)
            .then(confirmationResult => {
                myVerificationId = confirmationResult.verificationId;
            })
            .catch(error => {
                console.log('error', error);
            })
    
  • 通过深层链接

  • 将确认ID发回flutter应用
  • Firebase将发送短信代码。

  • 使用任何获取确认ID和的方法登录用户 代码作为参数。对于网络来说,它是这样的:

      let signinCredintial = firebase.auth.PhoneAuthProvider.credential(this.verificationId, this.code);
      firebase.auth().signInWithCredential(signinCredintial)
       .then(response => {
         // user is signed in
    
    })
    

答案 5 :(得分:0)

我已经用firebase实现了手机身份验证singnIn,它很容易,只需导入firebase_auth库并验证电话号码的格式是否正确,即它的开头是“ +”号,然后是国家/地区代码,然后是电话号码然后代码像这样

if (phoneExp.hasMatch(phon))
   {
      final PhoneVerificationCompleted verificationCompleted=(FirebaseUser user){
        setState(() {
                      _message=Future<String>.value("auto sign in succedded $user");
                      debugPrint("Sign up succedded");
                      _pref.setString("phonkey",user.phoneNumber.toString());
                      MyNavigator.goToDetail(context);
//called when the otp is variefied automatically
                    });
      };
  final PhoneVerificationFailed verificationFailed=(AuthException authException){
    setState(() {
                  _message=Future<String>.value("verification failed code: ${authException.code}. Message: ${authException.message}");
                });
  };

  final PhoneCodeSent codeSent=(String verificationId,[int forceResendingToken]) async {
    this.verificationId=verificationId;


  };

  final PhoneCodeAutoRetrievalTimeout codeAutoRetrievalTimeout = (String verificationId){
    this.verificationId=verificationId;

  };

  await _auth.verifyPhoneNumber(
    phoneNumber: phon,
    timeout: Duration(seconds: 60),
    verificationCompleted: verificationCompleted,
    verificationFailed: verificationFailed,
    codeSent: codeSent,
    codeAutoRetrievalTimeout: codeAutoRetrievalTimeout
    );



}

如果电话无法检测到自动发送的otp,请以字符串形式获取otp并实现此功能

void _signInWithOtp() async{
  final FirebaseUser user = await _auth.signInWithPhoneNumber(
  verificationId: verificationId,
  smsCode: _otpController.text,
);

答案 6 :(得分:0)

我已逐步解释了带有源代码的存储库 检查以下存储库可以帮助您  https://github.com/myvsparth/flutter_otp_auth