Reputation: 1141
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!
Upvotes: 6
Views: 21685
Reputation: 1269
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);
});
});
}
Upvotes: 7
Reputation: 1141
I got reCaptcha V2 working:
// Get Google ReCaptcha Score
let captchaToken = grecaptcha.getResponse();
That got me the token. It does say to use it on their website, but it doesn't show it in an example, so I wasn't sure how it all clicked together.
"grecaptcha.getResponse(opt_widget_id) after the user completes the reCAPTCHA challenge"
You could also do:
let captchaToken = = req.body["g-recaptcha-response"];
For reCaptcha V3 I have still no idea how to get the token...
Upvotes: 0