Reputation: 4519
I have implemented Email Authentication using Firebase in Flutter. I want to take the phone number from the user and verify it by sending an OTP to ensure it belongs to them and then link their phone number with the account they created earlier using email.
For this purpose I did the following:
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;
});
},
);
}
The above code sends the OTP to the number. Now when the user enters the received code into the TextField I want to verify that both match so I can proceed with updatePhoneNumber.
I am not sure how to implement the verification part. I have the following code and not sure how to output the errors if any or to confirm the verification did happen.
verifyPhoneCode(otp, code) async {
final AuthCredential credential =
PhoneAuthProvider.credential(verificationId: otp, smsCode: code);
await auth.currentUser.updatePhoneNumber(credential);
}
Upvotes: 3
Views: 2705
Reputation: 4519
Ok I have finally figured out the solution. In order to link phone number with an already existing account use .linkWithCredential
final AuthCredential credential =
PhoneAuthProvider.credential(
verificationId: _otpcode,
smsCode: val,
);
currentUser
.linkWithCredential(credential);
I hope it helps anyone looking for a solution to a similar problem.
Upvotes: 4
Reputation: 55
I recommend you to go through the official firebase flutter docs. There they explained all the steps involved during the phone authentication step in a well mannered way.
Moreover, here is the code snippet from official docs which refers to the phone verification steps.
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);
},
);
Upvotes: -1