最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

iphone - There is an error when sending the code while logging in with a phone number in React Native Firebase - Stack Overflow

programmeradmin3浏览0评论

I am trying to create a registration with a phone number in my React Native project using Firebase, but I am getting this error:

[auth/internal-error] An internal error has occurred, please try again.

I removed my phone number from the test phone numbers, added the GoogleServices.json file, and I should receive an SMS on my Android device instead of the iOS simulator, but I am getting an error. Can you help me?

function onAuthStateChanged(user: any) {
    if (user) {
      console.log('User is logged in');
    }
  }

  const fetchUserDetails = async () => {
    console.log('fetch user details...')
    try {
      const response = await apiClient('GET', '/social/userDetails', null, true)
      console.log('resssssss', response)
      if (response && response.data) {
        setUser({
          email: '',
          phoneNumber: '+90' + phoneNumber,
          fullName: response.data?.name || '',
          profileImage: response.data?.picture || '',
          userId: response.data?.userId || ''
        })
        return navigation.navigate(appRoutes.TAB_NAVIGATOR)
      }
      return navigation.navigate(authRoutes.SELECTION_CATEGORIES)
    } catch (error: any) {
      console.log('error-login', error)
      navigation.navigate(authRoutes.SELECTION_CATEGORIES)
    }
  }
  useEffect(() => {
    const subscriber = auth().onAuthStateChanged(onAuthStateChanged);
    return subscriber;
  }, []);

  const handleSendCode = async () => {
    try {
      setLoading(true);
      const phoneWithCountryCode = `+90${phoneNumber}`;

      const phoneAuthListener = firebase.auth().verifyPhoneNumber(phoneWithCountryCode);
      phoneAuthListener.on('state_changed', (phoneAuthSnapshot) => {
        if (phoneAuthSnapshot.state === 'sent') {
          console.log('SMS code sent successfully.');
          setVerificationId(phoneAuthSnapshot.verificationId);
          setIsVerification(true);
        }
      }, (phoneAuthError) => {
        console.error('Error sending code: ', phoneAuthError.message);
      });

    } catch (error) {
      console.error('Error sending code:', error);
    } finally {
      setLoading(false);
    }
  };

  const handleVerifyCode = async () => {
    try {
      setLoading(true);
      if (!verificationCode || !verificationId) return;

      const credential = firebase.auth.PhoneAuthProvider.credential(verificationId, verificationCode);
      try {
        const userCredential = await auth().signInWithCredential(credential);
        const authToken = await userCredential.user.getIdToken(true);
        stroage.set("auth-token", authToken);

        if (authToken) {
          await fetchUserDetails();
        }
      } catch (error: any) {
        // Kod hatalı ise Alert göster
        Alert.alert(
          "Verification Failed",
          "The code you entered is incorrect. Please try again.",
          [{ text: "OK", onPress: () => setVerificationCode('') }]
        );
      }
    } catch (error) {
      console.log('Invalid code:', error);
    } finally {
      setLoading(false);
    }
  };

  return (
    <TouchableWithoutFeedback onPress={Keyboard.dismiss}>
      <KeyboardAvoidingView
        behavior={Platform.OS === "ios" ? "padding" : "height"}
        style={styles.background}
      >
        <View style={{ flexDirection: 'row', justifyContent: 'space-between', top: Platform.OS === 'ios' ? '10%' : '5%' }}>
          <View style={{ flexDirection: 'row', justifyContent: 'center', left: 15 }}>
            <Text style={{ color: '#FFFFFF', fontSize: 18, fontWeight: '700' }}>Following</Text>
            <View style={{ marginLeft: 10 }}>
              <Text style={{ color: '#FFFFFF', fontSize: 18, fontWeight: '700' }}>For you</Text>
              <View
                style={{
                  height: 4,
                  backgroundColor: '#FFFFFF',
                  marginTop: 5,
                  alignSelf: 'center',
                  width: 29,
                }}
              />
            </View>
          </View>
          <View style={{ right: 10 }}>
            <Icon.SearchIcon width={22.71} height={22.48} />
          </View>
        </View>
        <Video
          source={require('assets/videos/cow.mp4')}
          style={styles.backgroundVideo}
          resizeMode="cover"
          repeat
          muted
        />
        <View style={styles.container}>
          <View style={styles.bottomView}>
            <View style={{ top: 10, flex: 1 }}>
              <Text style={styles.title}>
                {isVerification ? 'Enter your Verification Code ?' : "What's your Phone Number ?"}
              </Text>
              <Text style={styles.subtitle}>
                {isVerification ? `Enter the code sent to +${phoneNumber}` : 'We want to make sure its really you'}
              </Text>
              <View style={{ marginTop: 30 }}>
                {!isVerification ? (
                  <>
                    <TextInput
                      style={styles.input}
                      placeholder="Phone Number"
                      value={phoneNumber}
                      onChangeText={setPhoneNumber}
                      keyboardType="phone-pad"
                      maxLength={10}
                    />
                    <Text style={styles.inputText}>IN +90</Text>
                  </>
                ) : (
                  <TextInput
                    style={[
                      styles.input,
                      {
                        paddingLeft: 15,
                        fontSize: verificationCode.length > 0 ? 18 : 14,
                        fontWeight: verificationCode.length > 0 ? '700' : '500',
                        letterSpacing: verificationCode.length > 0 ? 1.5 : 0,
                        color: verificationCode.length > 0 ? '#1F1D2B' : '#545454'
                      }
                    ]}
                    placeholder="Enter Code here*"
                    placeholderTextColor="#545454"
                    value={verificationCode}
                    onChangeText={setVerificationCode}
                    keyboardType="number-pad"
                    maxLength={6}
                  />
                )}
              </View>
            </View>
            <View>
              <Button
                title={isVerification ? "Submit" : "Send Code"}
                onPress={isVerification ? handleVerifyCode : handleSendCode}
                loading={loading}
                textStyle={{ color: colors.darkGreen, fontSize: 16, fontWeight: '700' }}
                containerStyle={{ marginBottom: 15 }}
                disabled={isVerification ? verificationCode.length !== 6 : phoneNumber.length !== 10}
              />
              {isVerification && (
                <TouchableWithoutFeedback onPress={() => { }}>
                  <Text style={styles.resendCode}>Resend Code</Text>
                </TouchableWithoutFeedback>
              )}
            </View>
          </View>
        </View>
      </KeyboardAvoidingView>
    </TouchableWithoutFeedback>
  );
};

