Saltar al contenido

Cómo validar la reCaptcha de Google

Solución:

Deberías probar este código: he estado usando esto en mi sitio.

<script>
window.onload = function() {
  var recaptcha = document.forms["contactForm"]["g-recaptcha-response"];
  recaptcha.required = true;
  recaptcha.oninvalid = function(e) {

    alert("Please complete the captcha");
   }
}
</script> 

En mi opinión, la solución JavaScript aceptada anterior definitivamente NO es el camino a seguir. Cualquier bot que no use JS (que es la mayoría de ellos) simplemente pasará por alto su validación y obtendrá todo el spam que está tratando de bloquear. Siempre siempre siempre validar en el servidor. La validación de JS es solo un primer paso de UX.

De todos modos, hay múltiples soluciones, pero esto es lo que funcionó para mí en Magento 1.9 después de muchas horas de investigación. Esto originalmente se basó en la respuesta de Mike anterior, pero cambia file_get_contents por cURL ya que la función anterior generalmente le dará errores de contenedor http dependiendo de la configuración de su servidor.

Cree su propio módulo creando una carpeta / aplicación / código / local / YourVendorName / ValidateCaptcha /

En su nueva carpeta ValidateCaptcha, agregue una carpeta Modelo con un archivo Customer.php. Esto se utilizará para anular el archivo principal Customer.php proporcionado por Magento.

Copie y pegue este código:

<?php
class YourVendorName_ValidateCaptcha_Model_Customer extends Mage_Customer_Model_Customer {

    /**
     * Validate customer attribute values.
     *
     * @return bool
     */
    public function validate()
    {
        // This section is from the core file
        $errors = array();
        if (!Zend_Validate::is( trim($this->getFirstname()) , 'NotEmpty')) {
            $errors[] = Mage::helper('customer')->__('The first name cannot be empty.');
        }

        if (!Zend_Validate::is( trim($this->getLastname()) , 'NotEmpty')) {
            $errors[] = Mage::helper('customer')->__('The last name cannot be empty.');
        }

        if (!Zend_Validate::is($this->getEmail(), 'EmailAddress')) {
            $errors[] = Mage::helper('customer')->__('Invalid email address "%s".', $this->getEmail());
        }

        $password = $this->getPassword();
        if (!$this->getId() && !Zend_Validate::is($password , 'NotEmpty')) {
            $errors[] = Mage::helper('customer')->__('The password cannot be empty.');
        }
        if (strlen($password) && !Zend_Validate::is($password, 'StringLength', array(6))) {
            $errors[] = Mage::helper('customer')->__('The minimum password length is %s', 6);
        }
        $confirmation = $this->getPasswordConfirmation();
        if ($password != $confirmation) {
            $errors[] = Mage::helper('customer')->__('Please make sure your passwords match.');
        }

        $entityType = Mage::getSingleton('eav/config')->getEntityType('customer');
        $attribute = Mage::getModel('customer/attribute')->loadByCode($entityType, 'dob');
        if ($attribute->getIsRequired() && '' == trim($this->getDob())) {
            $errors[] = Mage::helper('customer')->__('The Date of Birth is required.');
        }
        $attribute = Mage::getModel('customer/attribute')->loadByCode($entityType, 'taxvat');
        if ($attribute->getIsRequired() && '' == trim($this->getTaxvat())) {
            $errors[] = Mage::helper('customer')->__('The TAX/VAT number is required.');
        }
        $attribute = Mage::getModel('customer/attribute')->loadByCode($entityType, 'gender');
        if ($attribute->getIsRequired() && '' == trim($this->getGender())) {
            $errors[] = Mage::helper('customer')->__('Gender is required.');
        }

        // additional reCAPTCHA validation
        // this should actually be in it's own function, but I've added 
        // it here for simplicity

        // Magento uses this method for a few different requests, so make
        // sure it's limited only to the 'createpost' action
        $action = Mage::app()->getRequest()->getActionName();
        if ( $action == 'createpost' ) { // restrict to the registration page only
            $captcha = Mage::app()->getRequest()->getPost('g-recaptcha-response', 1);
            if ( $captcha == '' ) {
                // if the field is empty, add an error which will be
                // displayed at the top of the page
                $errors[] = Mage::helper('customer')->__('Please check the reCAPTCHA field to continue.');
            } else {
                $secret="your-secret-key-goes-here";
                $url="https://www.google.com/recaptcha/api/siteverify?secret=" . $secret . '&response=" . $captcha . "&remoteip=' . $_SERVER["REMOTE_ADDR"];

                $ch = curl_init();
                // if you're testing this locally, you'll likely need to 
                // add your own CURLOPT_CAINFO parameter or you'll get
                // SSL errors
                curl_setopt( $ch, CURLOPT_URL, $url );
                curl_setopt( $ch, CURLOPT_RETURNTRANSFER, 1);
                $response = curl_exec( $ch );

                $result = json_decode( $response, true );
                if ( trim( $result['success'] ) != true ) {
                    // Add reCAPTCHA error
                    // This will be shown at the top of the registration page
                    $errors[] = Mage::helper('customer')->__('reCAPTCHA unable to verify.');
                }
            }
        }

        // now return the errors with your reCAPTCHA validation as well
        if (empty($errors)) {
            return true;
        }
        return $errors;
    }


}

