如何在 React Native 中使用 Firebase 电话身份验证而无需重新验证码 [英] How to Use Firebase Phone Authentication without recaptcha in React Native

查看:30
本文介绍了如何在 React Native 中使用 Firebase 电话身份验证而无需重新验证码的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在 React Native 中使用没有 recaptcha 的 firebase 电话验证.下面是我的代码.代码工作正常.但我不想使用recaptcha.我尝试删除它,但它给出了错误.我是本机反应的新手.请给出以下问题的正确解决方案.我的代码在下面检查并给出解决方案.谢谢

I want to use firebase phone verification without recaptcha in react native. Below is my code. The code is working properly. But I Don't want to use recaptcha. I try deleting it but it gives error. I am new to react native. Please give proper solution of the following problem. My code is given Below Check It and give solution. Thank You

import * as React from 'react';
import { Text, View, StyleSheet, TextInput,Image,TouchableOpacity,ActivityIndicator,Alert } from 'react-native';
import * as FirebaseRecaptcha from "expo-firebase-recaptcha";
import * as firebase from "firebase";

// PROVIDE VALID FIREBASE CONFIG HERE
// https://firebase.google.com/docs/web/setup
const FIREBASE_CONFIG: any = {
  
};

try {
  if (FIREBASE_CONFIG.apiKey) {
    firebase.initializeApp(FIREBASE_CONFIG);
  }
} catch (err) {
  // ignore app already initialized error on snack
}

export default function App() {
  const recaptchaVerifier = React.useRef(null);
  const verificationCodeTextInput = React.useRef(null);
  const [phoneNumber, setPhoneNumber] = React.useState("");
  const [verificationId, setVerificationId] = React.useState("");
  const [verifyError, setVerifyError] = React.useState<Error>();
  const [verifyInProgress, setVerifyInProgress] = React.useState(false);
  const [verificationCode, setVerificationCode] = React.useState("");
  const [confirmError, setConfirmError] = React.useState<Error>();
  const [confirmInProgress, setConfirmInProgress] = React.useState(false);
  const isConfigValid = !!FIREBASE_CONFIG.apiKey;
  return (
    <View style={styles.container}>
         <FirebaseRecaptcha.FirebaseRecaptchaVerifierModal
          ref={recaptchaVerifier}
          firebaseConfig={FIREBASE_CONFIG}
        />
      <View style={styles.first}>
        <Text style={{color:'white',fontSize:25,fontWeight:'bold'}}>Welcome</Text>
      </View>
      <View style={styles.second}>
        <Text style={{paddingVertical:5}}>Phone No</Text>
        <View style={styles.fileds}>
            <Image style={styles.logo} source={require('./assets/user.png')} />
            <TextInput style={styles.input}
             autoFocus={isConfigValid}
             autoCompleteType="tel"
             keyboardType="phone-pad"
             textContentType="telephoneNumber"
             editable={!verificationId}
             onChangeText={(phoneNumber: string) => setPhoneNumber(phoneNumber)}
            />
        </View>
        <TouchableOpacity style={styles.button} 
        disabled={!phoneNumber}
        onPress={async () => {
          const phoneProvider = new firebase.auth.PhoneAuthProvider();
          try {
            setVerifyError(undefined);
            setVerifyInProgress(true);
            setVerificationId("");
            const verificationId = await phoneProvider.verifyPhoneNumber(
              phoneNumber,
              recaptchaVerifier.current
            );
            setVerifyInProgress(false);
            setVerificationId(verificationId);
            verificationCodeTextInput.current?.focus();
          } catch (err) {
            setVerifyError(err);
            setVerifyInProgress(false);
          }
        }}
        >
          <Text style={{alignSelf:'center',color:'white'}}>{`${verificationId ? "Resend" : "Send"} OTP`}</Text>
        </TouchableOpacity>
        {verifyError && (
          <Text style={styles.error}>{`Error: ${verifyError.message}`}</Text>
        )}
        {verifyInProgress && <ActivityIndicator style={styles.loader} />}
        {verificationId ? (
          <Text style={styles.success}>
            A verification code has been sent to your phone
          </Text>
        ) : undefined}
        <Text style={{paddingTop:25,paddingBottom:5}}>OTP</Text>
        <View style={styles.fileds}>
          <Image style={styles.logo} source={require('./assets/password.png')} />
          <TextInput
          ref={verificationCodeTextInput}
          style={styles.input}
          editable={!!verificationId}
          placeholder="123456"
          onChangeText={(verificationCode: string) =>
            setVerificationCode(verificationCode)
          }
        />
        </View>
        <TouchableOpacity style={styles.button} 
          disabled={!verificationCode}
          onPress={async () => {
            try {
              setConfirmError(undefined);
              setConfirmInProgress(true);
              const credential = firebase.auth.PhoneAuthProvider.credential(
                verificationId,
                verificationCode
              );
              const authResult = await firebase
                .auth()
                .signInWithCredential(credential);
              setConfirmInProgress(false);
              setVerificationId("");
              setVerificationCode("");
              verificationCodeTextInput.current?.clear();
              Alert.alert("Phone authentication successful!");
            } catch (err) {
              setConfirmError(err);
              setConfirmInProgress(false);
            }
          }}>
          <Text style={{alignSelf:'center',color:'white'}}>Confirm OTP</Text>
        </TouchableOpacity>
        {confirmError && (
          <Text style={styles.error}>{`Error: ${confirmError.message}`}</Text>
        )}
        {confirmInProgress && <ActivityIndicator style={styles.loader} />}
      </View>
    </View>
  );
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
  },
  first: {
    height:'30%',
    width:'100%',
    backgroundColor:'rgb(26, 47, 94)',
    justifyContent:'center',
    padding:20
  },
  second:{
    paddingVertical:30,
    paddingHorizontal:20,
    borderTopLeftRadius:15,
    borderTopRightRadius:15,
    marginTop:-10,
    backgroundColor:'white'
  },
  fileds:{
    flexDirection:'row',
    borderBottomColor:'grey',
    borderBottomWidth:1,
    padding:5,
  },
  logo:{
    height:20,
    width:20
  },
  button:{
    backgroundColor:'rgb(72, 126, 241)',
    padding:10,
    borderRadius:10,
    marginVertical:15
  },
  buttontwo:{
    borderColor:'rgb(72, 126, 241)',
    borderWidth:1,
    padding:10,
    borderRadius:10,
    marginVertical:15
  },
  input:{
    width:'80%'
  },
  error: {
    marginTop: 10,
    fontWeight: "bold",
    color: "red",
  },
  success: {
    marginTop: 10,
    fontWeight: "bold",
    color: "blue",
  },
  loader: {
    marginTop: 10,
  },
});

推荐答案

您无法使用默认身份验证删除验证码验证.使用匿名身份验证以避免出现验证码字母.https://firebase.google.com/docs/auth/web/anonymous-验证

You can't remove captcha verification using default authentication. Use anonymous authentication to avoid captcha letters to appear. https://firebase.google.com/docs/auth/web/anonymous-auth

但是你也可以像这样让它不可见:

But You can also make it invisible like this:

window.recaptchaVerifier = new firebase.auth.RecaptchaVerifier(
    "recaptcha-container", {
        size: "invisible"
    }
);

这篇关于如何在 React Native 中使用 Firebase 电话身份验证而无需重新验证码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