WordPress in the implementation of SMS authentication registration login method - front-end + back-end

Cell phone registration is very popular in China, basically a commercial type of website, are required to use a cell phone number to register to log in, or provide a cell phone number to register to log in the option. We will not talk about whether this behavior violates personal privacy. WordPress DevelopmentThe method of SMS registration and login. Cell phone SMS verification registration and login implementation is actually very simple, have not done friends may feel the need to deal with too much logic, have not started to try to retreat. In fact, the integration of the registration verification process, the most troublesome is the docking of the SMS interface, the more commonly used SMS interface is okay, the official have provided the SDK and code for reference, you can also use the following introduction of the SMS send library. If you encounter a non-mainstream interface is depressing, interface documentation is simple as hell, interface implementation is also very bad, not enough patience to debug the past. Let's cut the crap and get to the point.

First is the authentication SMS service interface

SMS interface is necessary, there is no interface to talk about the technical implementation, as for the use of which interface. Depends on the choice of more important factors, the stability of the interface, flexibility, price, etc. are to be considered. The following table is “Probably the smartest and most elegant php SMS sending library available PhpSms” A few commonly used SMS service providers in the country organized for your reference.

service providerTemplate SMSContent SMSCAPTCHA, a type of challenge-response test (computing)minimum consumptionMinimum consumer unit price
Luosimao×¥850 (10,000)¥0.085/strip
cloud chip network×¥55 (1,000)¥0.055/bar
Junlian-Cloud Communication×Charge ¥500¥0.055/bar
SUBMAIL××¥100 (1,000)¥0.100/bar
cloud nine×-¥0.050/strip
syndicated data×-¥0.035/bar
aliens×-¥0.045/strip
SendCloud×-¥0.048/bar

Send and verify SMS backend code implementation

Before sending SMS, we must generate a random verification code, send the code through SMS at the same time, but also bar code saved to the database for verification when compared to determine whether the code is correct. The following is the simple logic of sending the code when I do a website registration and login, you can refer to it.

The following code needs to pay attention to two points: First, before sending the verification code, save the verification code database, so as not to verify the code is sent out, but the database has failed to save, this time even if the user receives the SMS verification code to verify the time is also a failure, if you fail to save the database, direct prompts a failure to send a message can be sent, do not re-send the text message to cause a waste; second is to save the database Secondly, to save the database, we need to consider the user did not receive the SMS, re-send the case, this time is to update the database records, rather than new, if it is a new, SMS verification records are duplicated, verification of SMS, it is likely to get the last verification records, the user to use the current verification code received verification, it is also verified that can not be passed.

In fact, the following verification logic inside, but also less than a cell phone number correctness verification, because it is added later, will no longer paste.

/**
 * Send a cell phone verification code
 */
new Dispatch( [
'wizhi/get_phone_code' => function ( $request ) {

   $phone = isset( $_POST[ 'phone' ] ) ? $_POST[ 'phone' ] : false;

   if ( $phone ) {

      // Generate a randomized code
      $phone_code = str_pad( mt_rand( 1, 99999 ), 6, '0', STR_PAD_LEFT );

      // create the database record first, then send the SMS.
      // Use findOrCreate instead of just create When retrying after a failed password send, creating a duplicate record causes authentication to fail
      $code = R::findOrCreate( CODES, [ 'phone' => $phone ] );
      $code->code = $phone_code;

      $success = R::store( $code );

      // Send the SMS after the database record has been created successfully, otherwise you don't have to send the SMS, and it won't be verified
      $sms = false;
      if ( $success ) {
         $sms = send_sms( $phone, $phone_code );
      } else {
         $msg = [
            'success' => 1, 'message' => 'verify' => 1, $sms = send_sms(
            'message' => 'Failed to send authentication SMS, please retry',
         ]; }
      }

      if ( $sms ) {
         $msg = [
            'success' => 1,
            'message' => 'Verification text message sent',
         ];
      } else {
         $msg = [
            'success' => 1, 'message' => 'Verification SMS sent', ]; } else { $msg = [ 'success' => 1, 'message' => 'Verification SMS sent', ]; }
            'message' => 'Failed to send verification SMS, please retry', ]; } else { $msg = [ 'success' => 1, 'message' => 'Verification SMS sent.
         ]; }
      }

   } else {
      $msg = [
         'success' => 0,
         'message' => 'Please enter the correct cell phone number',
      ];
   }

   wp_send_json( $msg ).

},

] );

After receiving the correct request, the above route returns a message string in JSON format, which can be further processed in the front-end, let's take a look at the front-end code implementation.

The front-end code implementation of the sent SMS verification code

The following code is a click to send a verification code, request the back-end interface, send SMS to the user's function, send verification SMS a minute later, you can re-send, you need to pay attention to the timer trigger timing, to be successfully sent after the text message, before enabling the timer. Otherwise, the user's cell phone filled in the wrong, or for other reasons did not send the text message, the user has to wait for a minute in vain, in order to continue to send SMS. If you are more rigorous, you can add a random CAPTCHA mechanism to prevent malicious programs from scanning to send SMS bombs.

//timer处理函数
var InterValObj; //timer变量,控制时间
var count = 60; //间隔函数,1秒执行
var curCount;//当前剩余秒数

/**
 * 设置计时器
 * @constructor
 */
function SetRemainTime() {
    if (curCount == 0) {
        window.clearInterval(InterValObj);//停止计时器
        $("#get_code").removeAttr("disabled");//启用按钮
        $("#get_code").val("重新发送");
    }
    else {
        curCount--;
        $("#get_code").val(curCount + "后重新获取");
    }
}


/**
 * 发送短信验证码
 * @returns {boolean}
 */
$('#get_code').on('click', function (event, element) {
    event.preventDefault();

    // 向后台发送处理数据
    $.ajax({
        method  : 'POST',
        url     : WizUrls.get_phone_code,
        dataType: "json",
        data    : {
            'phone': $('form#modal-register #user_login').val()
        },
        success : function (data) {
            if (data.success === 0) {
                $('form#modal-register div.status').removeClass('c-alert-success').addClass('c-alert c-alert-danger').html(data.message);
                return false;
            } else {
                // 验证码发送成功后,启动计时器
                curCount = count;

                // 设置button效果,开始计时
                $(this).attr("disabled", "true");
                $(this).val(curCount + "后重新获取");

                InterValObj = window.setInterval(SetRemainTime, 1000); //启动计时器,1秒执行一次

                $('form#modal-register div.status').removeClass('c-alert-danger').addClass('c-alert c-alert-success').html(data.message);
                return true;
            }
        }
    });

    return false;
});

After sending the registration and login verification SMS, front-end and back-end implementation are available, the last is to achieve the user registration or login, this step is a more conventional operation, according to the user's cell phone number, from the database to take out the verification code, and the user submitted to the verification code compared to, if consistent, that the verification code is correct, for the next step in the process; if inconsistent, that the verification code is incorrect, prompting the user to verify the code! If it is inconsistent, the code is incorrect and the user is prompted to correct or resend the code.

Related Posts

0 Comments

  1. Hello, can you give me the file structure of the implementation? I'm new to wordpress and don't know much about the js calls in it.

    1. If you're adding SMS verification to the WordPress default registration form, you can use the register_formregistration_errors These two Hooks.

Leave a Reply

Your email address will not be published. Required fields are marked *