【问题标题】:Flutter + Firebase - Link Phone Number with Existing AccountFlutter + Firebase - 将电话号码与现有帐户关联
【发布时间】:2021-06-26 09:58:09
【问题描述】:

我已经在 Flutter 中使用 Firebase 实现了电子邮件身份验证。我想从用户那里获取电话号码并通过发送 OTP 来验证它以确保它属于他们,然后将他们的电话号码与他们之前使用电子邮件创建的帐户相关联。

为此,我做了以下工作:

verifyPhoneNumber() async {
    await auth.verifyPhoneNumber(
      phoneNumber: '+92${widget.phoneNumber}',
      verificationCompleted: (PhoneAuthCredential credential) async {
        await auth.currentUser.updatePhoneNumber(credential);
        // either this occurs or the user needs to manually enter the SMS code
      },
      verificationFailed: (FirebaseAuthException e) {
        print(e.message);
      },
      codeSent: (String verificationId, int resendToken) {
        setState(() {
          _otpcode = verificationId;
        });
      },
      codeAutoRetrievalTimeout: (String verificationId) {
        setState(() {
          _otpcode = verificationId;
        });
      },
    );
  }

以上代码将 OTP 发送到号码。现在,当用户将接收到的代码输入到 TextField 中时,我想验证两者是否匹配,以便我可以继续 updatePhoneNumber。

我不确定如何实现验证部分。我有以下代码,不知道如何输出错误(如果有)或确认验证确实发生了。

verifyPhoneCode(otp, code) async {
  final AuthCredential credential =
      PhoneAuthProvider.credential(verificationId: otp, smsCode: code);
  await auth.currentUser.updatePhoneNumber(credential);
}

【问题讨论】:

    标签: firebase flutter firebase-authentication


    【解决方案1】:

    好的,我终于找到了解决方案。要将电话号码与现有帐户关联,请使用 .linkWithCredential

    final AuthCredential credential =
        PhoneAuthProvider.credential(
            verificationId: _otpcode,
            smsCode: val,
        );
    currentUser
        .linkWithCredential(credential);
    

    我希望它可以帮助任何寻找类似问题的解决方案的人。

    【讨论】:

      【解决方案2】:

      我建议你通过官方firebase flutter docs。他们在那里以礼貌的方式解释了电话身份验证步骤中涉及的所有步骤。

      此外,这里是来自官方文档的代码sn-p,它指的是电话验证步骤。

      FirebaseAuth auth = FirebaseAuth.instance;
      
      await auth.verifyPhoneNumber(
        phoneNumber: '+44 7123 123 456',
        codeSent: (String verificationId, int resendToken) async {
          // Update the UI - wait for the user to enter the SMS code
          String smsCode = 'xxxx';
      
          // Create a PhoneAuthCredential with the code
          PhoneAuthCredential phoneAuthCredential = PhoneAuthProvider.credential(verificationId: verificationId, smsCode: smsCode);
      
          // Sign the user in (or link) with the credential
          await auth.signInWithCredential(phoneAuthCredential);
        },
      );
      

      【讨论】:

      • 萨尔曼感谢您的友好回复。我不希望使用电话号码进行身份验证。我只想验证 OTP 并与现有用户凭据链接。
      • 好吧,我的错。可能是我没有正确理解您的问题。
      猜你喜欢
      • 1970-01-01
      • 2019-01-11
      • 1970-01-01
      • 2019-11-21
      • 2018-03-21
      • 1970-01-01
      • 2021-03-01
      • 2019-11-17
      • 1970-01-01
      相关资源
      最近更新 更多