Подтвердите номер телефона (проверка Otp) с помощью response-native-firebase

Я использую react-native-firebase v ^ 5.5.6. Теперь я хочу просто подтвердить свой номер телефона с помощью firebase. Для подтверждения номера телефона я использую

firebase.auth().verifyPhoneNumber(phoneNumber).on('state_changed', (phoneAuthSnapshot) => {

switch (phoneAuthSnapshot.state) {

  case firebase.auth.PhoneAuthState.CODE_SENT: // or 'sent'
    console.log('code sent');

    break;
  case firebase.auth.PhoneAuthState.ERROR: // or 'error'
    console.log('verification error');

    break;

  // ---------------------
  // ANDROID ONLY EVENTS
  // ---------------------
  case firebase.auth.PhoneAuthState.AUTO_VERIFY_TIMEOUT: // or 'timeout'
    console.log('auto verify on android timed out');

    break;
  case firebase.auth.PhoneAuthState.AUTO_VERIFIED: // or 'verified'

    console.log('auto verified on android');
    console.log(phoneAuthSnapshot);

    break;
}
}, (error) => {

console.log(error);
}, (phoneAuthSnapshot) => {

console.log(phoneAuthSnapshot);
});

Используя этот метод, я получил состояние сообщения, но всегда получал нулевой код

Ответ:

{verificationId: "AM5PThDkqMZC-alBDWvnn97ABxlVlFIZpEhN55sVLeR0b3_yar…rq9IksEpNBvU8tgv5kaE5CvWfIVv-Jn7YCNqVXtBrzD75j6og", code: null, error: null, state: "sent"}

Помогите, пожалуйста.

Спасибо заранее


person Pratik    schedule 15.11.2019    source источник


Ответы (1)


Вы можете сделать это с помощью этого фрагмента кода (для этого я использовал библиотеку react-native-firebase.)

firebase
  .auth()
  .verifyPhoneNumber(phoneNumber)
  .on(
    'state_changed',
    phoneAuthSnapshot => {
      switch (phoneAuthSnapshot.state) {
        case firebase.auth.PhoneAuthState.CODE_SENT:
          console.log('code sent',phoneAuthSnapshot);
          confirmResult =>
            this.setState({confirmResult, phoneError: 'Code has been sent!'});
            // this.props.navigation.navigate('SignUpOtp', {
            //   handleAddVal: this.props.navigation.state.params.handleAddVal,
            //   handleSubmit: this.props.navigation.state.params.handleSubmit,
            // });
          // this.props.navigation.navigate('SignUpPassword', {
          //   handleAddVal: this.props.navigation.state.params.handleAddVal,
          //   handleSubmit: this.props.navigation.state.params.handleSubmit,
          // });

          // on ios this is the final phone auth state event you'd receive
          // so you'd then ask for user input of the code and build a credential from it
          // as demonstrated in the `signInWithPhoneNumber` example above
          break;
        case firebase.auth.PhoneAuthState.ERROR: // or 'error'
          console.log('verification error', phoneAuthSnapshot);
          this.setState({phoneError: 'Error'});
          console.log(phoneAuthSnapshot.ERROR);
          break;
      }
    },
    error => {
      // optionalErrorCb would be same logic as the ERROR case above,  if you've already handed
      // the ERROR case in the above observer then there's no need to handle it here
      console.log(error);
      // verificationId is attached to error if required
      console.log(error.verificationId);
    },
    phoneAuthSnapshot => {
      // optionalCompleteCb would be same logic as the AUTO_VERIFIED/CODE_SENT switch cases above
      // depending on the platform. If you've already handled those cases in the observer then
      // there's absolutely no need to handle it here.

      // Platform specific logic:
      // - if this is on IOS then phoneAuthSnapshot.code will always be null
      // - if ANDROID auto verified the sms code then phoneAuthSnapshot.code will contain the verified sms code
      //   and there'd be no need to ask for user input of the code - proceed to credential creating logic
      // - if ANDROID auto verify timed out then phoneAuthSnapshot.code would be null, just like ios, you'd
      //   continue with user input logic.
      console.log('phoneAuthSnapshot', phoneAuthSnapshot);
    },
  );

убедитесь, что вы выполнили правильную настройку в консоли firebase с помощью sha1.

Если все еще возникнут проблемы, дайте мне знать !!!

person Master Wayne    schedule 18.11.2019
comment
привет, спасибо за повтор, но это все еще не работает. - person Pratik; 11.12.2019
comment
этот ответ не касается того факта, что объект PhoneAuthSnapshot содержит null для значения кода подтверждения, отправленного firebase. - person Jim; 17.01.2020