<?php
$sitekey = 'xxxxxxxxxxxxxxxxxxxxxxxxxxxx';        // reCAPTCHA v3 sitekey
$secretkey = 'xxxxxxxxxxxxxxxxxxxxxxxxxxxx'; // reCAPTCHA v3 secretkey
//reCAPTCHA token
$token = isset( $_POST[ 'try_recaptcha-response' ] ) ? $_POST[ 'try_recaptcha-response' ] : NULL;
//reCAPTCHA action
$action = isset( $_POST[ 'action' ] ) ? $_POST[ 'action' ] : NULL;
 
$Ret = ''; // result strings
 
if ( $token && $action) {//token&action取得時
  //get API Response
  $ch = curl_init();  //cURL session initialize
  curl_setopt($ch, CURLOPT_URL,"https://www.google.com/recaptcha/api/siteverify");
  curl_setopt($ch, CURLOPT_POST, true );
  curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query(array('secret' => $secretKey, 'response' => $token )));
  curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
  $api_response = curl_exec($ch);
  curl_close($ch);
  
  //API Response decode(JSON形式)
  $result = json_decode( $api_response );
  //$result->success = true(成功) / $result->action == $action(アクション名一致) / score 0.5以上はOK
  if ( $result->success && $result->action === $action && $result->score >= 0.5) { //score 0.5以上はOK
    $Ret = '合格： $result->score : ' . $result->score;
    // この場合に成功時の処理を入れれば良い。
  } else {
    $Ret = '不合格';
    // エラー処理を実行
  }
}
?>
<!DOCTYPE html>
<html lang="ja">
<head>
<title>Google reCAPTCHA v3検証</title>
</head>
<body>
  <h1>PHPを使っての検証</h1>
  <form id="try_form" method="post">
    <button type="submit">送信</button>
  </form>
  <div>
    <p>［検証結果］</p>
    <p><?php echo $Ret; ?></p>
  </div>
<script src="https://www.google.com/recaptcha/api.js?render=<?php echo $siteKey; ?>"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<script>
jQuery(function($){
  jQuery('#try_form').submit(function(event) {
    event.preventDefault();
    var action_name = 'contact'; //アクション名 
    grecaptcha.ready(function() {
      grecaptcha.execute('<?php echo $siteKey; ?>', { action: action_name }).then(function(token) {
        jQuery('#try_form').prepend('<input type="hidden" name="try_recaptcha-response" value="' + token + '">');
        jQuery('#try_form').prepend('<input type="hidden" name="action" value="' + action_name + '">');
        jQuery('#try_form').unbind('submit').submit();
      });;
    });
  });
})
</script>
</body>
</html>