Pratik Butani
Pratik Butani

Reputation: 62429

Firebase : updatePhoneNumber for Current User who logged in with google

Firebase developers, I used login with google in one of my application and successfully done.

Problem: I am getting Display Name and Email Id from Google but not getti get Phone Number. So I am taking that phone number from user in next activity.

Now If I want to update that phone number to current user of Firebase then what are the ways to do that.

I have found one method that is FirebaseAuth.getInstance().getCurrentUser().updatePhoneNumber() but didn't get any proper idea to use this.

If you have implemented this thing, help me.

Appreciated advance.

Thank you.

Upvotes: 2

Views: 4545

Answers (4)

Usama Shahid
Usama Shahid

Reputation: 865

You can do this in React Native.

 handlePhone=()=>{
 const auth = firebase.auth();
 const {phoneNumber} = this.state;
 const self = this;
 if(phoneNumber != ''){
  try{
    const snapshot = await auth.verifyPhoneNumber(`+92${phoneNumber}`).on('state_changed',
      async (phoneAuthSnapshot) => {
        switch(phoneAuthSnapshot.state){
          case firebase.auth.PhoneAuthState.CODE_SENT:
            self.setState({verificationSnapshot:phoneAuthSnapshot,showOTP:true})
        }
      })
  }catch(error){
    console.log(error);
    this.showAlert('Try again later');
  }
}else{
  this.showAlert('Please enter phone number.');
}
}


handleVerifyOTP=()=>{
const {verificationCode, verificationSnapshot} = this.state;
    console.log(verificationCode, verificationSnapshot)
    const self = this;
    try{
        const  credential = await firebase.auth.PhoneAuthProvider.credential(verificationSnapshot.verificationId, verificationCode);
        console.log(credential)
        const u =  await firebase.auth().currentUser.updatePhoneNumber(credential);
        console.log(u)
        self.setState({showOTP:false,phoneNumberState:true});
        Alert.alert('Number has been registered successfully')
    }catch(error){
        Alert.alert('Something went wrong');
        console.log(error,"ERRR")
    }
    }

Add two input fields with buttons One is for phone number Other is for OTP

Upvotes: 0

Mohamed SLimani
Mohamed SLimani

Reputation: 370

it took me a lot to find out how it could be done but here's how I did it

  1. user firebase SDK recapcha
window.recaptchaVerifier = new fireabase.auth.RecaptchaVerifier('sign-in-button', {
  size: 'invisible'
})
  1. send SMS code
const phoneNumber = this.input.phone
const appVerifier = window.recaptchaVerifier
firebase.auth().currentUser.linkWithPhoneNumber(phoneNumber, appVerifier)
 .then((confirmationResult) => {
   window.confirmationResult = confirmationResult
   // prompt user to entre code 
   ...
})
 .catch((error) => {
   // reset rechatcha and try again 
   appVerifier.reset('sign-in-button')
   alert(error.message)
})

  1. Confirm the Code and link
const code = this.input.code
window.confirmationResult.confirm(code).then((result) => {
  const credential = firebase.auth.PhoneAuthProvider.credential(window.confirmationResult.verificationId, code)
  firebase.auth().currentUser.linkWithCredential(credential)
})
  .then(() => {
    // done
  })
  .catch((error) => {
    alert(error.message)
   // try again
  })
  

Upvotes: 1

BBacon
BBacon

Reputation: 2678

Some github repo containing an implementation:

https://github.com/wardah9/QuestionsQate/blob/9224a6d2e00a9304566be063c2d611b76cc76fb8/app/src/main/java/com/questionqate/StudentProfile/UpdatedMobileAthuntication.java

You need to import and build an 'com.google.firebase.auth.PhoneAuthCredential'

To do that you need to ask your user to authenticate using their phone number using the 'com.google.firebase.auth.PhoneAuthProvider'.

Since you are using GoogleAuthProvider, you can update the user Phone Number 'by hand' using the method you posted and building the PhoneAuthCredential yourself or you need to intanciate a new PhoneAuthProvider and make the already authenticated user re-auth with his phone number (you need Phone Auth enabled in your providers at Firebase Console)

Upvotes: 0

Alex Mamo
Alex Mamo

Reputation: 138969

FirebaseUser's updatePhoneNumber() method:

Updates the phone number of the user.

And as you can see, it takes as an argument a PhoneAuthCredential object. So in order to update the phone number of the corresponding user, call updatePhoneNumber() method and pass the new phone credential object as an argument.

Important: this is a security sensitive operation that requires the user to have recently signed in. If this requirement isn't met, ask the user to authenticate again and later call reauthenticate(AuthCredential).

Upvotes: 3

Related Questions