Last active
May 5, 2017 21:50
-
-
Save hiendnguyen/3aff513bab1bdb274cab82fa34d27e9d to your computer and use it in GitHub Desktop.
Add reCAPTCHA to WooCommerce Signup Form
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
/* wooc_reCAPTCHA */ | |
// Add reCAPTCHA to WooCommerce Signup Form | |
function wooc_reCAPTCHA(){ | |
?> | |
<script src='https://www.google.com/recaptcha/api.js' defer'></script> | |
<label>ARE YOU HUMAN?</label> | |
<div class="g-recaptcha" data-sitekey="[reCAPTCHA Site Key]"></div> | |
<?php | |
} | |
add_action( 'woocommerce_register_form', 'wooc_reCAPTCHA', 19); | |
// Validate reCAPTCHA input before creating account | |
function wooc_validate_re_captcha_field( $username, $email, $wpErrors ){ | |
$remoteIP = $_SERVER['REMOTE_ADDR']; | |
$recaptchaResponse = $_POST['g-recaptcha-response']; | |
$response = wp_remote_post( 'https://www.google.com/recaptcha/api/siteverify', [ | |
'body' => [ | |
'secret' => '[reCAPTCHA Secret Key]', | |
'response' => $recaptchaResponse, | |
'remoteip' => $remoteIP | |
] | |
] ); | |
$response_code = wp_remote_retrieve_response_code( $response ); | |
$response_body = wp_remote_retrieve_body( $response ); | |
if ( $response_code == 200 ){ | |
$result = json_decode( $response_body, true ); | |
if ( ! $result['success'] ){ | |
switch ( $result['error-codes'] ){ | |
case 'missing-input-secret': | |
case 'invalid-input-secret': | |
$wpErrors->add( 'recaptcha', __( 'Invalid reCAPTCHA secret key.', 'woocommerce' ) ); | |
break; | |
case 'missing-input-response' : | |
case 'invalid-input-response' : | |
$wpErrors->add( 'recaptcha', __( 'Please check the box to prove that you are not a robot.', 'woocommerce' ) ); | |
break; | |
default: | |
$wpErrors->add( 'recaptcha', __( 'Something went wrong validating the reCAPTCHA.', 'woocommerce' ) ); | |
break; | |
} | |
} | |
} | |
else { | |
$wpErrors->add( 'recaptcha_error', __( 'Unable to reach the reCAPTCHA server.', 'woocommerce' ) ); | |
} | |
} | |
add_action( 'woocommerce_register_post', 'wooc_validate_re_captcha_field', 9, 3 ); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment