firebase, flutter 为已经注册邮箱密码的用户添加phone号验证

Add phone number verification to a user already registered with email password in firebase, flutter

在我的应用程序中,有一个登录屏幕、注册屏幕和一个 showProfile 屏幕。我正在使用电子邮件和密码注册用户。在注册屏幕中,有包含图像、名字、姓氏和 phone 编号的字段。我可以通过这样做将用户显示名称、图像 URL 添加到特定用户-

UserCredential user = await _auth.createUserWithEmailAndPassword(email: _email, password: _password);
var newUser = user.user;
if (newUser != null) {
    Reference imgReference = firebaseStorage.ref().child('UserImages/$_email');
    UploadTask uploadTask = imgReference.putFile(imgFile);
    TaskSnapshot taskSnapshot = await uploadTask;
    String url = await taskSnapshot.ref.getDownloadURL();
    if (url != null) {
       setState(() {
          imgUrl = url;
       });
    }
    await newUser.updatePhotoURL(imgUrl);
    await newUser.updateDisplayName(_firstName + ' ' + _lastName);
    await newUser.reload();
}

现在我想在注册过程中向用户添加 phone 没有 OTP 验证。 .但是如果不使用 phone no.

创建另一个用户帐户,我就无法对 phone no 做同样的事情

以便在成功登录后,在我的 showProfile 屏幕中我可以解析用户 phone 否。通过 user.phoneNumber 到屏幕,就像我可以为 user.displayName & user.photoURL 没有遇到任何问题。

有什么方法可以在注册的邮箱账户中添加phone否吗?我搜索了一下,但找不到任何可以开始的东西。

使用 Firebase 身份验证验证 phone 号码被视为使用该提供商登录。因此,不是向现有登录添加 phone 号码,而是您实际上要使用另一个提供商登录用户,然后将该新提供商链接到现有用户配置文件。

步骤与signing in with a phone number, but instead of calling signInWithCredential(credential) with the phone credentials, you call linkWithCredential(credential) on the current user as shown in the documentation on account linking大体相似。

上面是 Android 文档的链接,因为我觉得这些文档最清楚地记录了这个过程,并且跨平台的过程是相似的。对于 FlutterFire 等效项,请参阅 phone auth and account linking.

的文档

经过长时间的搜索、查找和尝试解决方案,我终于能够解决我的问题。使用 firebase OTP 验证向已注册的电子邮件传递帐户添加了一个 phone 号码。值得庆幸的是,这个 对我来说非常好。这是代码:

final _auth = FirebaseAuth.instance;
final userInfo = _auth.currentUser;    

Future<void> phoneVerification() async {
        await _auth.verifyPhoneNumber(
          phoneNumber: _mobile,
          verificationCompleted: (PhoneAuthCredential phoneAuthCredential) async {
            /// This is the main important line to link
            await userInfo.linkWithCredential(phoneAuthCredential);
            // Not nessecary
            /* User? refreshedUser = await refreshUser(userInfo);
            if (refreshedUser != null) {
              setState(() {
                userInfo = refreshedUser;
              });
            } */
          },
          verificationFailed: (FirebaseAuthException e) {
           // Handle error
            print(e);
          },
          codeSent: (String verificationId, int? resendToken) async {
            // write the code to handle the OTP code sent for manual verification in case autoverify doesn't work
          },
          codeAutoRetrievalTimeout: (String verificationId) {
            // Do Something for SMS request timeout
          },
        );
      }