How to use Google reCAPTCHA to block a certain part of a page?

For example,

I have a site in Wordpress, that the content is shown only after validating Google reCAPTCHA, I have looked for several codes but nothing helped me, Can someone 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>
Author: Matheus Vitor, 2018-02-25

2 answers

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

<?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 (it will be true if the 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 in a form on the page. Click on the <head> API:

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

The form e script for validation client-side :

<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 everything together 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>
 0
Author: Sam, 2018-02-27 02:15:09

You need to use a request to send the response up to your backend, validate it and return a HTML with the value to be displayed.

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

In your file 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 file .php or similar (will depend on your structure), just put the captcha and add a connection form. I will post with Fetch and XMLHttpRequest, go stays 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>
function onloadCallback() {

    /* Cria o captcha na DIV indicada */
    grecaptcha.render('g-recaptcha', {
        'sitekey' : 'Your-Code',
        'callback' : 'verificaCaptcha'
    });
}

/* 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(); ?>");

    /* 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);
}
 1
Author: Valdeir Psr, 2018-02-25 23:11:05