How do I get this token google reCAPTCHA needs to send a request to https://www.google.com/recaptcha/api/siteverify ?
The documentation is not very clear:
Everything I read is using various React npm programs. I don't want to use them, shouldn't really have to for such a simple thing.
Maybe someone could point me in the right direction?
const MyPage = () => {
const [reCaptchaVerified, setReCaptchaVerified] = useState(false);
const handleSubmit = (event) => {
let captchaToken = ''; // How to get the reCaptcha Token?
let captchaResult = GoogleReCaptcha(captchaToken); // My Backend. Sends the token and secret key to google's API.
if(captchaResult === true){
setReCaptchaVerified(true);
}
else {
setReCaptchaVerified(false);
}
}
return (
<form id="my-form" onSubmit="handleSubmit()">
<button type="submit" disabled={!reCaptchaVerified} data-sitekey={ RECAPTCHA_SITE_KEY } data-callback='onSubmit' data-action='my-form-submit'>Submit</button>
</form>
<footer>
{/* Google ReCaptcha Script */}
<Script src="https://www.google.com/recaptcha/api.js"></Script>
<Script>
{`function onSubmit(token) {
document.getElementById("my-form").submit();
} `}
</Script>
</footer>
)
}
I must be missing something in either the google scripts or a tag on the submit button? Or is the token included in the form's event? event.token?
I read about grecaptcha.getResponse() being used ??? But I see no examples.
Any help much appreciated!
For reCaptcha 3 this is working for me.
in the head of my page.
<script async src="https://www.google.com/recaptcha/api.js?render=SITE_KEY"></script>
Lower in my document.
<button onclick='someAction()'>Some Action</button>
and finally. The function that gets the token.
function someAction() {
grecaptcha.ready(function() {
grecaptcha.execute('SITE_KEY', {action: 'submit'}).then(function(token) {
console.log(token);
});
});
}