reCAPTCHA V2 with FormMail.cgi (Matt's Script Archive)

1.6k Views Asked by At

I was previously using reCAPTCHA V1 in conjunction with FormMail.cgi from Matt's Script Archive, with the following Perl function to validate the reCAPTCHA response:

sub check_captcha {

    my $ua = LWP::UserAgent->new();
    my $result=$ua->post(
        'http://www.google.com/recaptcha/api/verify',
        {
            privatekey => 'MyPrivateKey',
            remoteip   => $ENV{'REMOTE_ADDR'},
            challenge  => $Form{'recaptcha_challenge_field'},
            response   => $Form{'recaptcha_response_field'}
        }
    );
    if ( $result->is_success && $result->content =~ /^true/) {
        return;
    } else {
        &error('captcha_failed');
    }
}

reCAPTCHA V1 is shutting down at the end of March 2018 and so I need to move to reCAPTCHA V2, however, I'm having trouble validating the response in the CGI script.

Based on the server side documentation, here is what I've tried so far (without success):

sub check_captcha {

    my $ua = LWP::UserAgent->new();
    my $result=$ua->post(
        'https://www.google.com/recaptcha/api/siteverify',
        {
            secret     => 'MyPrivateKey',
            remoteip   => $ENV{'REMOTE_ADDR'},
            response   => $Form{'g-recaptcha-response'}
        }
    );
    if ( $result->is_success && $result->content =~ /"success": true/ ) {
        return;
    } else {
        &error('captcha_failed');
    }
}

The above always branches to the 'captcha_failed' error.

Thank you in advance for your time reading my question, I appreciate any assistance the community could offer.

Many thanks!

1

There are 1 best solutions below

2
On BEST ANSWER

I can't see any obvious problems with your code. But I wonder why you're implementing this yourself when Google::reCAPTCHA exists.

use Google::reCAPTCHA;

my $c = Google::reCAPTCHA->new( secret => 'MyPrivateKey' );

# Verifying the user's response 
my $success = $c->siteverify(
  response => $Form{'g-recaptcha-response'},
  remoteip => $ENV{'REMOTE_ADDR'},
);

if ( $success ) {
  # CAPTCHA was valid
}

And why are you using code from Matt's Script Archive?