下載recaptcha
https://github.com/google/recaptcha
載完之後放好就可以了,只要記得呼叫相對路徑就好
先引入https://www.google.com/recaptcha/api.js
function LoginForm(){
wp_register_script('pm-google_script','https://www.google.com/recaptcha/api.js');
wp_enqueue_script('pm-google_script');
}
前端html加入
<div class="g-recaptcha" data-callback="captcha_onclick" data-sitekey="your sitekey" style="margin-top:50px;"></div>
<input type="hidden" name="recaptcha" id="recaptchaValidator" />
js部分
function captcha_onclick() {
document.getElementById('recaptchaValidator').value = grecaptcha.getResponse();
}
後端驗證時加入
require(PM_DIR.'/recaptcha/src/autoload.php');
//記得改成最前面那包recaptcha的相對路徑
// _GOOGLE_RECAPTCHA_SEC_KEY 就是 google 給的 Secret Key
$recaptcha = new \ReCaptcha\ReCaptcha('6LeXo70UAAAAAORn5xn-s9QFPvBwAj2xOQKXhY63');
$gRecaptchaResponse = $_POST['recaptcha'];
$remoteIp = $_SERVER['REMOTE_ADDR'];
$resp = $recaptcha->verify($gRecaptchaResponse, $remoteIp);
if(!$resp->isSuccess()){
echo json_encode(array('error'=>'請先證明您不是機器人'));
exit();
}else{
//驗證成功時做的事情
}
記得回傳失敗的時候需要做以下處理,否則登入失敗時驗證區塊會卡死
grecaptcha.reset();