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

Asked

Viewed 993 times

1

For example,

I have a site in Wordpress, that the content is shown only after validating the reCAPTCHA Google, I’ve searched several codes but nothing helped me, someone can 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>

  • A demonstration in the download part: https://sanet.cd/blogs/hakunamatata/va_flaix_fm_aniversario.2515094.html

2 answers

1

You need to use a request to send the response up to his back-end, validate it and return one 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 file single php. or similar (will depend on your structure), just put the captcha and add a connection form. I will post with Fetch and XMLHttpRequest, 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>
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);
}

0


Include the part you want to lock inside 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 reCaptcha check return (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 also need to insert the client part in a page form. Click on <head> the API:

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

The form and 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>

Put it all together, it’d be 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>
  • Great, but how to make the Form disappear, and recaptcha after being validated ? It validates.. shows.. but after the content shown, continues showing the recaptcha just below...

  • Same thing: puts inside a if (!$resposta) {, that is, when $resposta for false.

  • Can you tell me how to do it ? I didn’t notice...

  • I updated the answer. Take a look.

  • Thank you so much !! Helped me with what I wanted !

Browser other questions tagged

You are not signed in. Login or sign up in order to post.