我们有一个 PHP 表单,它在 reCaptcha 上有几个选项卡和超时。一切都在一页中完成,如果表格在 <3 分钟内完成,它就可以正常工作。
一个解决方案的想法是将表单处理和 reCaptcha 移动到辅助页面进行处理。
问题是表单页面轮询谷歌服务以获取 reCaptcha 并将 token 值收集到隐藏字段。
<input type="hidden" name="recaptcha_response" id="recaptchaResponse">
问题是如何在服务端处理页面请求这个token?这是客户端表单页面上使用的代码。我需要以某种方式重新生成要应用的 token 值:
$recaptcha_response
这是表单页面上的工作版本。从表单页面删除对发布 token 的要求很容易,只是不确定如何重新生成 token 以在服务器端页面上使用。
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['recaptcha_response'])) {
// Build POST request:
$recaptcha_url = 'https://www.google.com/recaptcha/api/siteverify';
$recaptcha_secret = RECAPTCHA_SECRET_KEY;
$recaptcha_response = $_POST['recaptcha_response'];
$remoteip = $_SERVER['REMOTE_ADDR'];
// Make and decode POST request:
$recaptcha = file_get_contents($recaptcha_url . '?secret=' . $recaptcha_secret . '&response=' . $recaptcha_response. '&remoteip='.$remoteip);
$recaptcha = json_decode($recaptcha);
// Take action based on the score returned:
if ($recaptcha->score >= 0.5) {
编辑添加:
会使 reCaptcha 的初始化直到 Submit 延迟时间问题,因为这似乎是一个选项:
https://developers.google.com/recaptcha/docs/v3
“2. 在操作或页面加载时调用 grecaptcha.execute”
最佳答案
我们最近也遇到了这个问题。我在 GitHub 上找到了这个解决方案它对我们来说运作良好。
这样做的好处是仅在用户与页面交互(例如提交表单)时才要求 token ,而不必一直要求 token 。
<script>
grecaptcha.ready(function() {
document.getElementById('contactform').addEventListener("submit", function(event) {
event.preventDefault();
grecaptcha.execute('mykey', {action: 'homepage'}).then(function(token) {
document.getElementById("googletoken").value = token;
document.getElementById('contactform').submit();
});
}, false);
});
</script>
关于php - 如何解决 Google v3 reCaptcha 超时?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55251837/