Google reCAPTCHA V2 Response Error

A

Anonymous

Guest
Hello, it's my first time posting here and I'm not good with such stuff as the one I'm posting right now

I have been trying to solve this issue for 2 days by now so I could use some help lol

This error "Please solve the captcha." is showing even if the captcha is verified so it's showing in the both cases (verified/unverified).

Thanks in advance.


>> PHP Part:

```

<?php

require_once 'db/setting.php';
require_once 'db/odbc.php';

session_start();
error_reporting(0);

if (isset($_SERVER['HTTPS']) &&
($_SERVER['HTTPS'] == 'on' || $_SERVER['HTTPS'] == 1) ||
isset($_SERVER['HTTP_X_FORWARDED_PROTO']) &&
$_SERVER['HTTP_X_FORWARDED_PROTO'] == 'https') {
$protocol = 'https://';
}
else {
$protocol = 'http://';
}
$currentDomain = $protocol.$_SERVER[HTTP_HOST];

$API["secret_key"] = "xx";
$API["api_key"] = "xx";
$API["callback"] = $currentDomain."/vote-reward-tok.php?return={RETURNEDCODE}";
$API["API_Domain"] = "http://api.top-kal.com";

$secretKey = 'xxx';
$captcha = $_POST['g-recaptcha-response'];
$ip = $_SERVER['REMOTE_ADDR'];
$responseData=file_get_contents("https://www.google.com/recaptcha/api/siteverify?secret=".$secretKey."&responseData=".$captcha."&remoteip=".$ip);
$responseKeys = json_decode($responseData,true);

$config["db_username"] = "sa";
$config["db_password"] = "********";
$config["db_database_account"] = "kal_auth";
$config["db_database_player"] = "kal_db";
$config["db_server"] = "NAME\SQLEXPRESS";
$config["db_driver"] = "SQL Server";

$config["Reward_Name"] = "Vote Coin";
$config["MinLvl_Require"] = 30;
$config["Reward_Index"] = 447;
$config["Reward_Amount"] = 10;
$config["Reward_Bound"] = false;
```

>> SQL Part
```
function insertRewards($account_unique_id){
global $config;

$connect = odbc_connect('Driver={'.$config["db_driver"].'};Server='.$config["db_server"].';Database='.$config["db_database_player"].';', $config['db_username'] ,$config['db_password']);

if(!$connect)
return false;

$query = odbc_exec($connect,"SELECT Top 1 [IID] FROM [Item] Where [IID] < 1 order by IID Desc");
if(!$query)
return false;

$data = odbc_fetch_array($query);
if($data && !empty($data) && isset($data["IID"]))
odbc_exec($connect,"INSERT INTO [Item] ([PID],[IID],[Index],[Prefix],[Info],[Num])VALUES ($account_unique_id,".($data["IID"]+1).",".$config["Reward_Index"].",0,".(16+($config["Reward_Bound"] ? 128 : 0)).",".$config["Reward_Amount"].")");

}

function checkCharacters($accountUID){
global $config;

$connect = odbc_connect('Driver={'.$config["db_driver"].'};Server='.$config["db_server"].';Database='.$config["db_database_player"].';', $config['db_username'] ,$config['db_password']);

if(!$connect)
return array("error" => "failed to connect to database players.");

$query = odbc_exec($connect,"SELECT [Level] FROM [Player] WHERE [UID] = $accountUID ORDER BY [Level] DESC");
if(!$query)
return array("error" => "failed to find characters in this account id.");

while($r = odbc_fetch_array($query)){
if($r["Level"] >= $config["MinLvl_Require"])
return array("success" => $accountUID);
}
return array("error" => "You should have one character at least higher than level : ".$config["MinLvl_Require"]." to vote.");
}

function checkAccount($accountID){
global $config;

$connect = odbc_connect('Driver={'.$config["db_driver"].'};Server='.$config["db_server"].';Database='.$config["db_database_account"].';', $config['db_username'] ,$config['db_password']);

if(!$connect)
return array("error" => "failed to connect to database accounts.");

$query = odbc_exec($connect,"SELECT TOP 1 [UID] FROM [Login] WHERE [ID] = '$accountID'");
if(!$query)
return array("error" => "this account id not exists.");

$data = odbc_fetch_array($query);
if(!$data || empty($data) || !isset($data["UID"]))
return array("error" => "this account id not exists.");

if($config["MinLvl_Require"] > 0)
return checkCharacters($data["UID"]);

return array("success" => $data["UID"]);
}

```

>> Submitting Function

