Next js Firebase Auth 电话号码不可见 recaptcha

2023-12-28

Nextjs Firebase 电话身份验证

第一次尝试 useEffect()

useEffect(() => {
        window.recaptchaVerifier = new firebase.auth.RecaptchaVerifier('recaptcha', {
            'size': 'invisible',
            'callback': (response) => {
                console.log("This is not fired on loading", response)
            }
        })

    }, [])

return (
        <>
            <div id="recaptcha"></div>
            <button onClick={clicked}> Click me </button>
        </>
    )

这可以运行,但是验证码不起作用...用户被迫选择消防栓。

第二次尝试:React 组件

灵感:https://stackoverflow.com/a/63860925/7451631 https://stackoverflow.com/a/63860925/7451631将此导入到登录页面

class Recap extends Component {

  constructor(props) {
    super(props);
    this.signIn = this.signIn.bind(this);
  }

  componentDidMount() {
    window.reCaptchaVerifier = new firebase.auth.RecaptchaVerifier(this.recaptcha, {
      'size': 'invisible',
      'callback': function (response) {
        console.log("Magic", response)
      }
    })
  }

  signIn() {
    firebase.auth().signInWithPhoneNumber(phoneNumber, window.reCaptchaVerifier).catch((error) => {
      console.log(error)
    })
  }

  render() {
    return (
      <>
        <div ref={(ref) => this.recaptcha = ref} onClick={this.signIn}> Clik meeeee </div>
      </>
    )
  }
}

作品!在输入这个问题时,我得到了一个丑陋的解决方案。如果有人知道如何让它变得更好或者可以解释为什么第一次尝试没有成功,那就太棒了。


这是我的解决方案:

    import { createFirebaseApp } from '@utils/firebase';
    import { getAuth, PhoneAuthProvider, RecaptchaVerifier, signInWithCredential } from 'firebase/auth';
    import { useState } from 'react';
    
    export default function Example() {
      const app = createFirebaseApp();
      const auth = getAuth(app);
    
      const [code, setCode] = useState('');
      const [verificationId, setVerificationId] = useState('');
    
      const signInWithPhone1 = async () => {
        const applicationVerifier = new RecaptchaVerifier(
          'sign-in-button',
          {
            size: 'invisible',
          },
          auth,
        );
    
        const provider = new PhoneAuthProvider(auth);
        const vId = await provider.verifyPhoneNumber('+855012000001', applicationVerifier);
    
        setVerificationId(vId);
      };
    
      const verify = async () => {
        const authCredential = PhoneAuthProvider.credential(verificationId, code);
        const userCredential = await signInWithCredential(auth, authCredential);
        console.log('verify: ', userCredential);
      };
    
      return (
        <>
          <button id="sign-in-button" onClick={signInWithPhone1}>
            SignIn With Phone1
          </button>
    
          <div>
            <input type="text" value={code} onChange={(v) => setCode(v.target.value)} />
            <button onClick={verify}>Verify</button>
          </div>
        </>
      );
    }
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

Next js Firebase Auth 电话号码不可见 recaptcha 的相关文章

随机推荐