没有与WordPress的CAPTCHA reCAPTCHA集成

tech2023-01-10  118

A few weeks ago, the Google security team announced a new version of the popular reCAPTCHA system used by millions of websites in combating spam.

几周前, Google安全团队宣布了一种流行的reCAPTCHA系统的新版本,该系统已被数百万个网站用于反垃圾邮件。

For years, reCAPTCHA has prompted users to confirm they aren’t robots by asking them to read distorted text to be entered into a box, like this:

多年以来,reCAPTCHA一直要求用户阅读要输入到框中的变形文本,从而提示用户确认自己不是机器人,例如:

A lot of people griped and faulted the old reCAPTCHA system for many reasons. The distorted text it produces is difficult to recognize and bots get past the test better than humans do.

许多人出于各种原因而抓紧旧式reCAPTCHA系统并对其进行了故障。 它产生的扭曲文本很难识别,并且机器人比人类更能通过测试。

The new CAPTCHA is easy and convenient. All you need to do is click on a checkbox and you’re done. It’s also pretty effective in combating spam.

新的CAPTCHA既简单又方便。 您所需要做的就是单击一个复选框,然后完成。 在打击垃圾邮件方面也非常有效。

Previously on SitePoint, we wrote a series on integrating the old reCAPTCHA to the following WordPress forms:

以前在SitePoint上,我们编写了一系列有关将旧的reCAPTCHA集成到以下WordPress表单的系列:

login

登录

registration

注册

comment

评论

In this article, we will learn how to integrate the new No CAPTCHA reCAPTCHA with a custom form and WordPress.

在本文中,我们将学习如何将新的No CAPTCHA reCAPTCHA与自定义表单和WordPress集成在一起。

reCAPTCHA表单集成 (reCAPTCHA Form Integration)

Let’s go over the process on how to integrate reCAPTCHA with a web form.

让我们研究一下如何将reCAPTCHA与Web表单集成。

First off, head over to reCAPTCHA to grab your site and secret key.

首先,前往reCAPTCHA获取您的网站和密钥。

显示验证码 (Displaying the CAPTCHA)

Include the following to the header section of the web page: <script src="https://www.google.com/recaptcha/api.js" async defer></script>.

在网页的标题部分添加以下内容: <script src="https://www.google.com/recaptcha/api.js" async defer></script> 。

Add <div class="g-recaptcha" data-sitekey="your_site_key"></div> to wherever you want to output the CAPTCHA where your_site_key is your domain site/public key.

将<div class="g-recaptcha" data-sitekey="your_site_key"></div>到要输出CAPTCHA的任何位置,其中your_site_key是您的域站点/公共密钥。

More information on configuring the display of the CAPTCHA widget can be found here.

在此处可以找到有关配置CAPTCHA小部件的显示的更多信息。

验证用户的响应 (Verifying the User’s Response)

To verify the user response (check if the user passed or failed the CAPTCHA test), send a GET request to the URL below using either cURL, Guzzle, WordPress HTTP API or any HTTP client.

要验证用户响应(检查用户是否通过了验证码测试),请使用cURL , Guzzle , WordPress HTTP API或任何HTTP客户端将GET请求发送到下面的URL。

https://www.google.com/recaptcha/api/siteverify?secret=your_secret&response=response_string&remoteip=user_ip_address

Where:

哪里:

– your_secret: Secret (private) key. – response_string: The user response token (retrieved via PHP by $_POST['g-recaptcha-response']) ). – user_ip_address: The user IP address albeit optional. ($_SERVER["REMOTE_ADDR"]).

– your_secret :秘密(专用)密钥。 – response_string :用户响应令牌(通过PHP通过$_POST['g-recaptcha-response'])检索)。 – user_ip_address :用户IP地址,尽管是可选的。 ( $_SERVER["REMOTE_ADDR"] )。

If the request was successfully sent, the response will be a JSON object similar to the one below.

如果请求已成功发送,则响应将是与以下对象相似的JSON对象。

{ "success": true|false }

Decode the response using json_decode() and grab success property $response['success'] which returns true if the user passes the test, or false otherwise.