```
$response = array("error" => false , "success" => false , 'redirect' => false);

function post_content($query){
$query_array = array();foreach( $query as $key => $key_value )$query_array[] = urlencode( $key ) . '=' . urlencode( $key_value );return implode( '&', $query_array );
}

global $API;
$opts = array('http' => array('method' => 'POST',"header" => "Content-type: application/x-www-form-urlencoded\r\nAuthorization:".base64_encode($API["api_key"].":".$API["secret_key"])."\r\n", "content" => post_content($content)));return stream_context_create($opts);
}

function submit(){
global $API;

if(empty($captcha) || $captcha == '' || !isset($captcha))
return array( "error" => "Please solve the captcha.");

if (empty($_POST['account']) || !ctype_alnum($_POST['account']))
return array( "error" => "Invalid account id.");

$checkAccount = checkAccount($_POST['account']);

if (isset($checkAccount["error"]))
return array("error" => $checkAccount["error"]);

if (isset($checkAccount["success"])){
$account_unique_id = (isset($_SESSION['kal_id'])) ? $_SESSION['kal_id'] : $checkAccount["success"];
$result = json_decode(file_get_contents($API["API_Domain"] . '/api/generate/vote-rewards-token', false, postParams(array('callback' => $API["callback"],'account_unique_id' => $account_unique_id ))) , true);
{
echo '<br><center><h3>Please wait...</h3></center>';
}
if (!empty($result)){
if (isset($result["response"])){
if (isset($result["response"]["error"]))
return array("error" => $result["response"]["error"]);
elseif (isset($result["response"]["success"]))
return array("redirect" => '<script type="text/javascript">setTimeout(function () { window.location.href = "'.$result["response"]["success"].'";}, 500)</script>');
}
}
}
}
if ($_SERVER['REQUEST_METHOD'] == 'POST' && isset($_POST['account'])){
$response = submit();
if (isset($response['redirect']) && $response['redirect']){
echo $response['redirect'];
die;
}
}elseif (isset($_GET['return'])){
$result = json_decode(file_get_contents($API["API_Domain"] . '/api/verify/vote-rewards-token', false, postParams(array('returned_code' => $_GET['return']))) , true);
if (!empty($result)){
if (isset($result["response"])){
if (isset($result["response"]["error"]))
$response['error'] = $result["response"]["error"];
elseif (isset($result["response"]["success"])){
insertRewards($result["response"]["account_unique_id"]);
$response['success'] = '<b>Thank you, Your vote has been recorded and the server rank will be updated soon.<b><br />You will receive your rewards in storage of your account.<p>Your next vote in : <b>' . $result["response"]["NextVote"] . '</b></p>';
}
}
}
}
?>


```
>> HTML part:
```
<head>
<title>Vote Rewards - <?php echo $config['serverName']; ?></title>
<link rel="shortcut icon" href=images/favicon.png">
<link rel="stylesheet" href="css/vote.css">
<link rel="stylesheet" href="css/fontawesome.css">
<link rel="stylesheet" href="css/fontawesomeall.css">
<script src='https://www.google.com/recaptcha/api.js'></script>

</head>
<body>
<form class="vote-form" method="post">
<noscript><div class="isa_error">Javascript is not enabled in your browser! Please enable it or change your browser.</div></noscript>
<?php if(isset($response['error']) && $response['error']){ ?><div class="isa_error"> <?php echo $response['error'] ;?> </div> <?php } ?>
<?php if(isset($response['success']) && $response['success']){ ?><div class="isa_success"> <?php echo $response['success'] ;?> </div>
<?php }else{ ?>
<label>
<span>Account ID :</span>
<input type="text" name="account" maxlength="20" <?php echo (isset($_SESSION['kal_username'])) ? 'readonly value="'.$_SESSION['kal_username'].'"' : ""; ?>" />
</label>
<div class="g-recaptcha" style="margin:0 auto;" data-sitekey="xxx" data-theme="dark"></div>
<label class="label_btn">
<input type="submit" class="button" value="Vote" />
</label>
<?php } ?>
</form>
<script src="https://code.jquery.com/jquery-3.2.1.min.js"></script>
</body>
</html>
```

Sorry if the topic is way too long but I'm desperate =DD
 
I know this thread is over two weeks old, but here's my contact page PHP
Code:
<?php

require_once '../private/initialize.php';
if (is_logged_in()) {
    $smarty->assign('display_status', true);
}
else {
    $smarty->assign('display_status', false);
}
use Library\Database\Database as DB;
use Library\Email\Email;
$highlight = ["normal", "normal", "normal", "normal", "selected", "normal"];

$username = \NULL;
$success = "Contact Form";
$token = $_SESSION['token'];
$db = DB::getInstance();
$pdo = $db->getConnection();

if (!isset($_SESSION['user']->id)) {
    $smarty->assign('security_level', \NULL);
    $login_status = FALSE;
} else {
    $smarty->assign('security_level', $_SESSION['user']->security_level);
    $login_status = TRUE;
    $username = $_SESSION['user']->username;
}

