Magento Captcha

Recaptcha in custom form for magento



phtml code

<?php

require_once(Mage::getBaseDir('lib') . DS . 'reCaptcha' . DS . 'recaptchalib.php');

$publickey = "6Lf28ucSAAAAAPThJUwU7tc_6M65deNtRKV4_POk";

# the response from reCAPTCHA
$resp = null;
# the error code from reCAPTCHA, if any
$error = null;
$cap_error = null;
$captcha_error = null;

?>
<script type="text/javascript">
var RecaptchaOptions = {
    theme:'blackglass'
};
</script>
<?php echo recaptcha_get_html($publickey, $cap_error); ?>
<div id="captchaStatus"></div>

bottom of the page add js

    jQuery('#contactForm').submit(function (ev) {

        var form = jQuery('#contactForm');

        var challengeField = form.find("input#recaptcha_challenge_field").val();
        var responseField = form.find("input#recaptcha_response_field").val();

        var html = jQuery.ajax({
            type:"POST",
            url:'<?php echo Mage::getBaseUrl(); ?>cms/page/captcha_ajax',
            data:"recaptcha_challenge_field=" + challengeField + "&recaptcha_response_field=" + responseField,
            async:false
        }).responseText;

        var error = false;
        if (html != "success") {
            error = true;
            form.find("#captchaStatus").html("The security code you entered did not match. Please try again.");
            Recaptcha.reload();
        } else {
            form.find("#captchaStatus").html("");
            Recaptcha.reload();
        }    
        if (error) {
            ev.preventDefault();
            return false;
        }
    });

ajax function for link in controller

 public function captcha_ajaxAction()
    {

        require_once(Mage::getBaseDir('lib') . DS . 'reCaptcha' . DS . 'recaptchalib.php');

        $privatekey = "6Lf28ucSAAAAAPx7Tf1ZwG_7omIuFLS4bDDuG6R_";

        $resp = recaptcha_check_answer($privatekey,
            $_SERVER["REMOTE_ADDR"],
            $_POST["recaptcha_challenge_field"],
            $_POST["recaptcha_response_field"]);
        if ($resp->is_valid) {
            echo "success";
        } else {
            die("The reCAPTCHA wasn't entered correctly. Go back and try it again." .
                "(reCAPTCHA said: " . $resp->error . ")");
        }
    }