我想在 Recaptcha 的新版本 (V3) 中插入联系方式。
我寻找了不同的解决方案,但它们只显示了部分代码,它们不完整或者我得到了错误,而且找到的大多数解决方案对于如此简单的事情来说都非常复杂,而且我不理解代码。
最佳答案
我搜索了这个论坛和其他论坛,以在我的表单中实现新版本的 ReCaptcha (V3)。 我需要知道如何:
- 用JS插入
- 如何用 PHP 验证它
- 我的表单中需要哪些新字段。
我没有找到任何简单的解决方案来显示所有这些要点,或者对于只想在他们的网站上插入联系表格的人来说太复杂了。
最后,我取了多个解决方案的一些代码部分,使用了一个简单且可重用的代码,您只需在其中插入相应的键即可。
在这里。
基本的JS代码
<script src="https://www.google.com/recaptcha/api.js?render=your reCAPTCHA site key here"></script>
<script>
grecaptcha.ready(function() {
// do request for recaptcha token
// response is promise with passed token
grecaptcha.execute('your reCAPTCHA site key here', {action:'validate_captcha'})
.then(function(token) {
// add token value to form
document.getElementById('g-recaptcha-response').value = token;
});
});
</script>
基本的HTML代码
<form id="form_id" method="post" action="your_action.php">
<input type="hidden" id="g-recaptcha-response" name="g-recaptcha-response">
<input type="hidden" name="action" value="validate_captcha">
.... your fields
</form>
基本的PHP代码
if(isset($_POST['g-recaptcha-response'])){
$captcha=$_POST['g-recaptcha-response'];
}
else
$captcha = false;
if(!$captcha){
//Do something with error
}
else{
$secret = 'Your secret key here';
$response = json_decode(file_get_contents("https://www.google.com/recaptcha/api/siteverify?secret=".$secret."&response=".$captcha."&remoteip=".$_SERVER['REMOTE_ADDR']));
if($response->{'success'}==false)
{
//Do something with error
}
}
//... The Captcha is valid you can continue with the rest of your code
//... Add code to filter access using $response . score
if ($response->{'success'}==true && $response->{'score'} <= 0.5) {
//Do something to denied access
}
您必须使用 $response->{'score'} 的值过滤访问。它可以取 0.0 到 1.0 之间的值,其中 1.0 表示用户与您网站的最佳交互,0.0 表示最差的交互(如机器人)。您可以在 ReCaptcha documentation 中看到一些使用示例.
您只需添加您的 key ,无需更多更改:
src="https://www.google.com/recaptcha/api.js?render=your reCAPTCHA site key here"
grecaptcha.execute('your reCAPTCHA site key here'
和
$secret = 'Your secret key here';
显然你还必须改变表单的 Action ,在这个例子中:
action = "your_action.php"
关于php - 如何以 PHP 形式实现 Google Recaptcha v3?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54183985/