Why is google reCAPTCHA not firing correctly?

  • 0
    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 CMS Bitrix, but almost pure PHP is used in the reCAPTCHA processing on the server.

    What could be the reason for the error?

    $ captcha - PHP array that stores public and private keys
    I substitute the public key in the button button in the data-sitekey attribute
    i get it from PHP config object where keys are stored

    HTML code of the form (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">&gt;&gt;</div></button>


    The handler fires on the onSubmit event.

    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;    
        }


    Server handler

    // берем и сравниваем значения 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";
        }
    }


    What could be the reason for the message, frequent requests?
    JavaScript Anonymous, May 10, 2019

  • 0 Answers
Your Answer
To place the code, please use CodePen or similar tool. Thanks you!