google recaptcha驗證串接教學

下載recaptcha
https://github.com/google/recaptcha
載完之後放好就可以了,只要記得呼叫相對路徑就好

先引入https://www.google.com/recaptcha/api.js

[php]function LoginForm(){
		wp_register_script('pm-google_script','https://www.google.com/recaptcha/api.js');
		wp_enqueue_script('pm-google_script');
	}[/php]

前端html加入

[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" />[/html]

js部分

[php]function captcha_onclick() {
	document.getElementById('recaptchaValidator').value = grecaptcha.getResponse();
}[/php]

後端驗證時加入

[php]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{
                  //驗證成功時做的事情
                }[/php]

記得回傳失敗的時候需要做以下處理,否則登入失敗時驗證區塊會卡死

grecaptcha.reset();
展躍網頁設計從事 WordPress架設網站 已經多年,並且服務過各大知名品牌與上市櫃企業,如果你想了解到更多相關的網頁設計知識與趨勢,歡迎隨時關注我們「展躍有限公司」,如果你有想要我們協助你 架設網站 或是提供你更完整的設計服務也歡迎致電或來信詢問!
客服專線:03-2728415 / 客服信箱:[email protected] / LINE ID:@obn8515v