Google reCAPTCHA 是 Google 提供的一种验证码服务,用来区分访问者是 真人用户 还是 自动化脚本(机器人)。它的目标就是保护网站免受垃圾注册、恶意爬虫、暴力破解和垃圾评论的攻击。它的核心原理是:通过交互、行为分析和风险建模,判断访问者的真实性。很多wp的表单插件已经集成了recaptcha的配置,本文主要介绍怎样手动添加google recaptacha。
第一步,打开https://cloud.google.com/security/products/recaptcha ,点击”开始使用”,然后在页面中选择reCAPTCHA 类型以及域名.

第二步,提交成功会有2个密钥:

第三步,集成到代码
html:
<button data-sitekey="xxxxxxxx" data-callback='onSubmit'
data-action='submit'
class="g-recaptcha">Submit</button>
php校验:
if (!isset($_POST['g-recaptcha-response'])) {
wp_die('Invalid request');
}
$recaptcha_response = $_POST['g-recaptcha-response'];
$recaptcha_url = 'https://www.google.com/recaptcha/api/siteverify';
$recaptcha_secret = 'xxxxx;
// 构建POST请求数据
$recaptcha_data = wp_remote_post($recaptcha_url, array(
'body' => array(
'secret' => $recaptcha_secret,
'response' => $recaptcha_response
)
));
$data = json_decode(wp_remote_retrieve_body($recaptcha_data));
if ($data->success === false) {
wp_die('reCAPTCHA verification failed.');
}