Vin*_*rma 5 javascript firebase reactjs firebase-authentication invisible-recaptcha
嗨,我在React JS应用程序中使用Firebase 的隐形 reCaptcha进行电话号码身份验证。根据Firebase的文档,您需要提供处理登录表单提交的按钮的id(例如)。sign-in-button
一旦用户点击该按钮,Firebase 的隐形 reCaptcha 就会启动并检查它是否已被用户解决。如果 reCaptcha 已解决,则将触发callback 提供者new firebase.auth.RecaptchaVerifier('...', {})。在那个回调中,我们应该向用户的电话号码发送一个 OTP代码。
发生的事情是callback除非在提交登录表单时未发送 OTP,否则不会被触发,这是没有意义的,因为发送 OTP 需要由隐形 reCaptcha 提供的回调处理,而不是通过使用 onSubmit 发送 OTP的形式。
"firebase": "^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>
);
}
}
Run Code Online (Sandbox Code Playgroud)
这是我正在使用的,看起来效果很好
const [token, setToken] = useState("");
useEffect(() => {
new firebase.auth.RecaptchaVerifier("request-otp", { size: "invisible" })
.verify()
.then(setToken);
}, []);
Run Code Online (Sandbox Code Playgroud)
通常,reCAPTCHA在使用之前需要渲染。因此,例如,以下代码可以工作。问题中代码的唯一修改是:
componentDidMountonSumbit因此不使用表单(在这种情况下它实际上永远不会触发,因为 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>
);
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1757 次 |
| 最近记录: |