首页 > 解决方案 > Firebase:不可见的 reCaptcha 在 React JS 中不起作用

问题描述

概述

嗨,我在我的React JS应用程序中使用Firebase 的隐形 reCaptcha进行电话号码身份验证。根据 Firebase 的文档,您需要提供处理登录表单提交的按钮的ID(例如)。sign-in-button

预期行为

一旦用户单击该按钮,Firebase 的不可见 reCaptcha 应该会启动并检查它是否已被用户解决。如果 reCaptcha 已解决,将触发callback 提供的 by 。new firebase.auth.RecaptchaVerifier('...', {})在该回调中,我们应该向用户的电话号码发送 OTP代码。

问题

发生的情况是,除非在提交登录表单时未发送 OTP,callback否则不会触发,这是没有意义的,因为发送 OTP 需要由不可见的 reCaptcha 提供的回调处理,而不是通过使用 onSubmit 发送 OTP的形式。

版本

“火力基地”:“^7.15.1”,

代码

import React, { Component } from 'react';

import firebase from 'firebase/app';
import 'firebase/auth';

firebase.initializeApp({
  apiKey: 'xxx',
  authDomain: 'xxx',
  databaseURL: 'xxx',
  projectId: 'xxx',
  storageBucket: 'xxx',
  messagingSenderId: 'xxx',
  appId: 'xxx',
  measurementId: 'xxx',
});

class App extends Component {
  componentDidMount() {
    window.reCaptchaVerifier = new firebase.auth.RecaptchaVerifier('login-button', {
      size: 'invisible',
      callback: () => {
        // callback is not being fired automatically
        // but after the OTP has been sent to user's
        // phone number which makes this callback useless
        // as opposed to Firebase's documentation
      },
    });
  }

  handleSubmit = event => {
    event.preventDefault();

    firebase
      .auth()
      .signInWithPhoneNumber('+1 XXX-XXX-XXXX', window.reCaptchaVerifier)
      .then(confirmationResult => {
        window.confirmationResult = confirmationResult;
      })
      .catch(() => {});
  };

  render() {
    return (
      <form onSubmit={this.handleSubmit}>
        <input />
        <button id="login-button">Submit</button>
      </form>
    );
  }
}

标签: javascriptreactjsfirebasefirebase-authenticationinvisible-recaptcha

解决方案


通常,reCAPTCHA 需要在使用进行渲染。因此,例如,以下代码有效。问题中代码的唯一修改是:

  • reCAPTCHA 显式呈现在componentDidMount
  • onSumbit因此不使用表单(在这种情况下它实际上从不触发,因为 reCAPTCHA 回调处理的是提交事件)

预渲染的工作解决方案:

class App extends Component {
  componentDidMount() {
    const reCaptchaVerifier = new firebase.auth.RecaptchaVerifier('sign-in-button', {
      size: 'invisible',
      callback: function (response) {
        console.log('It works!');
      },
    });
    reCaptchaVerifier.render();
  }

  render() {
    return (
      <form>
        <input />
        <button id="sign-in-button">Submit</button>
      </form>
    );
  }

}

推荐阅读