使用json_decode()解码响应,并获取成功属性$response['success'] ,如果用户通过测试,则返回true,否则返回false。

More information on verifying the user response can be found here.

在此处可以找到有关验证用户响应的更多信息。

reCAPTCHA WordPress集成 (reCAPTCHA WordPress Integration)

Having learned how the new No CAPTCHA reCAPTCHA can be integrated with a form, let’s also see how it can be integrated with WordPress.

了解了如何将新的No CAPTCHA reCAPTCHA与表单集成后,让我们看看如何将其与WordPress集成。

The first step is to include the plugin file header:

第一步是包括插件文件头:

<?php /* Plugin Name: No CAPTCHA reCAPTCHA Plugin URI: https://www.sitepoint.com Description: Protect WordPress login, registration and comment form from spam with the new No CAPTCHA reCAPTCHA Version: 1.0 Author: Agbonghama Collins Author URI: http://w3guy.com License: GPL2 */

Enqueue the reCAPTCHA script to WordPress header section.

将reCAPTCHA脚本排队到WordPress标头部分。

// add the header script to login/registration page header add_action( 'login_enqueue_scripts', 'header_script' ); // add CAPTCHA header script to WordPress header add_action( 'wp_head', 'header_script' ); /** reCAPTCHA header script */ function header_script() { echo '<script src="https://www.google.com/recaptcha/api.js" async defer></script>'; }

Next we use display_captcha() and the captcha_verification() wrapper function for displaying the CAPTCHA widget and verifying the user response.

接下来,我们使用display_captcha()和captcha_verification()包装函数来显示CAPTCHA小部件并验证用户响应。

Note: change *your_site_key* and *your_secret* in the code below to your site (public) key and secret (private) key respectively.

注意:将下面代码中的* your_site_key *和* your_secret *分别更改为您的站点(公共)密钥和秘密(私有)密钥。

