how to add recaptcha to woocommerce register php

Solutions on MaxInterview for how to add recaptcha to woocommerce register php by the best coders in the world

showing results for - "how to add recaptcha to woocommerce register php"
Angelo
06 Nov 2019
1// Add field into the registration form
2
3    function nada_woocommerce_edit_registration_form() {
4            ?>
5            <p id="recaptcha" class="g-recaptcha" data-sitekey="##your-google-captcha-key##"></p>
6            <?php
7        }
8        add_action( 'woocommerce_register_form', 'nada_woocommerce_edit_registration_form', 15 );
9
10    /**
11     * Validate Woocommerce Registration form fields
12     */
13
14    function nada_validate_extra_register_fields( $errors, $username, $email ) {
15        if ( empty( $_POST['g-recaptcha-response'] ) ) {
16                $errors->add( 'captcha-error', wp_kses_post( '<strong>Error</strong>: Captcha is missing.', 'nada' ) );
17        }
18        return $errors;
19    }
20    add_filter( 'woocommerce_registration_errors', 'nada_validate_extra_register_fields', 10, 3 );
Arda
12 Jan 2018
1function wooc_validate_re_captcha_field( $username, $email, $wpErrors )
2{
3    $remoteIP = $_SERVER['REMOTE_ADDR'];
4    $recaptchaResponse = $_POST['g-recaptcha-response'];
5
6    $response = wp_remote_post( 'https://www.google.com/recaptcha/api/siteverify', [
7        'body' => [
8            'secret'   => 'PRIVATE KEY HERE !!!',
9            'response' => $recaptchaResponse,
10            'remoteip' => $remoteIP
11        ]
12    ] );
13
14    $response_code = wp_remote_retrieve_response_code( $response );
15    $response_body = wp_remote_retrieve_body( $response );
16
17    if ( $response_code == 200 )
18    {
19        $result = json_decode( $response_body, true );
20
21        if ( ! $result['success'] )
22        {
23            switch ( $result['error-codes'] )
24            {
25                case 'missing-input-secret':
26                case 'invalid-input-secret':
27                    $wpErrors->add( 'recaptcha', __( '<strong>ERROR</strong>: Invalid reCAPTCHA secret key.', 'woocommerce' ) );
28                    break;
29
30                case 'missing-input-response' :
31                case 'invalid-input-response' :
32                    $wpErrors->add( 'recaptcha', __( '<strong>ERROR</strong>: Please check the box to prove that you are not a robot.', 'woocommerce' ) );
33                    break;
34
35                default:
36                    $wpErrors->add( 'recaptcha', __( '<strong>ERROR</strong>: Something went wront validating the reCAPTCHA.', 'woocommerce' ) );
37                    break;
38            }
39        }
40    }
41    else
42    {
43        $wpErrors->add( 'recaptcha_error', __( '<strong>Error</strong>: Unable to reach the reCAPTCHA server.', 'woocommerce' ) );
44    }
45}
46add_action( 'woocommerce_register_post', 'wooc_validate_re_captcha_field', 10, 3 );