React Ionic中的Firebase电话认证

pokxtpni  于 2023-09-28  发布在  Ionic
关注(0)|答案(1)|浏览(163)

我正在使用firebase电话认证在react ionic应用程序中验证电话号码。它在网页版上运行得很好,但我在iOS上得到了这个错误。
未处理的Promise拒绝:FirebaseError:Firebase:错误(auth/internal-error)。wrapNativeSuper.js
这是我的代码。

import { initializeApp, getApp } from "firebase/app"
import { Capacitor } from "@capacitor/core"
import { getAuth, initializeAuth, indexedDBLocalPersistence } from "firebase/auth"

export const firebaseConfig = {
    apiKey: "XXX",
    authDomain: "XXX.firebaseapp.com",
    projectId: "XXX",
    storageBucket: "XXX",
    messagingSenderId: "XXX",
    appId: "XXX",
    measurementId: "XXX"
  };

const firebaseApp = initializeApp(firebaseConfig)
let auth
export function getFirebaseAuth() {
  if (!auth) {
    if (Capacitor.isNativePlatform()) {
      auth = initializeAuth(getApp(), { persistence: indexedDBLocalPersistence })
    } else {
      auth = getAuth()
    }
  }
  return auth
}

export default  firebaseApp

这是执行部分。

import { getAuth, RecaptchaVerifier, signInWithPhoneNumber, PhoneAuthProvider  } from "firebase/auth";
import { useEffect } from 'react';
import { getFirebaseAuth  } from "../firebaseInit";

...

const auth = getFirebaseAuth()

const recaptchaVerifier = new RecaptchaVerifier("recaptcha-container", {
    size: "invisible",
},auth);
signInWithPhoneNumber(auth, `+81${phonenumber}`, recaptchaVerifier)
.then((confirmationResult) => {
     ...
})

我根据本教程在XCode中添加了URL类型。
设置reCAPTCHA验证

deyfvvtc

deyfvvtc1#

以下是在React Ionic应用程序中使用Firebase进行电话身份验证的示例实现:
firebaseConfig对象中的"YOUR_API_KEY""YOUR_AUTH_DOMAIN"和其他占位符替换为实际的Firebase项目详细信息。
在单独的文件firebaseInit.js:中设置Firebase配置并初始化Firebase应用程序

import { initializeApp } from "firebase/app";
import { getAuth, RecaptchaVerifier, signInWithPhoneNumber } from "firebase/auth";

const firebaseConfig = {
  apiKey: "YOUR_API_KEY",
  authDomain: "YOUR_AUTH_DOMAIN",
  projectId: "YOUR_PROJECT_ID",
  storageBucket: "YOUR_STORAGE_BUCKET",
  messagingSenderId: "YOUR_MESSAGING_SENDER_ID",
  appId: "YOUR_APP_ID",
  measurementId: "YOUR_MEASUREMENT_ID",
};

const firebaseApp = initializeApp(firebaseConfig);
const auth = getAuth(firebaseApp);
const recaptchaVerifier = new RecaptchaVerifier("recaptcha-container", {
  size: "invisible",
});

export { auth, recaptchaVerifier };

创建处理电话身份验证的组件PhoneAuth.js:

import React, { useState } from "react";
import { IonContent, IonHeader, IonPage, IonTitle, IonToolbar, IonButton } from "@ionic/react";
import { auth, recaptchaVerifier } from "../firebaseInit";

const PhoneAuth = () => {
  const [phoneNumber, setPhoneNumber] = useState("");
  const [verificationCode, setVerificationCode] = useState("");
  const [verificationId, setVerificationId] = useState(null);

  const handleSendCode = () => {
    signInWithPhoneNumber(auth, `+81${phoneNumber}`, recaptchaVerifier)
      .then((confirmationResult) => {
        setVerificationId(confirmationResult.verificationId);
        // The verification code will be sent to the user's phone
      })
      .catch((error) => {
        console.error("Error sending verification code:", error);
      });
  };

  const handleVerifyCode = () => {
    const credential = PhoneAuthProvider.credential(verificationId, verificationCode);
    signInWithPhoneNumber(auth, credential)
      .then((userCredential) => {
        const user = userCredential.user;
        // User is now signed in with their phone number
      })
      .catch((error) => {
        console.error("Error verifying code:", error);
      });
  };

  return (
    <IonPage>
      <IonHeader>
        <IonToolbar>
          <IonTitle>Phone Authentication</IonTitle>
        </IonToolbar>
      </IonHeader>
      <IonContent>
        <div>
          <input type="tel" value={phoneNumber} onChange={(e) => setPhoneNumber(e.target.value)} />
          <IonButton onClick={handleSendCode}>Send Verification Code</IonButton>
        </div>
        {verificationId && (
          <div>
            <input type="text" value={verificationCode} onChange={(e) => setVerificationCode(e.target.value)} />
            <IonButton onClick={handleVerifyCode}>Verify Code</IonButton>
          </div>
        )}
        <div id="recaptcha-container"></div>
      </IonContent>
    </IonPage>
  );
};

export default PhoneAuth;

主应用组件,使用PhoneAuth组件:

import React from "react";
import { IonApp, IonRouterOutlet } from "@ionic/react";
import { IonReactRouter } from "@ionic/react-router";
import { Route, Redirect } from "react-router-dom";
import PhoneAuth from "./components/PhoneAuth";

const App = () => (
  <IonApp>
    <IonReactRouter>
      <IonRouterOutlet>
        <Route exact path="/" render={() => <Redirect to="/phone-auth" />} />
        <Route path="/phone-auth" component={PhoneAuth} />
      </IonRouterOutlet>
    </IonReactRouter>
  </IonApp>
);

export default App;

当用户输入他们的电话号码并点击“发送验证码”时,验证码将被发送到他们的手机上。然后,他们可以输入验证码并单击“验证码”以完成身份验证过程。

相关问题