/** Output the reCAPTCHA form field. */ function display_captcha() { echo '<div class="g-recaptcha" data-sitekey="your_site_key"></div>'; } /** * Send a GET request to verify CAPTCHA challenge * * @return bool */ function captcha_verification() { $response = isset( $_POST['g-recaptcha-response'] ) ? esc_attr( $_POST['g-recaptcha-response'] ) : ''; $remote_ip = $_SERVER["REMOTE_ADDR"]; // make a GET request to the Google reCAPTCHA Server $request = wp_remote_get( 'https://www.google.com/recaptcha/api/siteverify?secret=your_secret&response=' . $response . '&remoteip=' . $remote_ip ); // get the request response body $response_body = wp_remote_retrieve_body( $request ); $result = json_decode( $response_body, true ); return $result['success']; }

We’ve now defined the base functionality of the plugin, up next is integrating the CAPTCHA with login, registration and comment forms.

现在,我们已经定义了插件的基本功能,接下来是将CAPTCHA与登录,注册和评论表单集成在一起。

登录表单 (Login Form)

Include the CAPTCHA widget to the login form by hooking the function display_captcha() to the login_form Action.

通过将函数display_captcha()挂接到login_form操作,将CAPTCHA小部件包括到登录表单中。

// adds the CAPTCHA to the login form add_action( 'login_form', array( __CLASS__, 'display_captcha' ) );

The validate_login_captcha() function will validate and ensure the CAPTCHA checkbox isn’t left unchecked and that the test is passed.

validate_login_captcha()函数将验证并确保未选中CAPTCHA复选框,并且测试已通过。

// authenticate the CAPTCHA answer add_action( 'wp_authenticate_user', 'validate_captcha', 10, 2 ); /** * Verify the CAPTCHA answer * * @param $user string login username * @param $password string login password * * @return WP_Error|WP_user */ function validate_captcha( $user, $password ) { if ( isset( $_POST['g-recaptcha-response'] ) && !captcha_verification() ) { return new WP_Error( 'empty_captcha', '<strong>ERROR</strong>: Please retry CAPTCHA' ); } return $user; }

报名表格 (Registration Form)

Include the CAPTCHA widget to the registration form by hooking the function display_captcha() to the register_form Action.

通过将函数display_captcha()挂接到register_form Action,将CAPTCHA小部件包括到注册表单中。

// adds the CAPTCHA to the registration form add_action( 'register_form', 'display_captcha' );

Validate the CAPTCHA test in the registration form with the validate_captcha_registration_field() function hooked to registration_errors.

使用挂钩到registration_errors的validate_captcha_registration_field()函数来validate_captcha_registration_field()注册表单中的CAPTCHA测试。

// authenticate the CAPTCHA answer add_action( 'registration_errors', 'validate_captcha_registration_field', 10, 3 ); /** * Verify the captcha answer * * @param $user string login username * @param $password string login password * * @return WP_Error|WP_user */ function validate_captcha_registration_field( $errors, $sanitized_user_login, $user_email ) { if ( isset( $_POST['g-recaptcha-response'] ) && !captcha_verification() ) { $errors->add( 'failed_verification', '<strong>ERROR</strong>: Please retry CAPTCHA' ); } return $errors; }

评论表格 (Comment Form)

First, create a global variable that will hold the status of the CAPTCHA test. That is, when a user fails the challenge, it is set to ‘failed’ and empty otherwise.

首先,创建一个全局变量,该变量将保持CAPTCHA测试的状态。 也就是说,当用户未通过挑战时,它将设置为“失败”,否则设置为空。

global $captcha_error;

Include the CAPTCHA widget to the comment form by hooking the display_captcha() function to the comment_form Action.

通过将display_captcha()函数挂接到comment_form操作上,将CAPTCHA小部件包括到注释表单中。

// add the CAPTCHA to the comment form add_action( 'comment_form', 'display_captcha' );

The filter preprocess_comment calls the validate_captcha_comment_field() function to ensure the CAPTCHA field isn’t left empty and also that the answer is correct.

过滤器preprocess_comment调用validate_captcha_comment_field()函数,以确保CAPTCHA字段不为空,并且答案正确。

// authenticate the captcha answer add_filter( 'preprocess_comment', 'validate_captcha_comment_field'); /** * Verify the captcha answer * * @param $commentdata object comment object * * @return object */ function validate_captcha_comment_field( $commentdata ) { global $captcha_error; if ( isset( $_POST['g-recaptcha-response'] ) && ! (captcha_verification()) ) { $captcha_error = 'failed'; } return $commentdata; }

The filter comment_post_redirect calls redirect_fail_captcha_comment() to delete comments detected as spam and also adds some query parameters to the comment redirection URL.

过滤器comment_post_redirect调用redirect_fail_captcha_comment()删除检测为垃圾邮件的注释,并向注释重定向URL添加一些查询参数。

add_filter( 'comment_post_redirect', 'redirect_fail_captcha_comment', 10, 2 ); /** * Delete spam comments * * Add query string to the comment redirect location * * @param $location string location to redirect to after comment * @param $comment object comment object * * @return string */ function redirect_fail_captcha_comment( $location, $comment ) { global $captcha_error; if ( ! empty( $captcha_error ) ) { // delete the failed captcha comment wp_delete_comment( absint( $comment->comment_ID ) ); // add failed query string for @parent::display_captcha to display error message $location = add_query_arg( 'captcha', 'failed', $location ); } return $location; }

Voila! We’re done coding the plugin.

瞧! 我们已经完成了插件的编码。

摘要 (Summary)

In this article, we learned how to protect web forms against spam using the new No CAPTCHA reCAPTCHA and finally, integrated it with the WordPress login, registration and comment forms.

在本文中,我们学习了如何使用新的No CAPTCHA reCAPTCHA保护Web表单免受垃圾邮件的侵扰,最后将其与WordPress登录,注册和评论表单集成。

If you’d like to integrate the new reCAPTCHA widget with your WordPress powered site, the plugin is available at the WordPress plugin directory.

如果您想将新的reCAPTCHA小部件与WordPress支持的网站集成在一起,则可在WordPress插件目录中使用该插件 。

Until I come your way again, happy coding!

直到我再次走上前,祝您编程愉快!

翻译自: https://www.sitepoint.com/no-captcha-integration-wordpress/

最新回复(0)