Answer the question
In order to leave comments, you need to log in
Why is google reCAPTCHA not working correctly?
Created a check using google reCAPTCHA for the site.
reCAPTCHA type:Version 2 - invisible icon.
Sometimes when testing google reCAPTCHA, I get a message: “Unable to contact the reCAPTCHA service. Please check your internet connection and try again.”
The site works on Bitrix CMS, but almost pure PHP is used in reCAPTCHA processing on the server.
What could be the reason for the error?
$captcha - PHP array that stores the public and secret keys
I substitute the public key in the button button in the data-sitekey attribute,
I get it from the PHP configuration object where the keys are stored
HTML form code (simplified)
<?
// объект конфигурации Битрикс в котором хранятся ключи
$configuration = \Bitrix\Main\Config\Configuration::getInstance();
$captcha = $configuration->get('google_recaptcha');
?>
<script src="https://www.google.com/recaptcha/api.js" async defer></script>
<script src="https://www.google.com/recaptcha/api.js" async defer></script>
<button class="g-recaptcha form__btn btn" id="feedback_send" data-size="invisible" data-sitekey="<?=$captcha['value']['public']?>" data-callback="onSubmit">Отправить<div class="decor">>></div></button>
function onSubmit(token) {
if(token){
let err = 0;
err = err + checkFeedbackPhone(); // phone
err = err + checkFeedbackEmail(); // email
err = err + checkMessage(); // message
if(err == 0){
formAjax(token);
toggelFiledError(err);
}else{
grecaptcha.reset();
toggelFiledError(err);
}
}
}
// ajax функция отправки сообщения
formAjax: function(token) {
let email = $("#feedback input[name='email']").val(),
phone = $("#feedback input[name='phone']").val(),
iblock_id = $("#feedback input:hidden[name='iblock_id']").val(),
google_recaptcha = token,
message = $("#feedback textarea[name='message']").val();
let formData = new FormData();
if(inputFileCounter){
let i = 1;
const elementList = document.querySelectorAll('#feedback input[type="file"]');
elementList.forEach(function(element) {
const file = element.files[0];
formData.append('file_v_'+i, file);
i++;
});
}
formData.append('email', email);
formData.append('phone', phone);
formData.append('iblock_id', iblock_id);
formData.append('google_recaptcha', google_recaptcha);
formData.append('message', message);
let obj = this;
// отправляем через ajax
$.ajax({
url: arParamsFeedback['AJAX_FILE_PATH'],
type: "POST",
dataType : "json",
cache: false,
contentType: false,
processData: false,
data: formData,
success: function(data){
grecaptcha.reset();
/**
здесь получаем сообщение от бэкенда
**/
}
});
return false;
}
// берем и сравниваем значения captcha
function post_captcha($google_recaptcha) {
$configuration = Configuration::getInstance(); // объект конфигурации где хранятся ключи
$captcha = $configuration->get('google_recaptcha');
$result = false;
if($captcha){
$httpClient = new HttpClient(); // класс Битрикс для работы с http
$result = $httpClient->post( // отправляем на google запрос верификации
'https://www.google.com/recaptcha/api/siteverify',
array(
'secret' => $captcha['value']['secret'],
'response' => $google_recaptcha,
'remoteip' => $_SERVER['HTTP_X_REAL_IP']
)
);
}
return json_decode($result, true);
}
$result = [];
$google_recaptcha = htmlspecialchars($_REQUEST['google_recaptcha']);
if($google_recaptcha){ // google captcha
$res = post_captcha($google_recaptcha);
if (!$res['success'] || $res == false) {
$result['recaptca_success'] = false;
// Если капча не правильная
$result['msg'] = "RECAPTCHA_ERROR";
echo json_encode($result);
die();
} else {
// Если капча правильная
$result['recaptca_success'] = $res['success'];
$result['msg'] = "RECAPTCHA_SUCCESS";
}
}
Answer the question
In order to leave comments, you need to log in
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question