Skip to content

what a mistake that makes my reCAPTCHA returns message “not validate reCAPTCHA tokens”?

Tried many ways to implement google recaptcha, but in my admin console shown message: “your site does not validate reCAPTCHA tokens”.

Script included on the top of HTML page

<script src="https://www.google.com/recaptcha/api.js?render=my_site_key_here"></script>

My php realized form

    <?php
      function submit_details_form() {
        $form = <<<HTML
                <form class="modal-form" id="modal-container-screw" method="post" enctype="multipart/form-data" action="/wp-content/plugins/screw-cat_plugin/send-form.php">
                  <input type="hidden" name="g-recaptcha_response" id="g-recaptcha-response">
                  <input type="hidden" name="action" value="validate_captcha">
                  *other inputs*...
                  <button type="submit" name="submitBtn" id='submit-btn-screw'>Submit</button>
                </form>
        HTML;
       return $form; }
    ?>

My javascript reCAPTCHA code

window.addEventListener("load", function(){
  grecaptcha.ready(function() {
  //do request for recaptcha token
  //response is promise with passed token
  grecaptcha.execute('6LffySQbAAAAADoL3UKMcHfGAbdiqcaSkq5crucT', {action:'validate_captcha'})
    .then(function(token) {
      //add token value to form
      document.getElementById('g-recaptcha-response').value = token;
    });
  });
});

My php code for submiting for data

$recaptcha_url = 'https://www.google.com/recaptcha/api/siteverify';
$recaptcha_secret = 'my secret reCAPTCHA key here';
$recaptcha_response = $_POST['g-recaptcha-response'];
// Sending POST request and decode answer results
$recaptcha = file_get_contents($recaptcha_url . '?secret=' . $recaptcha_secret . '&response= . '$recaptcha_response . "&remoteip=" . $_SERVER['REMOTE_ADDR']);
print_r($recaptcha);
$recaptcha = json_decode($recaptcha);
// Тake measures depending on the result
  if ($recaptcha->score >= 0.3) {
  $success_msg = "Success!";
  echo '<script language="javascript">';
  echo 'alert("Successful spam check.")';
  echo '</script>'; 
  sendWithAttachments("myemail@mail.com", "Some mail theme");
} else {
  $recaptchaToArr = json_decode(json_encode($recaptcha), true);
  echo '<script language="javascript">';
  echo 'alert("Failed spam check.")';
  echo '</script>';
}

print_r($recaptcha); displays { "success": false, "error-codes": [ "invalid-input-response" ] }

Answer

The issue I believe is a simple one. The original syntax error as per the comment was a curve ball but on closer inspection and some rudimentary testing reveals that the spelling of g-recaptcha-response in the PHP and g-recaptcha_response in Form were causing the problem.

<?php
    
    
    define('_PUBKEY','6LffySQbAAAAADoL3UKMcHfGAbdiqcaSkq5crucT');
    define('_PRIVKEY','xxxxxxxxxxx');
    define('SEND_MESSAGE',false);
    
    if( $_SERVER['REQUEST_METHOD'] == 'POST' && isset(
        $_POST['g-recaptcha-response'],
        $_POST['action']
    )){
    
        $baseurl = 'https://www.google.com/recaptcha/api/siteverify';
        $secret = _PRIVKEY;
        $url=sprintf(
            '%s?secret=%s&response=%s&remoteip=%s', 
            $baseurl, 
            $secret, 
            $_POST['g-recaptcha-response'], 
            $_SERVER['REMOTE_ADDR']
        );

        $json = json_decode( file_get_contents( $url ) );

        if ( $json->score >= 0.3 ) {
          echo '
          <script>
            alert("Successful spam check.")
          </script>'; 
          
          if( SEND_MESSAGE && function_exists('sendWithAttachments') )sendWithAttachments("myemail@mail.com", "Some mail theme");
          
        } else {
          echo '
          <script>
            alert("Failed spam check.")
          </script>';
        }
    }
    
?>
<!DOCTYPE html>
<html lang='en'>
    <head>
        <meta charset='utf-8' />
        <title>Google recaptcha</title>
        <script>
            <?php
                printf('
                const _PUBKEY="%s";
                ',_PUBKEY);
            ?>
            window.addEventListener("load", function(){
                grecaptcha.ready(()=>{
                    console.log('ready')
                    grecaptcha.execute( _PUBKEY, { action:'validate_captcha' })
                        .then(( token )=>{
                            document.getElementById('g-recaptcha-response').value = token;
                        });
                });
            });
        </script>
        <script src='//www.google.com/recaptcha/api.js?render=<?php echo _PUBKEY;?>' async defer></script>
    </head>
    <body>
    
        <form class='modal-form' id='modal-container-screw' method='post' enctype='multipart/form-data'>
          <input type='text' name='g-recaptcha-response' id='g-recaptcha-response' />
          <input type='hidden' name='action' value='validate_captcha' />
          <input type='submit' />
        </form>
        
        
    </body>
</html>