Hướng dẫn tự code chức năng đăng nhập wordpress với xác thực google recaptcha

Để chèn thêm xác thực Google reCaptcha vào form đăng nhập wordpress bạn chèn đoạn code sau vào file functions.php của theme đang kích hoạt hoặc tải plugin(link ở cuối bài viết) về cài đặt như bình thường sau đó đăng kí Google reCaptcha rồi để tạo key cài đặt vào plugin thông qua giao diện admin thì sẽ nhận được kết quả như sau:

Xem thêm hướng dẫn Đăng kí Google reCaptcha KEY từ Google

WordPress login form
Woocommerce login form

Bên dưới là mã code đầy đủ của plugin

<?php

/*
Plugin Name: Google's reCAPTCHA to WordPress Login Form
Plugin URI: https://sanwp.com
Description: Add Google's reCAPTCHA to WordPress Login Form
Version: 1.0.0
Author: binmaocom
Author URI: https://sanwp.com
License: GPL2
*/

class WP_Google_reCAPTCHA_Login_Form {

	/** @type string private key|public key */
	private $public_key, $private_key;

	/** class constructor */
	public function __construct() {
		$this->public_key  = get_option('google_recaptcha_site_key', '6LeZg30aAAAAAFYsiP5j3PGJbHzeKnqoImvmfPV2');
		$this->private_key = get_option('google_recaptcha_secret_key', '6LeZg30aAAAAAD0K4mExjXsKs0XX99eXpR_oftcQ');

		// adds the captcha to the login form
		add_action( 'login_form', array( $this, 'captcha_display' ) );
		add_action( 'woocommerce_login_form_start', array( $this, 'captcha_display' ) );

		// authenticate the captcha answer
		add_action( 'wp_authenticate_user', array( $this, 'validate_captcha_field' ), 10, 2 );
		add_action( 'admin_init', array($this, 'recaptcha_register_settings') );
		add_action( 'plugin_action_links_' . plugin_basename( __FILE__ ), array($this, 'add_action_links' ) );
	}

	function add_action_links( $links ) {
		$links = array_merge( 
			array(
			'<a target="blank" href="'.admin_url( '/options-general.php#google-recaptcha-container' ) .'">'.__('Cấu hình','g-recaptcha').'</a>',
		), $links );
		return $links;
	}

	/** Output the reCAPTCHA form field. */
	public function captcha_display() {
		?>
		<script type="text/javascript">
			var verifyCallback = function(response) {
		        console.log(response);
	      	};
	      	var onloadCallback = function() {
	        	grecaptcha.render('google_captcha_html_element', {
	          		'sitekey' : '<?php echo $this->public_key; ?>'
	        	});
	      	};
	    </script>
		<script src="https://www.google.com/recaptcha/api.js?onload=onloadCallback&render=explicit"
		    async defer>
		</script>
		<div style="margin-bottom: 12px;overflow: hidden;" id="google_captcha_html_element" class="g-recaptcha"></div>
	<?php
	}

	/**
	 * Verify the captcha answer
	 *
	 * @param $user string login username
	 * @param $password string login password
	 *
	 * @return WP_Error|WP_user
	 */
	public function validate_captcha_field($user, $password) {
		if ( ! isset( $_POST['g-recaptcha-response'] ) || empty( $_POST['g-recaptcha-response'] ) ) {
			return new WP_Error( 'empty_captcha', __('CAPTCHA should not be empty', 'g-recaptcha'));
		}
		$recaptcha_response = $this->recaptcha_response();
		if( is_wp_error($recaptcha_response) ) {
			return $recaptcha_response;
		}
		return $user;
	}

	/**
	 * Get the reCAPTCHA API response.
	 *
	 * @return string
	 */
	public function recaptcha_response() {

		// reCAPTCHA response post data
		$response  = isset($_POST['g-recaptcha-response']) ? esc_attr($_POST['g-recaptcha-response']) : '';
		$remote_ip = $_SERVER["REMOTE_ADDR"];
		$post_body = array(
			'secret' => $this->private_key,
			'remoteip'   => $remote_ip,
			'response'   => $response
		);
		return $this->recaptcha_post_request( $post_body );
	}

