React Google Recaptcha ' executeRecaptcha '函数总是返回' null '.&l



我使用^1.10.0版本的react-google-recaptcha-v3,但是当我想从executeRecaptcha函数获得令牌时,该函数总是返回null而不是返回令牌。有人知道吗?

附加代码:

import React, {  useState } from 'react';
import {
GoogleReCaptchaProvider,
useGoogleReCaptcha,
} from 'react-google-recaptcha-v3';
...
const AuthSigninPage = () => {
const service = new AuthService();
const isRecaptchaAvailable = true;
const setPhone = useAuthStore((state) => state.setPhone);
const { executeRecaptcha } = useGoogleReCaptcha();
const { getPhoneState } = usePhoneState();
const { push } = useRouter();
const [isButtonDisabled, setIsButtonDisabled] = useState<boolean>(true);

const authenticate = async () => {
try {
const isEligibleToLogin = await checkRecaptcha();
if (!isEligibleToLogin) return;
setPhone(phone);
const { isHasPassword, isRegistered } = await getPhoneState(phone);
if (!isRegistered) {
return;
}
push(isHasPassword ? '/auth/password' : '/auth/verify');
} catch (error: any) {
...
}
};
const checkRecaptcha = async () => {
try {
let isRecaptchaValid: boolean = true;
if (!executeRecaptcha) {
console.log('Execute recaptcha not yet available');
return;
}
if (isRecaptchaAvailable) {
const token = await executeRecaptcha!('login');
console.log(token); // always return null
if (!token) {
bottomSheet.warning({
message: 'Recaptcha token is not available',
});
return false;
}
isRecaptchaValid = await service.validateRecaptcha(token);
}
if (!isRecaptchaValid) {
bottomSheet.error({
message: 'Recaptcha is not valid',
});
}
return isRecaptchaValid;
} catch (error: any) {
JSON.stringify(error);
}
};
return (
<MainLayout
backable
title="Masuk"
>
Pretend that there is another element here like button to login
</MainLayout>
)
};
const SigninPageWrappedWithCaptcha = () => {
return (
<GoogleReCaptchaProvider
reCaptchaKey={process.env.NEXT_PUBLIC_GR_KEY as string}
>
<AuthSigninPage />
</GoogleReCaptchaProvider>
);
};
export default SigninPageWrappedWithCaptcha;

你的executeRecaptcha函数有一个小错别字:

更改此const token = await executeRecaptcha!('login');

到此const token = await executeRecaptcha('login');

但是,我不认为这是它不起作用的原因。您的代码看起来很好。一些可能的检查

  1. 检查。env
  2. 中的NEXT_PUBLIC_GR_KEY变量是否正确
  3. 检查您的帐户和您的。env中的令牌是否相同
  4. 请确保您运行代码的域与您在google帐户中设置recaptcha的域相同
  5. 重新启动服务器并重试

最新更新