I am trying to create a registration with a phone number in my React Native project using Firebase, but I am getting this error:

[auth/internal-error] An internal error has occurred, please try again.

I removed my phone number from the test phone numbers, added the GoogleServices.json file, and I should receive an SMS on my Android device instead of the iOS simulator, but I am getting an error. Can you help me?

function onAuthStateChanged(user: any) {
    if (user) {
      console.log('User is logged in');
    }
  }

  const fetchUserDetails = async () => {
    console.log('fetch user details...')
    try {
      const response = await apiClient('GET', '/social/userDetails', null, true)
      console.log('resssssss', response)
      if (response && response.data) {
        setUser({
          email: '',
          phoneNumber: '+90' + phoneNumber,
          fullName: response.data?.name || '',
          profileImage: response.data?.picture || '',
          userId: response.data?.userId || ''
        })
        return navigation.navigate(appRoutes.TAB_NAVIGATOR)
      }
      return navigation.navigate(authRoutes.SELECTION_CATEGORIES)
    } catch (error: any) {
      console.log('error-login', error)
      navigation.navigate(authRoutes.SELECTION_CATEGORIES)
    }
  }
  useEffect(() => {
    const subscriber = auth().onAuthStateChanged(onAuthStateChanged);
    return subscriber;
  }, []);

  const handleSendCode = async () => {
    try {
      setLoading(true);
      const phoneWithCountryCode = `+90${phoneNumber}`;

      const phoneAuthListener = firebase.auth().verifyPhoneNumber(phoneWithCountryCode);
      phoneAuthListener.on('state_changed', (phoneAuthSnapshot) => {
        if (phoneAuthSnapshot.state === 'sent') {
          console.log('SMS code sent successfully.');
          setVerificationId(phoneAuthSnapshot.verificationId);
          setIsVerification(true);
        }
      }, (phoneAuthError) => {
        console.error('Error sending code: ', phoneAuthError.message);
      });

    } catch (error) {
      console.error('Error sending code:', error);
    } finally {
      setLoading(false);
    }
  };

  const handleVerifyCode = async () => {
    try {
      setLoading(true);
      if (!verificationCode || !verificationId) return;

      const credential = firebase.auth.PhoneAuthProvider.credential(verificationId, verificationCode);
      try {
        const userCredential = await auth().signInWithCredential(credential);
        const authToken = await userCredential.user.getIdToken(true);
        stroage.set("auth-token", authToken);

        if (authToken) {
          await fetchUserDetails();
        }
      } catch (error: any) {
        // Kod hatalı ise Alert göster
        Alert.alert(
          "Verification Failed",
          "The code you entered is incorrect. Please try again.",
          [{ text: "OK", onPress: () => setVerificationCode('') }]
        );
      }
    } catch (error) {
      console.log('Invalid code:', error);
    } finally {
      setLoading(false);
    }
  };

  return (
    <TouchableWithoutFeedback onPress={Keyboard.dismiss}>
      <KeyboardAvoidingView
        behavior={Platform.OS === "ios" ? "padding" : "height"}
        style={styles.background}
      >
        <View style={{ flexDirection: 'row', justifyContent: 'space-between', top: Platform.OS === 'ios' ? '10%' : '5%' }}>
          <View style={{ flexDirection: 'row', justifyContent: 'center', left: 15 }}>
            <Text style={{ color: '#FFFFFF', fontSize: 18, fontWeight: '700' }}>Following</Text>
            <View style={{ marginLeft: 10 }}>
              <Text style={{ color: '#FFFFFF', fontSize: 18, fontWeight: '700' }}>For you</Text>
              <View
                style={{
                  height: 4,
                  backgroundColor: '#FFFFFF',
                  marginTop: 5,
                  alignSelf: 'center',
                  width: 29,
                }}
              />
            </View>
          </View>
          <View style={{ right: 10 }}>
            <Icon.SearchIcon width={22.71} height={22.48} />
          </View>
        </View>
        <Video
          source={require('assets/videos/cow.mp4')}
          style={styles.backgroundVideo}
          resizeMode="cover"
          repeat
          muted
        />
        <View style={styles.container}>
          <View style={styles.bottomView}>
            <View style={{ top: 10, flex: 1 }}>
              <Text style={styles.title}>
                {isVerification ? 'Enter your Verification Code ?' : "What's your Phone Number ?"}
              </Text>
              <Text style={styles.subtitle}>
                {isVerification ? `Enter the code sent to +${phoneNumber}` : 'We want to make sure its really you'}
              </Text>
              <View style={{ marginTop: 30 }}>
                {!isVerification ? (
                  <>
                    <TextInput
                      style={styles.input}
                      placeholder="Phone Number"
                      value={phoneNumber}
                      onChangeText={setPhoneNumber}
                      keyboardType="phone-pad"
                      maxLength={10}
                    />
                    <Text style={styles.inputText}>IN +90</Text>
                  </>
                ) : (
                  <TextInput
                    style={[
                      styles.input,
                      {
                        paddingLeft: 15,
                        fontSize: verificationCode.length > 0 ? 18 : 14,
                        fontWeight: verificationCode.length > 0 ? '700' : '500',
                        letterSpacing: verificationCode.length > 0 ? 1.5 : 0,
                        color: verificationCode.length > 0 ? '#1F1D2B' : '#545454'
                      }
                    ]}
                    placeholder="Enter Code here*"
                    placeholderTextColor="#545454"
                    value={verificationCode}
                    onChangeText={setVerificationCode}
                    keyboardType="number-pad"
                    maxLength={6}
                  />
                )}
              </View>
            </View>
            <View>
              <Button
                title={isVerification ? "Submit" : "Send Code"}
                onPress={isVerification ? handleVerifyCode : handleSendCode}
                loading={loading}
                textStyle={{ color: colors.darkGreen, fontSize: 16, fontWeight: '700' }}
                containerStyle={{ marginBottom: 15 }}
                disabled={isVerification ? verificationCode.length !== 6 : phoneNumber.length !== 10}
              />
              {isVerification && (
                <TouchableWithoutFeedback onPress={() => { }}>
                  <Text style={styles.resendCode}>Resend Code</Text>
                </TouchableWithoutFeedback>
              )}
            </View>
          </View>
        </View>
      </KeyboardAvoidingView>
    </TouchableWithoutFeedback>
  );
};
Share Improve this question edited Feb 15 at 15:42 Frank van Puffelen 600k85 gold badges889 silver badges859 bronze badges Recognized by Google Cloud Collective asked Feb 15 at 15:06 burak kılınçburak kılınç 1 New contributor burak kılınç is a new contributor to this site. Take care in asking for clarification, commenting, and answering. Check out our Code of Conduct. 0
Add a comment  | 

1 Answer 1

Reset to default 0

Try using signInWithPhoneNumber instead of verifyPhoneNumber

Modify your handleSendCode function like this:

const handleSendCode = async () => {
  try {
    setLoading(true);
    const phoneWithCountryCode = `+90${phoneNumber}`;

    const confirmation = await auth().signInWithPhoneNumber(phoneWithCountryCode);
    setVerificationId(confirmation.verificationId);
    setIsVerification(true);
    console.log("SMS sent successfully.");
  } catch (error) {
    console.error("Error sending code:", error);
    Alert.alert("Error", "Failed to send verification code. Please try again.");
  } finally {
    setLoading(false);
  }
};

与本文相关的文章

发布评论

评论列表(0)

  1. 暂无评论