-->

Verify reCaptcha V2 : Always false

2020-07-25 23:09发布

问题:

I'm trying to implant reCaptcha V2 of Google in my website (developed in PHP & Wordpress).

I'm trying to verify if the user has checked this Captcha before the submit.

And here is my verification :

<?php

if(isset($_POST['g-recaptcha-response']) && !empty($_POST['g-recaptcha-response'])){
  $privatekey = $secret;
  $captcha = $_POST['g-recaptcha-response'];
  $url = 'https://www.google.com/recaptcha/api/siteverify';
  $data = array(
      'secret' => $privatekey,
      'response' => $captcha,
      'remoteip' => $_SERVER['REMOTE_ADDR']
  );

  $curlConfig = array(
      CURLOPT_URL => $url,
      CURLOPT_POST => true,
      CURLOPT_RETURNTRANSFER => true,
      CURLOPT_POSTFIELDS => $data
  );

  $ch = curl_init();
  curl_setopt_array($ch, $curlConfig);
  $response = curl_exec($ch);
  curl_close($ch);
  $jsonResponse = json_decode($response);
  if ($jsonResponse->success == true) {
            $succMsg = 'Your contact request have submitted successfully.';
            echo "<script>alert(\"OK\")</script>";
  }
  else {
      $errMsg = 'Robot verification failed, please try again.';
            echo "<script>alert(\"KO ROBOT\")</script>";
    }
}
else{

  $errMsg = 'Please click on the reCAPTCHA box.';
    echo "<script>alert(\"KO CLICK ON BOX\")</script>";
}
?>

When I reload the page, or when I submit without checked captcha, or when I checked captcha, it always displays:"KO ROBOT"

I have tried also with "file_get_contents" instead of curl, but I had an SSL error Warning.

Thanks.

UPDATE :

When i do this :

var_dump($jsonResponse);

I have this on my page :

object(stdClass)#4028 (2) { ["success"]=> bool(false) ["error-codes"]=> array(1) { [0]=> string(20) "invalid-input-secret" } }

UPDATE 2 :

Now i have this, after verification of my secret key :

object(stdClass)#4028 (2) { ["success"]=> bool(false) ["error-codes"]=> array(1) { [0]=> string(20) "timeout-or-duplicate" } }

回答1:

try with this one, just replace secret key.

<?php
$response   = isset($_POST["g-recaptcha-response"]) ? $_POST['g-recaptcha-response'] : null;
$privatekey = "YOUR PRIVATE KEY";

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "https://www.google.com/recaptcha/api/siteverify");
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, array(
    'secret' => $privatekey,
    'response' => $response,
    'remoteip' => $_SERVER['REMOTE_ADDR']
));

$resp = json_decode(curl_exec($ch));
curl_close($ch);

if ($resp->success) {

} else {

    //failed return mess
}
?>