Jump to content

g-recaptcha-response not working


Smashden

Recommended Posts

Hello, during testing reCAPTCHA from google I am having trouble that I can not fix it.

I add:

<td>
    <div class="g-recaptcha" data-sitekey="my site key"></div>
    <script src="https://www.google.com/recaptcha/api.js"></script>
</td>

to my form. 

And this:

function json_status($status)
{
	echo json_encode(array('status' => $status));
}

if ( $_SERVER['REQUEST_METHOD'] === 'POST' )
{
	$captcha = $_POST['g-recaptcha-response'];
	if(!empty($captcha))
	{	
		$google_url = "https://www.google.com/recaptcha/api/siteverify";
		$secret = 'my secret key';
		$ip = $_SERVER['REMOTE_ADDR'];
		$captchaurl = $google_url."?secret=".$secret."&response=".$captcha."&remoteip=".$ip;
												
		$curl_init = curl_init();
		curl_setopt($curl_init, CURLOPT_URL, $captchaurl);
		curl_setopt($curl_init, CURLOPT_RETURNTRANSFER, 1);
		curl_setopt($curl_init, CURLOPT_TIMEOUT, 10);
		$results = curl_exec($curl_init);
		curl_close($curl_init);
												
		$results= json_decode($results, true);
		if($results['success'])
		{	
			//my code
		} else {
			json_status('Invalid reCAPTCHA code.');
		}			
	} else {
		json_status('Please re-enter your reCAPTCHA.'); 
	}			

is my *.php which getting POST send by JS.

 

Here is my JS:

function onRulesCheck(node) {
	if (node.checked) {
		node.disabled = true;
		$('#sign_up').prop( "disabled", false);
	}
}

$(function(){

	var form	= $('#form');
	var submit 	= $('#sign_up');
	var alert	= $('.alert');
	var alert_error	= $('.alert_error');
	var alert_error2 = $('.alert_error2');

	// validate form
	form.validate({
		// validation rules
		rules: {
			// account_name field (required , minimum length 3, max 
			account_name: {
				required: true,
				minlength: 5,
				maxlength: 11
			},
			// account_password field (required , minimum length 6, max 16)
			account_password: {
				required: true,
				minlength: 5,
				maxlength: 32
			},
			// account_password2 field must be equal to password field
			account_password2: {
				equalTo: '#account_password'
			},
			
			// email field only required
			email: 'required'
		},
		// submit ajax request
		submitHandler: ajaxSubmit
	});

	/**
	* ajax submit function
	* sending simple ajax request
	**/

	function ajaxSubmit() {
		$.ajax({
			url: 'modules/account_create.php',
			type: 'POST',
			dataType: 'json',
			// form serialize data
			data: form.serialize(),
			beforeSend: function(){
				alert.fadeOut();
				alert_error.fadeOut();
				submit.val('Sending...').attr('disabled', 'disabled');
			},
			success: function(data){
				if ( data.status === 'success' ) {
					// if response status == success redirect to success page
					alert.fadeIn();
					alert_error2.html('Account Created!').fadeIn();		
				} else {
					// not success! show error messages
					alert.fadeIn();
					alert_error.html(data.status).fadeIn();
					submit.val('Sign Up').removeAttr('disabled');
				}
			},
			error: function(){
				// show error message			
				submit.val('Sign Up').removeAttr('disabled');
			}
		});
	};
});

I always have this error: "Please re-enter your reCAPTCHA."

Link to post
Share on other sites

If you are getting that message then it appears the  g-recaptcha-response  value is not being submitted by your form. 

 

Make the google recaptha code is within your  <form></form  tags and can you confirm there is a  g-recaptcha-response  value when submitting the form. To see the submitted values add  console.log(form.serialize());  after  function ajaxSubmit() { - You will need to look at your browsers development console tab to see the logged value returns (press F12 key or right click anywhere on the page select Inspect Element and then select console tab)

Link to post
Share on other sites
			<form id="form" class="form-horizontal" action="" method="post">		
				<tr>	
					<td width="30%" style="vertical-align: top; padding-left: 10px;">
						<label for="email" class="control-label">
							<span class="register_label">Email Address:</span> <span class="required">*</span>
						</label>
					</td>		
					<td width="70%">
						<input type="text" name="email" id="email" required placeholder="Email Address">
						<div class="register_label_info">Please enter a valid email address if we need to contact you.</div>				
					</td>
				</tr>
				
				<tr>	
					<td width="30%" style="vertical-align: top; padding-left: 10px;">
						<label for="account_name" class="control-label">
							<span class="register_label">Account Name:</span> <span class="required">*</span>
						</label>
					</td>		
					<td width="70%">
						<input type="text" name="account_name" id="account_name" required placeholder="Account Name">
						<div class="register_label_info">Account name consists of numbers 0-9 and is at least 6 characters long.</div>				
					</td>
				</tr>		

				<tr>	
					<td width="30%" style="vertical-align: top; padding-left: 10px;">
						<label for="account_password" class="control-label">
							<span class="register_label">Choose a password:</span> <span class="required">*</span>
						</label>
					</td>		
					<td width="70%">
						<input type="password" name="account_password" id="account_password" required placeholder="Password">
						<div class="register_label_info">Password consists of letters a-z, numbers 0-9, symbols(~!@#%&;,:\^$.|?*+()) and is at least 6 characters long.</div>				
					</td>
				</tr>					

				<tr>	
					<td width="30%" style="vertical-align: top; padding-left: 10px;">
						<label for="account_password2" class="control-label">
							<span class="register_label">Repeat Password:</span> <span class="required">*</span>
						</label>
					</td>		
					<td width="70%">
						<input type="password" name="account_password2" id="account_password2" required placeholder="Repeat Password">			
					</td>
				</tr>				

				<tr>	
					<td width="30%" style="vertical-align: top; padding-left: 10px;">
						<label for="rlname" class="control-label">
							<span class="register_label">Your name:</span>
						</label>
					</td>		
					<td width="70%">
						<input type="text" name="rlname" id="rlname" required placeholder="Your name">			
					</td>
				</tr>	

				<tr>	
					<td width="30%" style="vertical-align: top; padding-left: 10px;">
						<label for="location" class="control-label">
							<span class="register_label">Your location:</span>
						</label>
					</td>		
					<td width="70%">
						<input type="text" name="location" id="location" required placeholder="Your location">					
					</td>
					
				</tr>
				
				<tr>	
					<td width="30%" style="vertical-align: top; padding-left: 10px;">
					</td>					
					<td>
						<label class="register_label_info"><span class="required">*</span> Required fields</label>
					</td>				
				</tr>				
				
				<tr>
					<td style="vertical-align: top; padding-left: 10px;">
						<b><label class="register_label">Verification:</label></b>
					</td>
					<td>
						<div class="g-recaptcha" data-sitekey="my site key"></div>
                                                <script src='https://www.google.com/recaptcha/api.js'></script>
					</td>
				</tr>
								
	
				<tr>		
					<td colspan="2">
						<label for="location" class="control-label">
							<div style="overflow-y: scroll; height: 200px;"><?php echo htmlspecialchars(@file_get_contents('documents/server_rules.txt'));?></div>						
						</label>	
					</td>						
				</tr>	

				<tr>
					<td width="30%" style="vertical-align: bot; padding-left: 10px;">
						<div class="controls">
							<input id="rules_check" type="checkbox" onclick="onRulesCheck(this)"/>
							<span class="register_label"><b>I agree with server rules</b></span>
						</div>					
					</td>					
				</tr>
				
				<tr>
					<td width="30%" style="vertical-align: bot; padding-left: 10px;">
						<div class="controls">
							<input class="btn btn-primary" id="sign_up" disabled="disabled" type="submit" value="Sign Up!">
						</div>					
					</td>					
				</tr>
			</form>

This is my form, I have g-recaptcha here. In console I have only 

email=&account_name=&account_password=&account_password2=&rlname=&location=

 

so g-recaptcha-response is no send to PHP. And I don't know how to fix it.

Link to post
Share on other sites

The reCapture is being displayed on your page right? If you can see it, then it should be embedding a textarea into the form, named as  g-recaptcha-response  .

 

 form.serialize();  should be containing all the field values from your form. What happens if your change  console.log(form.serialize());  to be

console.log($('#g-recaptcha-response').val());

Do you get a value when submitting the form?

Link to post
Share on other sites

Yeah, I have this:

03AHJ_VuvYDqg8zAe1koLOPTyLiHp222YxqldLe3lcxt-voWMubFb7F7BL--zxqWShUrxekUe3pwTLIH63GRWvdK8Po5GM-ch82FUVmR7DkLIzuwXyjYRikv0yhLdKzpKrkM-REpN8V20JGmaEdkJODnc_1nvmUitmBoDMWv2Uh5ax2zbkJP9eT0krmAE3zKvWGwDOX_VbGaarSZdN79D0nksEjmgYkPAKZOMqKqQQ1QG7ryAaiyjFVkh9NUQMeepdEsJF7FM8PPZwkhDHPy0S_9oa_d-ugRo_PbWPctO9wSk8m1KKj9a71vMyoenLf0Y_v0UCJoIG5WK3dTBXoqGhzaojNgrjWvlwL7VHMroECUqOx24sY0cAWJNyJhs2AR2IJIr06HBgH3DhayO4RPAdOS0J5353w7CWKrlF5ehmxsharT_vHUJAJTVX9WnOETM2N0f0NczX2nl9zcwM3fdqOcZZtPBHA2_ui2knvyAphX0ETTG0u0zTM0koPpbkSD_E-ne1le-DmrR74D2n2eqVTgEuPMF7Qm6WTKJCmIoEvrZllSdsS28ZyCAmDG75r21HXs7UQS2zWB7TITUIev1Nr6URL80544Bo420TOeM2PhJFcXmVgHvitUdaDhfGJ0EvBeokA2ZW6bjKGarNnSEmtplVuncMoAdRgXRFF21H2219MGB2_GvIDuFEX5xnhEIIkX_fc-4xRkOyEk2qSRQZIhNpk2PQ6otzCUUGm7IMUjfecx_wZwEIhjpXQWPNc6t2-jnsq5xSjtErvX6ES7ys4bYfjxhEw7pTIoz0kSXUnCqEtetegQJNc1xahnwu4VC-jzPNeR6Mdl7crlQv72afYNx6gxktdpNcp2P9z6w0I3hvwYLdV3-R7D4TW_eS54Wu-Bp5L-lF6UbKo9kI728MY78diKD01-HPqY6zn1cJS7VCTw9HuDUIFodccema7UVZYcasoZe40wSO0O-r9DKY_lQ1F0_0yhHghntdJdImwnNCa5-RWqInMDU

when I accept captcha

Link to post
Share on other sites

I'm not sure whats going on then form.serialize() works for me. I guess you have to add the recapture value manually, change the ajax  data:  option to be

            data: (function() {
                    formValues = form.serializeArray();
                    // add google recapture value to serlized form field values
                    formValues.push({name: 'g-recaptcha-response', value: $('#g-recaptcha-response').val()});
                    return formValues; })(),
Link to post
Share on other sites

The Google reCapture api requires you submit the secret key and recaptha response values via POST. Change your code to be

<?php

function json_status($status)
{
    echo json_encode(array('status' => $status));
}

if ( $_SERVER['REQUEST_METHOD'] === 'POST' )
{
    if(isset($_POST['g-recaptcha-response']) && !empty($_POST['g-recaptcha-response']))
    {   
        $captchaurl = "https://www.google.com/recaptcha/api/siteverify";

        // values for verifying recaptha
        $captcha_params = array(
            'secret'   => 'secret-key-here',
            'response' => $_POST['g-recaptcha-response'],
            'ip'       => $_SERVER['REMOTE_ADDR']
        );

        $curl_init = curl_init();
        curl_setopt($curl_init, CURLOPT_URL, $captchaurl);
        curl_setopt($curl_init, CURLOPT_RETURNTRANSFER, 1);

        // send recapture values via POST
        curl_setopt($curl_init, CURLOPT_POST, count($captcha_params));
        curl_setopt($curl_init, CURLOPT_POSTFIELDS, $captcha_params);

        curl_setopt($curl_init, CURLOPT_SSL_VERIFYPEER, false);

        $results = curl_exec($curl_init);
        curl_close($curl_init);

        $results = json_decode($results, true);

        if($results['success'])
        {   
            json_status('success');
        }
        else
        {
            json_status('Invalid reCAPTCHA code');
        }           
    }
    else
    {
        json_status('Please re-enter your reCAPTCHA.'); 
    }
}
  
Link to post
Share on other sites

Hello again :(

 

I created two captcha on my page and I have problem with second, first captcha works fine.

 

Look on my code, what it is wrong?

My page

[...]		
                <script src="javascript/recaptcha.js"></script>

		<div class="character_create target" style="display: none;">
			<hr class="account_edit">
			<?php include ("modules/character_create.php"); ?>
			<script src="javascript/character_create_script.js"></script>
		</div>
		<div class="character_delete target" style="display: none;">
			<hr class="account_edit">
			<?php include ("modules/character_delete.php"); ?>
			<script src="javascript/character_delete_script.js"></script>	
		</div>
[...]	

recaptcha.js

var CaptchaCallback = function(){
	grecaptcha.render('Captcha_Character_Create', {'sitekey' : 'my_site_key'});
	grecaptcha.render('Captcha_Character_Delete', {'sitekey' : 'my_site_key'});
}

modules/character_create.php -- here I have first captcha, this works.

 

modules/character_delete.php -- second captcha and not works.

[...]
		<div><center><span class="register_label" style="font-size: 20px;">Delete Character</div></center></span>
		<table style="padding-top: 15px">
			<form id="form_detete_character" class="form-horizontal" action="" method="post">		                [...]			
				<tr>
					<td style="vertical-align: top; padding-left: 10px;">
						<b><label class="register_label">Verification:</label></b>
					</td>
					<td>
						<div id="Captcha_Character_Delete"></div>
					</td>
				</tr>			
				
				<tr>
					<td width="30%" style="vertical-align: bot; padding-left: 10px;">
						<div class="controls">
							<input class="btn btn-primary" id="delete_character" type="submit" value="Delete Character">
						</div>					
					</td>					
				</tr>			
			</form>
		</table>

character_delete_script.js

$(function(){

	var form	= $('#form_detete_character');
	var submit 	= $('#delete_character');
	var alert	= $('.alert');
	var alert_error	= $('.alert_error');
	var alert_error2 = $('.alert_error2');

	// validate form
	form.validate({
		// validation rules
		rules: {

			character_password: {
				required: true,
				minlength: 5,
				maxlength: 32
			}
		},
		// submit ajax request
		submitHandler: ajaxSubmit
	});

	/**
	* ajax submit function
	* sending simple ajax request
	**/

	function ajaxSubmit() {
		console.log(form.serialize());
		$.ajax({
			url: 'modules/account/character_delete.php',
			type: 'POST',
			dataType: 'json',
			// form serialize data
			//data: form.serialize(),
			data: (function() {
                formValues = form.serializeArray();
                // add google recapture value to serlized form field values
                formValues.push({name: 'g-recaptcha-response', value: $('.g-recaptcha-response').val()});
            return formValues; })(),	
			
			beforeSend: function(){
				alert.fadeOut();
				alert_error.fadeOut();
				submit.val('Sending...').attr('disabled', 'disabled');
			},
			success: function(data){
				if ( data.status === 'success' ) {
					// if response status == success redirect to success page
					alert.fadeIn();		
					alert_error2.html('Your character was deleted.').fadeIn();		
					setTimeout(function(){window.location = "account.php?character_deleted"} , 1500)
				} else {
					// not success! show error messages
					alert.fadeIn();
					alert_error.html(data.status).fadeIn();
					submit.val('Delete Character').removeAttr('disabled');
				}
			},
			error: function(){
				// show error message				
				submit.val('Delete Character').removeAttr('disabled');
			}
		});
	};
});

modules/account/character_delete.php

<?php
[...]
header('Content-type: application/json');

function json_status($status)
{
    echo json_encode(array('status' => $status));
}

if ( $_SERVER['REQUEST_METHOD'] === 'POST' )
{ 
	[...]			
						if(isset($_POST['g-recaptcha-response']) && !empty($_POST['g-recaptcha-response']))
						{   
							$captchaurl = "https://www.google.com/recaptcha/api/siteverify";
										
							// values for verifying recaptha
							$captcha_params = array(
								'secret'   => 'my_secret_key',
								'response' => $_POST['g-recaptcha-response'],
								'ip'       => $_SERVER['REMOTE_ADDR']
							);

							$curl_init = curl_init();
							curl_setopt($curl_init, CURLOPT_URL, $captchaurl);
							curl_setopt($curl_init, CURLOPT_RETURNTRANSFER, 1);

							// send recapture values via POST
							curl_setopt($curl_init, CURLOPT_POST, count($captcha_params));
							curl_setopt($curl_init, CURLOPT_POSTFIELDS, $captcha_params);

							curl_setopt($curl_init, CURLOPT_SSL_VERIFYPEER, false);

							$results = curl_exec($curl_init);
							curl_close($curl_init);

							$results = json_decode($results, true);

							if($results['success'])
							{										
								if ($player->delete()){
									$account->logAction('Deleted character '.$player->getAttr('name'));
									json_status('success');	
									
								} else {
									json_status('ERROR');
								}								
							} else {
								json_status('Invalid reCAPTCHA code');
							}           
						} else {
							json_status('Please re-enter your reCAPTCHA.'); 
						}						
	} else { 
		json_status('You must complete all the fields.'); 
	}
}
?>

And last, in section <head> I have:

<script src="https://www.google.com/recaptcha/api.js?onload=CaptchaCallback&render=explicit" async defer></script>

I have this error: Please re-enter your reCAPTCHA.

Link to post
Share on other sites

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.