	/**
	 * Send HTTP POST request and return the response.
	 *
	 * @param $post_body array HTTP POST body
	 *
	 * @return bool
	 */
	public function recaptcha_post_request( $post_body ) {
		$args = array( 'body' => $post_body );
		// make a POST request to the Google reCaptcha Server
		$request = wp_remote_post( 'https://www.google.com/recaptcha/api/siteverify', $args );
		// get the request response body
		$response_body = wp_remote_retrieve_body( $request );
		/**
		 * explode the response body and use the request_status
		 * @see https://developers.google.com/recaptcha/docs/verify
		 */
		$response_ob = json_decode($response_body, true);
		// var_dump($response_ob);exit;
		if($response_ob['success'] == false){
			$list_errors = array(
				'missing-input-secret'	=> __('The secret parameter is missing.', 'g-recaptcha'),
				'invalid-input-secret'	=> __('The secret parameter is invalid or malformed.', 'g-recaptcha'),
				'missing-input-response'	=> __('The response parameter is missing.', 'g-recaptcha'),
				'invalid-input-response'	=> __('The response parameter is invalid or malformed.', 'g-recaptcha'),
				'bad-request'	=> __('The request is invalid or malformed.', 'g-recaptcha'),
				'timeout-or-duplicate'	=> __('The response is no longer valid: either is too old or has been used previously', 'g-recaptcha')
			);
			return new WP_Error( 'invalid_captcha', __('[reCaptcha]', 'g-recaptcha').' ' . $list_errors[$response_ob['error-codes'][0]] );
		}
		return true;
	}
	
	function recaptcha_register_settings() 
	{
	    register_setting( 'general', 'google_recaptcha_key', 'esc_attr' );
	    add_settings_field(
	        'google_recaptcha_key',
	        '<label for="google_recaptcha_key">' . __( 'How to get the Key for Google reCaptcha' , 'google_recaptcha_site_key' ) . '</label>',
	        array($this, 'google_recaptcha_key_html'),
	        'general'
	    );
	    register_setting( 'general', 'google_recaptcha_site_key', 'esc_attr' );
	    add_settings_field(
	        'google_recaptcha_site_key',
	        '<label for="google_recaptcha_site_key">' . __( 'Google reCaptcha SITE KEY' , 'google_recaptcha_site_key' ) . '</label>',
	        array($this, 'google_recaptcha_site_key_html'),
	        'general'
	    );
	    register_setting( 'general', 'google_recaptcha_secret_key', 'esc_attr' );
	    add_settings_field(
	        'google_recaptcha_secret_key',
	        '<label for="google_recaptcha_secret_key">' . __( 'Google reCaptcha SECRET KEY' , 'google_recaptcha_secret_key' ) . '</label>',
	        array($this, 'google_recaptcha_secret_key_html'),
	        'general'
	    );
	}

	/* 
	 * Print settings field content 
	 */
	function google_recaptcha_key_html() 
	{
		echo '<div id="google-recaptcha-container"><p style="margin-bottom: 10px;">'.__('Goto Google service to get the key for your site <a target="blank" href="https://www.google.com/recaptcha">here</a>. <br/>When you are done you can see the Key same here', 'google_recaptcha_secret_key').'</p>';
	    echo '<img src="'.plugin_dir_url(__FILE__).'google-recaptcha.png" /></div>';
	}
	function google_recaptcha_site_key_html() 
	{
	    $google_recaptcha_site_key = ( get_option( 'google_recaptcha_site_key' ) );
	    echo '<input type="password" id="google_recaptcha_site_key" name="google_recaptcha_site_key" value="'.$google_recaptcha_site_key.'" />';
	}
	function google_recaptcha_secret_key_html() 
	{
	    $google_recaptcha_secret_key = ( get_option( 'google_recaptcha_secret_key' ) );
	    echo '<input type="password" id="google_recaptcha_secret_key" name="google_recaptcha_secret_key" value="'.$google_recaptcha_secret_key.'" />';
	}

}

new WP_Google_reCAPTCHA_Login_Form();


function bi_wooc_extra_register_fields() {?>
       <p class="form-row form-row-wide">
       <label for="reg_billing_phone"><?php _e( 'Phone', 'woocommerce' ); ?></label>
       <input type="text" class="input-text" name="billing_phone" id="reg_billing_phone" value="<?php esc_attr_e( $_POST['billing_phone'] ); ?>" />
       </p>
       <p class="form-row form-row-first">
       <label for="reg_billing_first_name"><?php _e( 'First name', 'woocommerce' ); ?><span class="required">*</span></label>
       <input type="text" class="input-text" name="billing_first_name" id="reg_billing_first_name" value="<?php if ( ! empty( $_POST['billing_first_name'] ) ) esc_attr_e( $_POST['billing_first_name'] ); ?>" />
       </p>
       <p class="form-row form-row-last">
       <label for="reg_billing_last_name"><?php _e( 'Last name', 'woocommerce' ); ?><span class="required">*</span></label>
       <input type="text" class="input-text" name="billing_last_name" id="reg_billing_last_name" value="<?php if ( ! empty( $_POST['billing_last_name'] ) ) esc_attr_e( $_POST['billing_last_name'] ); ?>" />
       </p>
       <div class="clear"></div>
       <?php
 }

Tải plugin tại đây https://drive.google.com/file/d/1iSNcQEG68RDmfpETshhH_i_ntd7uxC3O/view?usp=sharing

Bài viết liên quan

Trả lời

Email của bạn sẽ không được hiển thị công khai. Các trường bắt buộc được đánh dấu *

Đồng ý với chính sách thu thập dữ liệu của chúng tôi tại đây