CLIENT-SIDE
Carregue o JavaScript na página:
1 |
<script src="https://www.google.com/recaptcha/api.js?render=reCAPTCHA_site_key"></script> |
Em sua função do ajax:
1 2 3 4 5 6 7 8 9 10 |
grecaptcha.ready(function() { grecaptcha.execute('reCAPTCHA_site_key', {action: 'submit'}).then(function(token) { //você precisa enviar o token na requisição do ajax //var formData = new FormData($(form)[0]); //formData.append('google_recaptcha_token', token); //$(form).serialize()+'&google_recaptcha_token='+token; //faça sua requisição ajax aqui }); }); |
Para esconder o ícone do google recaptcha utilize o css:
1 2 3 |
.grecaptcha-badge { visibility: hidden; } |
SERVER-SIDE
Crie uma função para utilizar em todos os formulários do seu site:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
function google_captcha_check($token){ global $config; $google_captcha_response = get_request('https://www.google.com/recaptcha/api/siteverify','POST',[ 'secret' => 'reCAPTCHA_site_secret_key', 'response' => $token, 'remoteip' => $_SERVER['REMOTE_ADDR'] ]); $google_captcha_response = json_decode($google_captcha_response); if($google_captcha_response->success !== true){ return false; } return true; } |
Chame a função na sua página ajax:
1 2 3 4 |
if(!google_captcha_check($_POST['google_recaptcha_token'])){ echo 'Captcha não solucionado, tente novamente'; exit; } |
Observação
A função get_request não existe no PHP, você pode usar a função abaixo, ou utilizar cURL
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 |
function get_request($url,$method = 'GET',$params = [], $token = ''){ $dir = tempnam('tmp', 'CURLCOOKIE'); $method = strtoupper($method); $agent = 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/66.0.3359.181 Safari/537.36'; if($method == 'GET' && count($params) > 0){ $newURL = explode('?',$url); if(isset($newURL[1])){ $newURL[1] .= '&'; } $newURL[1] .= http_build_query($params); $url = implode('?',$newURL); } $opt_params = array( CURLOPT_URL => $url, CURLOPT_SSL_VERIFYPEER => false, CURLOPT_USERAGENT => $agent, CURLOPT_RETURNTRANSFER => true, CURLOPT_ENCODING => "", CURLOPT_MAXREDIRS => 10, CURLOPT_TIMEOUT => 0, CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1, CURLOPT_CUSTOMREQUEST => $method, CURLOPT_HTTPHEADER => array( "cache-control: no-cache", "content-type: application/x-www-form-urlencoded" ), CURLOPT_COOKIEJAR => $dir, CURLOPT_COOKIEFILE => $dir, CURLOPT_POSTFIELDS => http_build_query($params), ); $curl = curl_init(); if(!empty($token)){ array_push($opt_params[CURLOPT_HTTPHEADER], "authorization: Bearer ".$token); } curl_setopt_array($curl, $opt_params); $html = curl_exec($curl); curl_close($curl); return $html; } |
Como criar uma key do google recaptcha?
Acesse https://www.google.com/recaptcha/admin/ e siga as instruções.