Ahora agregue una carpeta etc a su módulo y cree un config.xml con lo siguiente:

<?xml version="1.0"?>
<config>
    <modules>
        <YourVendorName_ValidateCaptcha>
            <version>1.0</version>
        </YourVendorName_ValidateCaptcha>
    </modules>

    <global>
       <models>
          <customer>
              <rewrite>
                  <customer>YourVendorName_ValidateCaptcha_Model_Customer</customer>
              </rewrite>
          </customer>
       </models>
    </global>
</config>

A continuación, deberá agregar el JS al encabezado de su tema. En app / design / frontend / default / YOURTHEME / template / page / html / head.phtml agregue esto justo al final. Si no tiene este archivo, cópielo de los archivos base. Sin embargo, no sobrescriba los archivos base. ¡Haz siempre el tuyo!

<?php
/* reCAPTCHA */
if ( strpos( Mage::helper('core/url')->getCurrentUrl(), 'account/create') != false ) { ?>   
<script src="https://www.google.com/recaptcha/api.js" async defer></script>
<?php } ?>

Ahora en app / design / frontend / default / YOURTHEME / template / persistent / customer / form / register.phtml agregue esto justo antes del div button-set cerca de la parte inferior:

    <div data-sitekey="your-site-key-goes-here"></div>
    <span><?php echo $this->__('Please Fill Recaptcha To Continue'); ?></span>

¡Casi termino! Ahora simplemente registre su nuevo módulo creando una aplicación / etc / modules / YourVendorName / ValidateCaptcha.xml con lo siguiente:

<?xml version="1.0"?>
<config>
    <modules>
        <YourVendorName_ValidateCaptcha>
            <active>true</active>
            <codePool>local</codePool>
        </YourVendorName_ValidateCaptcha>
    </modules>
</config>

Reemplace YourVendorName en todas partes con lo que desee. Tu estructura final debería ser algo como:

- app
  - code
    - local
      - YourVendorName
        - ValidateCaptcha
          - etc
            config.xml
          - Model
            Customer.php
- design
  - frontend
    - default
      - YOURTHEME
        - template
          - customer
            - form
              register.phtml
          - page
            - html
              head.phtml
          - persistent
            - customer
              - form
                register.phtml
- etc
  - modules
    YourVendorName_ValidateCaptcha.xml

Este script se utiliza para la validación de google reCaptcha como una validación predeterminada de magento. por favor úselo.

<form name="freeeventForm">
    <div></div>
    <input type="hidden">
</form>
        <script src="https://www.google.com/recaptcha/api.js?onload=CaptchaCallback&render=explicit" async defer></script>
    <script type="text/javascript">
        //< ![CDATA[
            var CaptchaCallback = function() {  
            grecaptcha.render('RecaptchaField', {'sitekey' : '6LeuiDwUAAAAALByt-xxxxxxxxxxx-xUsZHFkeEP'});
        };
        var customForm = new VarienForm('freeeventForm');
        Validation.add('validate-reCAPTCHA','reCAPTCHA is mandatory',function(){
            var response = grecaptcha.getResponse();
            if (response.length === 0) {
                    return false;
            }
            return true;
    });
        //]]>
    </script>
¡Haz clic para puntuar esta entrada!
(Votos: 0 Promedio: 0)



Utiliza Nuestro Buscador

Deja una respuesta

Tu dirección de correo electrónico no será publicada. Los campos obligatorios están marcados con *