谷歌(Google) reCaptchaV3做网站人机验证
需要特别注意的是,必须使用公网ip,本地ip无法进行验证!!!
1.reCaptcha官网网站为:https://developers.google.com/recaptcha/(需要FQ)
2.在国内使用的话,需要将demo中所有的www.google.com替换成www.recaptcha.net不然无法使用reCAPTCHA
3.使用reCaptcha需要去注册google账号,并且去https://www.google.com/recaptcha/admin#list里面去创建秘钥对()稍等我会标注出来)
前端页面代码
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="utf-8">
<title>网页标题</title>
<script src="https://code.jquery.com/jquery-3.1.1.min.js"></script>
<script src=\'https://www.recaptcha.net/recaptcha/api.js?render=网站秘钥第一个sitekey\'></script>
</head>
<body>
人机验证得分为:<span id="span"></span>
</body>
<script>
grecaptcha.ready(function() {
grecaptcha.execute(\'网站秘钥第一个sitekey\').then(function(token) {
console.log(token);
$.ajax({
url: \'https://自己的公网地址/yanzheng.php\',
type: \'POST\',
data: {"token":token},
success: function(result) {
var data=JSON.parse(result);
if(data.score>0.5){
console.log(\'你是人\');
window.location.href="www.baidu.com" ;
}else{
console.log(\'你是机器人\');
}
document.getElementById(\'span\').innerText=data.score;
console.log(data.score);
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
errorMsg = "获取身份错误<br/>错误信息:" + textStatus + "错误码:" + XMLHttpRequest.status + \'<br/>请刷新重试\';
console.log(errorMsg, \'网络错误\');
}
});
});
});
</script>
</html>
后端代码为PHP
<?php
$token=$_POST[\'token\'];
$secret=\'通信秘钥 第二个\';
$value = http_post("https://www.recaptcha.net/recaptcha/api/siteverify",\'secret=\'.$secret.\'&response=\'.$token);//参数建议用与符号拼接
echo $value;
function http_post($url,$postbody){
$curl = curl_init();
curl_setopt($curl,CURLOPT_URL,$url);
// CURLOPT_RETURNTRANSFER 设置是否有返回值
curl_setopt($curl,CURLOPT_RETURNTRANSFER,true);
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);//这个是重点,如果是https请求一定要加这句话。
curl_setopt($curl,CURLOPT_POST,true);
curl_setopt($curl,CURLOPT_POSTFIELDS,$postbody);
//执行完以后的返回值
$response = curl_exec($curl);
//释放curl
curl_close($curl);
return $response;
}
?>
参考博客:https://blog.csdn.net/dulinanaaa/article/details/88126607