首先,我知道在这里已经发现了相同的问题: Error: No reCAPTCHA clients exist (reCAPTCHA v3)但是,既然那里的答案没有导致我找到解决方案,我在这里试试运气。
所以我尝试使用reCAPTCHA,因为我从网页上的表单中收到了很多垃圾邮件。在我的HTML头中,我有该代码:
<script src="https://www.google.com/recaptcha/api.js?render=MY_SITE_KEY"></script>
<script>
grecaptcha.ready(function() {
grecaptcha.execute("MY_SITE_KEY").then(function(token) {
console.log(token);
});
});
</script>
加载验证码并生成令牌。提交表单时,我将调用以下ajax代码:
$.ajax({
type: 'POST',
url: $(form).attr('action'),
data: {
name: name,
email: email,
message: message,
captcha: grecaptcha.getResponse()
}).done(function(response){ ... })
最后在PHP中,我执行以下操作:
<?php
$secret = "MY_SECRET_KEY";
$response = $_POST["captcha"];
$verify=file_get_contents("https://www.google.com/recaptcha/api/siteverify?secret={$secret}&response={$response}");
$captcha_success=json_decode($verify);
if ($captcha_success->success==false) {
echo "reCaptcha indentified you as a bot. We don't like bots here.";
}
else if ($captcha_success->success==true) {
// MY WHOLE mail() function here
}
?>
然后我提交表单时,出现错误:
Uncaught Error: No reCAPTCHA clients exist.
at Gw (recaptcha__de.js:511)
at Object.Q5 [as getResponse] (recaptcha__de.js:519)
at HTMLFormElement.<anonymous> (main.js:265)
at HTMLFormElement.dispatch (jquery.min.js:3)
at HTMLFormElement.q.handle (jquery.min.js:3)
我做错了什么?我遵循了Google的指示,但也许我错过了一些东西。
答案 0 :(得分:1)
您可以通过以下方法重新实现:
<script src="https://www.google.com/recaptcha/api.js?render=MY_SITE_KEY"></script>
<script>
var grecaptchaSiteKey = 'MY_SITE_KEY';
var _RECAPTCHA = _RECAPTCHA || {};
_RECAPTCHA.init = function() {
grecaptcha.ready(function() {
grecaptcha.execute(grecaptchaSiteKey, {action: 'homepage'}).then(function(token) {
if (jQuery(form)[0]) {
if (jQuery('.grecaptchaToken')[0]) {
jQuery(form).find('.grecaptchaToken').remove();
}
jQuery(form).append('<input type="hidden" class="grecaptchaToken" name="grecaptchaToken" value="' + token + '" />');
}
});
});
}
_RECAPTCHA.init();
</script>
之后,您可以获取隐藏输入的值,并将其放入Ajax有效负载中。
现在,为避免在第二次提交表单时出错,您可以调用_RECAPTCHA.init()方法;在Ajax调用的成功回调中。