How do I use Google's reCAPTCHA to block a particular part of a page?

1

For example,

I have a website in Wordpress, that the content is shown only after I validate Google's reCAPTCHA, I have already looked for several codes but nothing helped me, can anyone give me a tip?

<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <title>Conteudo a ser Bloqueado</title>
  </head>
  <body>
    <h1>Exemplo</h1>
    <p>Conteúdo 01 (quero que isso seja mostrado na pagina somente depois que passar pelo reCAPTCHA do Google)</p>
  </body>
</html>
    
asked by anonymous 25.02.2018 / 22:48

2 answers

0

Include the part you want to block within a if with a variable that will be the Google response reCaptcha:

<?php
if($resposta){
?>
<p>Conteúdo 01 (quero que isso seja mostrado na pagina somente depois que passar pelo reCAPTCHA do Google)</p>
<?php
}
?>

The variable $resposta will be the return of the reCaptcha check (will be true if reCaptcha has been validated or false if not) which will be given by the following code:

<?php
$resposta = false;
if (isset($_POST['g-recaptcha-response']) && !empty($_POST['g-recaptcha-response'])) {
   $captcha_data = $_POST['g-recaptcha-response'];
   $chave_secreta = "CHAVE_SECRETA";   
   $resposta = file_get_contents("https://www.google.com/recaptcha/api/siteverify?secret=$chave_secreta&response=$captcha_data&remoteip=".$_SERVER['REMOTE_ADDR']);
}
?>

Above is part of the server. You must also insert the client part into a form on the page. Click on <head> API:

<script src='https://www.google.com/recaptcha/api.js'></script>

The form and script for client-side validation:

<form method="post" onsubmit="return validar()">
   <div class="g-recaptcha" data-callback="recaptchaCallback" data-sitekey="CHAVE_DO_SITE"></div>
   <br>
   <button type="submit">Validar</button>
</form>

<script>
googlerecpchk = false;
function recaptchaCallback() {
   googlerecpchk = true;
};

function validar(){

   if(!googlerecpchk){
      alert("reCaptcha inválido!");
      return false;
   }

}
</script>

Putting it all together, it would look like this:

<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <title>Conteudo a ser Bloqueado</title>
    <script src='https://www.google.com/recaptcha/api.js'></script>
  </head>
  <body>
    <h1>Exemplo</h1>
   <?php
   $resposta = false;
   if (isset($_POST['g-recaptcha-response']) && !empty($_POST['g-recaptcha-response'])) {
      $captcha_data = $_POST['g-recaptcha-response'];
      $chave_secreta = "CHAVE_SECRETA";   
      $resposta = file_get_contents("https://www.google.com/recaptcha/api/siteverify?secret=$chave_secreta&response=$captcha_data&remoteip=".$_SERVER['REMOTE_ADDR']);
   }
   if ($resposta) {
   ?>
    <p>Conteúdo 01 (quero que isso seja mostrado na pagina somente depois que passar pelo reCAPTCHA do Google)</p>
    <?php
   }
   ?>

   <?php
   if(!$resposta){
   ?>
   <form method="post" onsubmit="return validar()">
      <div class="g-recaptcha" data-callback="recaptchaCallback" data-sitekey="CHAVE_DO_SITE"></div>
      <br>
      <button type="submit">Validar</button>
   </form>
   <script>
   googlerecpchk = false;
   function recaptchaCallback() {
      googlerecpchk = true;
   };

   function validar(){

      console.log(googlerecpchk);
      if(!googlerecpchk){
         alert("reCaptcha inválido!");
         return false;
      }

   }
   </script>
    <?php
   }
   ?>

  </body>
</html>
    
26.02.2018 / 00:09
1

You must use a request to send response to your back-end , validate it, and return an HTML with the value to be displayed. p>

The first step is to create a AJAX function. Let's use the wp ajax

In your functions.php

<?php

/* Sua chave secreta do Google reCaptcha */
define('RECAPTCHA_SECRET', 'Your-Secret');

/*
 * Adiciona ações para captura via AJAX
 * Para acessa-las basta enviar uma requisição
 * para https://www.YOUR-SITE.com/wp-admin/admin-ajax.php?aciton=nome-da-acao
 */
add_action('wp_ajax_carrega_post', 'carrega_post');
add_action('wp_ajax_nopriv_carrega_post', 'carrega_post');

/*
 * Função responsável por verificar o response do capcha
 * E liberar o conteúdo do POST
 */
function carrega_post() {

    /* Cria um contexto do tipo HTTP POST com o valor do response */
    $context = stream_context_create([
        'http' => [
            'method'  => 'POST',
            'content' => http_build_query([
                'secret'   => RECAPTCHA_SECRET,
                'response' => filter_input(INPUT_POST, 'response', FILTER_SANITIZE_STRING),
            ])
        ]
    ]);

    /* Faz uma requisição do tipo POST para o servidor da Google */
    $result = json_decode(file_get_contents("https://www.google.com/recaptcha/api/siteverify", FILE_BINARY, $context));

    /* Verifica se o valor do captcha é válido */
    if ( $result->success ) {

        /* 
         * Aqui você pode fazer sua regra de 
         * negócio para capturar o que 
         * você deseja
         */

        $post = (new WP_Query( intval($_POST['postID']) ))->posts[0];

        echo "Conteúdo do post \"{$post->post_title}\" liberado";

        wp_die();
    }
}

In your single.php or similar file (it will depend on your structure), just put captcha and add a connection form. I will post with Fetch and XMLHttpRequest , it will be at your discretion.

<?php
/**
 * Template test
 *
 * @author Valdeir Psr < http://www.valdeirpsr.com.br >
 * @version 1.0
 */

get_header(); ?>

<div id="g-recaptcha"></div>

<script src="https://www.google.com/recaptcha/api.js?onload=onloadCallback"></script><script>functiononloadCallback(){/*CriaocaptchanaDIVindicada*/grecaptcha.render('g-recaptcha',{'sitekey':'Your-Code','callback':'verificaCaptcha'});}/*FunçãoresponsávelporreceberoresponseCodeefazerarequisição*/functionverificaCaptcha(response){alert("Aguarde...");

    /* Cria um formulário */
    let form = new FormData();
    form.append("response", response);
    form.append("postID", "<?php the_ID(); ?>");

    /* Cria uma requisição no formato POST com os dados acima */
    let request = new Request("<?php echo home_url() ?>/wp-admin/admin-ajax.php?action=carrega_post", {
        method: "POST",
        body: form,
        cache: "no-cache"
    });

    /* Envia a conexão e retorna os dados */
    fetch(request)
        .then( response => {
            return response.text()
        } )
        .then( text => alert(text) );
}
</script>

<?php get_footer();

Example with XMLHttpRequest :

/* Função responsável por receber o responseCode e fazer a requisição */
function verificaCaptcha(response) {

    alert("Aguarde...");

    /* Cria um formulário */
    let form = new FormData();
    form.append("response", response);
    form.append("postID", "<?php the_ID(); ?>");

    let xhr = new XMLHttpRequest();
    xhr.addEventListener("load", result => {
        alert( result.target.response )
    })
    xhr.open("POST", "<?php echo home_url() ?>/wp-admin/admin-ajax.php?action=carrega_post", true);
    xhr.send(form);
}
    
26.02.2018 / 00:11