$submit = filter_input(INPUT_POST, 'submit', FILTER_SANITIZE_FULL_SPECIAL_CHARS);
if (isset($submit) && $submit === 'submit') {
    $token = filter_input(INPUT_POST, 'token', FILTER_SANITIZE_FULL_SPECIAL_CHARS);
    if (!empty($token)) {
        if (hash_equals($_SESSION['token'], $token)) {
            /* The Following to get response back from Google recaptcah */
            $url = "https://www.google.com/recaptcha/api/siteverify";

            $remoteServer = filter_input(INPUT_SERVER, 'REMOTE_ADDR', FILTER_SANITIZE_URL);
            $response = file_get_contents($url . "?secret=" . PRIVATE_KEY . "&response=" . \htmlspecialchars($_POST['g-recaptcha-response']) . "&remoteip=" . $remoteServer);
            $recaptcha_data = json_decode($response);
            /* The actual check of the recaptcha */
            if (isset($recaptcha_data->success) && $recaptcha_data->success === TRUE) {
                $success = "Mail was sent!";
                $data['name'] = filter_input(INPUT_POST, 'name', FILTER_SANITIZE_FULL_SPECIAL_CHARS);
                $data['email'] = filter_input(INPUT_POST, 'email', FILTER_SANITIZE_FULL_SPECIAL_CHARS);
                $data['phone'] = filter_input(INPUT_POST, 'phone', FILTER_SANITIZE_FULL_SPECIAL_CHARS);
                $data['website'] = filter_input(INPUT_POST, 'website', FILTER_SANITIZE_FULL_SPECIAL_CHARS);
                $data['reason'] = filter_input(INPUT_POST, 'reason', FILTER_SANITIZE_FULL_SPECIAL_CHARS);
                $data['comments'] = filter_input(INPUT_POST, 'comments', FILTER_SANITIZE_FULL_SPECIAL_CHARS);

                $send = new Email($data);
            } else {
                $success = "You're not a human!"; // Not of a production server:
            }
        } else {
            // Log this as a warning and keep an eye on these attempts
        }
    }
}

$smarty->assign('holidayMessage', $holiday_message);
$smarty->assign('highlight', $highlight);
$smarty->assign('title', "Contact Page");
$smarty->assign('pagename', ucfirst($pageName));
$smarty->assign('username', $username);
$smarty->assign('login_status', $login_status); // Login Status:
$smarty->assign('token', $token);
$smarty->assign('success', $success);
//$smarty->caching = 1;


$smarty->assign('calendar', $calendar);
$smarty->display('contact_template.tpl');
I use a Smarty a template engine as I find it easier separating the PHP from the HTML/CSS. plus it adds a little more security to the php. Anyways look at the PHP code after the third nested if statement as that is the meat & potatoes of the reCAPTCHA portion of it.

Here's the HTML template
Code:
{extends file="general_page_template.tpl"}
{block name=title}
    {$title|escape}
{/block}

{block name=body}
    <div class="contact-style">
        <form class="contact" name="contact" action="contact.php" method="post"  autocomplete="on">
            <fieldset>
                <legend>{$success}</legend>
                <input type="hidden" name="token" value="{$token}">
                <label for="name" accesskey="U">Name</label>
                <input name="name" type="text" id="name" tabindex="1" autofocus required="required" />

                <label for="email" accesskey="E">Email</label>
                <input name="email" type="email" id="email" tabindex="2" required="required" />

                <label for="phone" accesskey="P" >Phone <small>(optional)</small></label>
                <input name="phone" type="tel" id="phone" tabindex="3">

                <label for="web" accesskey="W">Website <small>(optional)</small></label>
                <input name="website" type="text"  id="web" tabindex="4">

                <div class="radioBlock">
                    <input type="radio" id="radio1" name="reason" value="message" tabindex="5" checked>
                    <label class="radioStyle" for="radio1">message</label>
                    <input type="radio" id="radio2" name="reason" value="order">
                    <label class="radioStyle" for="radio2">order</label>  
                    <input type="radio" id="radio3" name="reason" value="status">
                    <label class="radioStyle" for="radio3">status inquiry</label>    
                </div>

                <label class="textBox" for="comments">Comments</label>
                <textarea name="comments" id="comments" spellcheck="true" tabindex="6" required="required"></textarea> 
                <div class="g-recaptcha" data-sitekey="6LdXNpAUAAAAAMwtslAEqbi9CU3sviuv2imYbQfe"></div>
                <input type="submit" name="submit" value="submit" tabindex="7">
            </fieldset>
        </form>
    </div>
    {block name="aside"}
    {/block}

{/block}
 
Back
Top