简体   繁体   中英

Firebase phone auth react js

I am trying to implement firebase phone authentication in react js without using the firebase UI . How do I do it?

code

 requestVerificationCode = () => { const { phoneNumber } = this.state; const appVerifier = new firebase.auth.RecaptchaVerifier( "recaptcha-container" ); if (phoneNumber < 10) { this.setState({ error: true }); } else { this.setState({ message: "Sending code ..." }); firebase .auth() .signInWithPhoneNumber(phoneNumber, appVerifier) .then(confirmResult => this.setState({ confirmResult, verifying: true }) ) .catch(error => this.setState({ message: `Sign In With Phone Number Error: ${error.message}` }) ); } };

error


auth.esm.js:282 Uncaught K {code: "auth/argument-error", message: "reCAPTCHA container is either not found or already contains inner elements!"}

The important part is to wait for componentDidMount() or mounted() in Vue JS so that the dom element containing "recaptcha-container" is mounted.

HTML

<input id="recaptcha-container" type="button" onClick="this.onClick" />

JS

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

onClick() {
    const phoneNumber = this.phone;
    const appVerifier = window.recaptchaVerifier;
    firebase
    .auth()
    .signInWithPhoneNumber(phoneNumber, appVerifier)
    .then(confirmResult => {
      // success
    })
    .catch(error => {
      // error
    });
}

If you re-direct the user away from your component where id="recaptcha-container" lives, then recaptcha will work fine but throw a style related error in the console, but that's because it's wants a permanent place on the page.

In React JS you will need to put this in index.html in public folder.

<input id="recaptcha-container" type="button" onClick="this.onClick" />

Alternatively, you can also create the html on dom.

  const tag = document.createElement("input");
  tag.id = "recaptcha-container"; // need to be same id as your firebase.auth.RecaptchaVerifier below
  tag.type="button" 
  tag.onClick="this.onClick"
  document.body.appendChild(tag);

then

window.recaptchaVerifier = new firebase.auth.RecaptchaVerifier("recaptcha-container", {
    size: "invisible",
    callback: (response) => {
      // reCAPTCHA solved, allow signInWithPhoneNumber.
      console.log("Submitted  window.recaptchaVerifier: ", response);

    },
    "expired-callback": (e) => {
      console.log("Expired Callback: ", e);
      // Response expired. Ask user to solve reCAPTCHA again.
      // ...
    },
  });

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM