I am setting an invisible reCAPTCHA in my web application and having trouble verifying the user’s response. (even though I am passing the correct POST parameters)
I am programmatically invoking the challenge by calling grecaptcha.execute();
on the client-side. And submitting the form afterwards (registrationForm.submit();
) using the recaptcha callback:
<div class="g-recaptcha"
data-sitekey="SITE_KEY"
data-callback="onSubmit"
data-size="invisible">
</div>
Now after reading «Verifying the user’s response» documentation, I figured that the response token is passed as a POST parameter to g-recaptcha-response
:
For web users, you can get the user’s response token in one of three ways:
- g-recaptcha-response POST parameter when the user submits the form on your site
- …
So I am using Fetch to create a POST request on the server side to the verification endpoint with the required body data:
verify(req, res, next) {
const VERIFY_URL = "https://www.google.com/recaptcha/api/siteverify";
return fetch(VERIFY_URL, {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({
secret: process.env.RECAP_INVIS_SECRET_KEY,
response: req.body['g-recaptcha-response'],
}),
})
.then(response => response.json())
.then(data => {
res.locals.recaptcha = data;
return next();
});
}
But I keep getting the following response:
{
success: false,
error-codes: [ ‘missing-input-response’, ‘missing-input-secret’ ]
}
Even though I am passing the response and secret as JSON data in the POST body.
Am I doing something wrong? Regards.
Как устранить ошибку Captcha в браузере Chrome
Я устанавливаю невидимую reCAPTCHA в своем веб-приложении и не могу проверить ответ пользователя. (хотя я передаю правильные параметры POST)
Я программно вызываю вызов, вызывая grecaptcha.execute();
на стороне клиента. И отправка формы после (registrationForm.submit();
) с помощью обратного вызова recaptcha:
Теперь после прочтения «Проверка ответа пользователя» документации, я решил, что токен ответа передается как параметр POST в g-recaptcha-response
:
Для веб-пользователей вы можете получить токен ответа одним из трех способов:
- g-recaptcha-response параметр POST, когда пользователь отправляет форму на вашем сайте
- …
Поэтому я использую Fetch для создания запроса POST на стороне сервера к конечной точке проверки с необходимыми данными тела:
verify(req, res, next) { const VERIFY_URL = 'https://www.google.com/recaptcha/api/siteverify'; return fetch(VERIFY_URL, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ secret: process.env.RECAP_INVIS_SECRET_KEY, response: req.body['g-recaptcha-response'], }), }) .then(response => response.json()) .then(data => { res.locals.recaptcha = data; return next(); }); }
Но я получаю такой ответ:
{успех: ложь, коды ошибок: [‘отсутствует-ввод-ответ’, ‘отсутствует-ввод-секрет’]}
Хотя я передаю ответ и секрет как данные JSON в теле сообщения POST.
Я делаю что-то неправильно? С уважением.
Проведя небольшое исследование и покопавшись на форумах Google, посвященных reCaptcha, кажется, что эта конечная точка принимает только тип контента по умолчанию; application/x-www-form-urlencoded
.
Это означает, что вам следует не используйте JSON для отправки токена ответа и ключа сайта. Вместо этого отправьте значение как application/x-www-form-urlencoded
определено:
Формы, отправленные с этим типом контента, должны быть закодированы следующим образом:
- Имена и значения элементов управления экранированы. Пробелы заменяются на ‘+’, а затем зарезервированные символы экранируются, как описано в [RFC1738], раздел 2.2: Неалфавитно-цифровые символы заменяются ‘% HH’, знаком процента и двумя шестнадцатеричными цифрами, представляющими код ASCII персонаж. Разрывы строк представлены парами «CR LF» (т. Е. «% 0D% 0A»).
- Имена / значения элементов управления перечислены в порядке их появления в документе. Имя отделяется от значения знаком ‘=’, а пары имя / значение отделяются друг от друга знаком ‘&’.
Следовательно, у вас есть два способа сделать это: либо передать параметры POST через URL-адрес (строки запроса), либо отправить их как запрос POST:
https://www.google.com/recaptcha/api/siteverify?secret=${SECRET_KEY}&response=${req.body['g-recaptcha-response']}
или добавив данные в тело вручную, например:
verify(req, res, next) { const VERIFY_URL = 'https://www.google.com/recaptcha/api/siteverify'; return fetch(VERIFY_URL, { method: 'POST', headers: { 'Content-Type': 'application/x-www-form-urlencoded' }, body: `secret=${SECRET_KEY}&response=${req.body['g-recaptcha-response']}`, }) .then(response => response.json()) .then(data => { res.locals.recaptcha = data; return next(); }); }
- 1 Спасибо! Решение с параметрами POST сработало для меня.
Tweet
Share
Link
Plus
Send
Send
Pin
Solution 1
Please note : g-recaptcha-respone
!= g-recaptcha-response
Google reCatcha API you might need to specify additional parameters to the file_get_contents
function call, setting the context options specifically for SSL (If site has SSL).
// If submitted check response
if ($_POST["g-recaptcha-response"]) {
// Input data
$secret = 'SECRET_KEY';
$response = $_POST['g-recaptcha-response'];
$remoteip = $_SERVER['REMOTE_ADDR'];
$url = "https://www.google.com/recaptcha/api/siteverify";
$post_data = http_build_query(
array(
'secret' => $secret,
'response' => $response,
'remoteip' => $remoteip
)
);
$options=array(
// If site has SSL then
'ssl'=>array(
// In my case its /etc/ssl/certs/cacert.pem
'cafile' => '/path/to/cacert.pem',
'verify_peer' => true,
'verify_peer_name' => true,
),
'http' =>
array(
'method' => 'POST',
'header' => 'Content-type: application/x-www-form-urlencoded',
'content' => $post_data
)
);
$context = stream_context_create( $options );
$result_json = file_get_contents( $url, false, $context );
$resulting = json_decode($result_json, true);
if($resulting['success']) {
//Success
} else {
// action for no response
}
At least on ubuntu — If site has SSL
cd /usr/local/share/ca-certificates
sudo curl http://curl.haxx.se/ca/cacert.pem -o cacert.crt
sudo update-ca-certificates
sudo update-ca-certificates –fresh
and your cafile and path will be
capath=/etc/ssl/certs/
cafile=/etc/ssl/certs/cacert.pem
Solution 2
In my case I needed to add two extra parameters ('', '&'
) in this call:
http_build_query(array(
'secret' => $secret,
'response' => $response,
'remoteip' => $remoteip
), '', '&');
Solution 3
I’m not able to comment so I’m going to answer here. I copied my code which works perfectly and btw $_POST['g-recaptcha-respone']
, are you sure your inputs name is g-recaptcha-respone
?
$secret = 'SECRET-KEY';
$response = $_POST['g-recaptcha-response'];
$ip = $_SERVER['REMOTE_ADDR'];
$dav = file_get_contents("https://www.google.com/recaptcha/api/siteverify?secret=".$secret."&response=".$response."&remoteip=".$ip);
$res = json_decode($dav,true);
if ($res['success']) {
die(json_encode(0));
} else {
die(json_encode(1));
}
Solution 4
This error happened to me because I had two instances of the ReCaptcha element on my page (one for mobile views, one for desktop). As soon as I removed one of them this error stopped.
Solution 5
Just a note on this, you should be sending all your params via POST not GET (see https://developers.google.com/recaptcha/docs/verify#api_request). Use something like cURL to help make the request.
Related videos on Youtube
03 : 54
FIX Recaptcha Not Working in Google Chrome [Tutorial]
08 : 08
Validate Google reCAPTCHA using JavaScript
01 : 05
Recaptcha Not Working in Google Chrome [Tutorial]
17 : 33
Using reCAPTCHA in React and Node
05 : 30
How to bypass Google ReCaptcha automatically for FREE.
14 : 41
Integrate Google’s recptcha in ReactJS and verifying user response in NodeJS
17 : 37
Recaptcha Response Verification
01 : 04
Google ReCaptcha not posting g-recaptcha-response — PHP
Comments
-
I have a problem with google reCaptcha.
Here is my php code:
$secret = 'SECRET_KEY'; $response = $_POST['g-recaptcha-respone']; $remoteip = $_SERVER['REMOTE_ADDR']; $url = "https://www.google.com/recaptcha/api/siteverify?secret=$secret&response=$response&remoteip=$remoteip"; $result_json = file_get_contents($url); $resulting = json_decode($result_json, true); print_r($resulting); if($resulting['success']) { //Success }
input of print_r is: Array ( [success] => [error-codes] => Array ( [0] => missing-input-response ) )
How to solve this problem?
Thanks for answers
-
Thank you for your response! Honestly I didn’t expect that the «http_build_query» was not building the correct query.
-
With my version of PHP (5.4.34), the result of http_build_query uses the html entity ‘&’ to separate parameters. Adding the extra two parameters (the second isn’t needed except to allow specifying the third) forces the result to separate the parameters with just plain ‘&’. The description of http_build_query does say that it builds a url-encoded query, but the description of url_encode says that is uses %-encoding for non-alphanumeric characters, but has a long note concluding that the most portable arg separator would be ‘&’ . What a mess!
-
Google says you should use POST, but actually GET works fine. I just tried it.
Recents
Answer by Iris Weaver
Now after reading «Verifying the user’s response» documentation, I figured that the response token is passed as a POST parameter to g-recaptcha-response:,I am programmatically invoking the challenge by calling grecaptcha.execute(); on the client-side. And submitting the form afterwards (registrationForm.submit();) using the recaptcha callback:,I am setting an invisible reCAPTCHA in my web application and having trouble verifying the user’s response. (even though I am passing the correct POST parameters),{
success: false,
error-codes: [ ‘missing-input-response’, ‘missing-input-secret’ ]
}
Therefore, you got two ways of doing this, either by passing the POST parameters through the URL (query strings) and sending it as a POST request:
https://www.google.com/recaptcha/api/siteverify?secret=${SECRET_KEY}&response=${req.body['g-recaptcha-response']}
or appending the data to the body manually like so:
verify(req, res, next) {
const VERIFY_URL = "https://www.google.com/recaptcha/api/siteverify";
return fetch(VERIFY_URL, {
method: "POST",
headers: { "Content-Type": "application/x-www-form-urlencoded" },
body: `secret=${SECRET_KEY}&response=${req.body['g-recaptcha-response']}`,
})
.then(response => response.json())
.then(data => {
res.locals.recaptcha = data;
return next();
});
}
Answer by Renata Perez
As far as I can see, there is nothing wrong with your request, syntax wise anyways. It’s possible that you still need to add a couple of other cURL options, but I haven’t used this API so that’s just a guess on my part.
$captcha = Curl::to('https://www.google.com/recaptcha/api/siteverify')
->withData(array(
'secret' => 'my_secret',
'response' => $recaptcha_response,
'remoteip' => $_SERVER['REMOTE_ADDR']
))->asJson(true)->post();
Answer by Mikayla Burch
I have explained how to use Google reCAPTCHA in another post. Google returns “true” or “false” in “success” parameter as a response to your AJAX call.,
Home » Development » Solved: Google reCAPTCHA always returns “false” as a response to AJAX call
,You might be sending “secret” and “response” parameters as hash map. Your code may look like this:,After your implementation, you might be constantly getting “false” value in this parameter. The response looks like this in your browser trace:
You might be sending “secret” and “response” parameters as hash map. Your code may look like this:
$.ajax({
type: "POST",
url: "https://www.google.com/recaptcha/api/siteverify",
data: {
secret: "YOUR-SECRET-KEY",
response: captchaResult
},
contentType: "application/json; charset=utf-8",
dataType: "json",
failure: function (response) {
alert(response.d);
},
success: function (response) {
googleCallResult = response.success;
}
}).done(function () {
// Do stuff with googleCallResult
});
Google reCAPTCHA expects parameters to be sent in the URL instead of hash map. So you need to add “secret” and “response” parameters into the URL. Here is the edited code:
$.ajax({
type: "POST",
url: "https://www.google.com/recaptcha/api/siteverify?secret=YOUR-SITE-KEY&response=" + captchaResult,
contentType: "application/json; charset=utf-8",
dataType: "json",
failure: function (response) {
alert(response.d);
},
success: function (response) {
googleCallResult = response.success;
}
}).done(function () {
// Do stuff with googleCallResult
});
Answer by Everett Shepard
I am setting an invisible reCAPTCHA in my web application and having trouble verifying the user’s response. (even though I am passing the correct POST parameters),Doing a bit of research and digging around the reCaptcha Google forums, It seems that this endpoint only accepts the default content type; application/x-www-form-urlencoded.,Therefore, you got two ways of doing this, either by passing the POST parameters through the URL (query strings) and sending it as a POST request:,g-recaptcha-response POST parameter when the user submits the form on your site
I am programmatically invoking the challenge by calling grecaptcha.execute();
on the client-side. And submitting the form afterwards (registrationForm.submit();
) using the recaptcha callback:
<div class="g-recaptcha"
data-sitekey="SITE_KEY"
data-callback="onSubmit"
data-size="invisible">
</div>
So I am using Fetch to create a POST request on the server side to the verification endpoint with the required body data:
verify(req, res, next) {
const VERIFY_URL = "https://www.google.com/recaptcha/api/siteverify";
return fetch(VERIFY_URL, {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({
secret: process.env.RECAP_INVIS_SECRET_KEY,
response: req.body['g-recaptcha-response'],
}),
})
.then(response => response.json())
.then(data => {
res.locals.recaptcha = data;
return next();
});
}
Answer by Lilyana Schultz
I am trying out the demo but I keep getting «reCAPTCHA validation failed (error code: missing-input-response)» because my Validate.IsValid is always false:,I chose the correct reCAPTCHA type (at https://www.google.com/recaptcha/ and in the demo) and copied the site and secret keys correctly.,LearnTrainingWelcomeGuided PathsTraining PlannerCoursesTech TalksClassroomCertificationsDocumentationOverviewOutSystems 11Best PracticesHow-to Guides
It would be interesting to check if your sitekey is valid, because the error code is that the information in the request is missing, if you have not created your own sitekey check recaptcha documentation for further clarification, see also a new version of hcaptcha in the forge.