Using reCAPTCHA with jQuery (ajax) and PHP

1

Hello, guys!

I've been programming for 4 days using jQuery :)
I made a form using ajax and PHP, it worked perfectly! But ...
there was a need to implement reCAPTCHA. I do not know where to start, I need help.

formular.html

<div id="alerta" class="alert alert-dismissible" role="alert" style="display: none;">
  <button type="button" class="close" data-dismiss="alert" aria-label="Close"><span aria-hidden="true">&times;</span></button>
  <div><strong>Atenção!</strong> Existem campos obrigatórios.</div>
</div>

<form id="form" class="form-inline contact_box">
   <input type="text" class="form-control input_box" name="Nome">
   <input type="text" class="form-control input_box" name="Telefone">
   <input type="text" class="form-control input_box" name="Email">
   <input type="text" class="form-control input_box" name="Assunto">
   <textarea class="form-control input_box" name="Mensagem"></textarea>
   <div class="g-recaptcha" data-sitekey="6Ldf5kAUAAAAAFMK5xRr6aE06eiyx0nTRPqAYLHM"></div>
   <br>
   <button id="btnForm" type="submit" class="btn btn-default">Enviar</button>
</form>

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script><script>$("#form").on("submit",function(){
      event.preventDefault();

      var dados = $(this).serialize();
      $.ajax({
        method: "POST",
        url: "https://meusite.com.br/enviaemail/",
        data: dados,
        beforeSend: function(){
         $('#btnForm').html('<i class="fa fa-spinner fa-pulse fa-fw"></i> Enviando...').attr("disabled", "disabled");
      },
      success: function(e){
        var retorno = JSON.parse(e);
        var tipo = retorno.tipo;
        var frase = retorno.frase;

        $('#alerta').addClass(tipo).find('div').html(frase);
        $('#alerta').show(500);

        $('#btnForm').html('<i class="fa fa-check" aria-hidden="true"></i> Enviado!').attr("disabled", false);
      }
    });
  });
</script>

enviaemail.php

<?php
  $nomeForm = $_POST['Nome'];
  $telsForm = $_POST['Telefone'];
  $emaiForm = $_POST['Email'];
  $assuForm = $_POST['Assunto'];
  $mensForm = $_POST['Mensagem'];

  if ($nomeForm != "" && $emaiForm != "" && $assuForm != "" && $mensForm != "") {
    if (filter_var($emaiForm, FILTER_VALIDATE_EMAIL)) {
      //função para enviar email...
      $Resp = array('tipo' => 'alert-success', 'frase' => 'Sua mensagem foi enviada com sucesso. Logo entraremos em contato.');
    } else {
      $Resp = array('tipo' => 'alert-warning', 'frase' => '<strong>Atenção!</strong> Por favor, insira um email válido.');
    }
  } else {
    $Resp = array('tipo' => 'alert-warning', 'frase' => '<strong>Atenção!</strong> Todos os campos são obrigatórios. Por favor, tente novamente.');
  }

  echo json_encode($Resp);
?>

The question is: how to do this send the reCaptcha confirmation to PHP?

    
asked by anonymous 16.01.2018 / 13:55

1 answer

3

To catch the value of reCaptcha , use the getResponse method. It will give you a code that should be used for validation.

No JavaScript:

var dados = $(this).serialize();
post += "&recaptcha=" + grecaptcha.getResponse()
$.ajax({
    method: "POST",
    url: "https://meusite.com.br/enviaemail/",
    data: dados
});

In PHP (using file_get_contents):

<?php

$content = [
    "secret" => "YOUR-SECRET",
    "response" => $_POST["recaptcha"] ?? "",
    "remoteip" => $_SERVER["REMOTE_ADDR"] ?? null,
];

$opts = [
    "http" => [
        "method" => "POST",
        "content" => http_build_query($content),
        "header" => "Content-Type: application/x-www-form-urlencoded",
    ]
];

$context = stream_context_create($opts);

$validation = file_get_contents("https://www.google.com/recaptcha/api/siteverify", FILE_BINARY, $context);

$response = json_decode($validation);

if ($response->success) {
    echo "Captcha válido";
} else {
    echo "Captcha inválido";
}

In PHP (Using curl):

<?php

$content = [
    "secret" => "YOUR-SECRET",
    "response" => $_POST["recaptcha"] ?? "",
    "remoteip" => $_SERVER["REMOTE_ADDR"] ?? null,
];

$curl = curl_init("https://www.google.com/recaptcha/api/siteverify");
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_POST, true);
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($curl, CURLOPT_POSTFIELDS, $content);
$validation = curl_exec($curl);
curl_close($curl);

$response = json_decode($validation);

if ($response->success) {
    echo "Captcha válido";
} else {
    echo "Captcha inválido";
}
    
16.01.2018 / 14:14