firebase - Flutter + Firebase - 将电话号码与现有帐户相关联

标签 firebase flutter firebase-authentication

我已经在 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 中时,我想验证两者是否匹配,以便我可以继续更新电话号码。

我不确定如何实现验证部分。我有以下代码,但不确定如何输出错误或确认验证是否发生。

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

最佳答案

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

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

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

关于firebase - Flutter + Firebase - 将电话号码与现有帐户相关联,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66870016/

相关文章:

java - 在 Playstore 上发布后,OTP 未获取,但在 Android Studio 中运行良好

android - 无法更改从 Firebase 控制台发送的 Firebase 云消息传递通知的默认图标

android - 如何删除此警告 "Please apply google-services plugin at the bottom of the build file."

ios - 为什么我的 UICollectionView 无法访问我在 for 循环中创建的数组 - fatal error : Index out of range

firebase - 更新 Firebase 实时数据库对象中的特定值

swift - Firebase 短信密码重置

javascript - firebase v3 - 谷歌身份验证 "internal-error"

android - 某些 Android 设备中的 Firebase AUTHENTICATION_FAILED(java.io.IOException)

sqlite - Flutter中的Sqflite,使用两个数据库(附件)

dart - 如何使用 Positioned 小部件定位在堆栈的右上角