How to Implement SMS Verification for WordPress Registration and Login

Mobile phone registration is very popular in China. It is basically a commercial website that requires a mobile phone number to register and log in, or provides the option to register and log in with a mobile phone number. We will not discuss whether this behavior infringes on personal privacy. Today we will only talk about usingWordPress developmentHow to register and log in via SMS. The implementation of mobile phone SMS verification registration and login is actually very simple. Friends who have never done it may feel that there is too much logic to deal with, and they will shrink back before they even start trying. In fact, during the integrated registration verification process, the most troublesome thing is the docking of the SMS interface. The more commonly used SMS interfaces are easy to say. The official SDK and code are provided for reference. You can also use the SMS sending library introduced below. If you encounter a non-mainstream interface, you will be depressed. The interface document is extremely simple and the interface implementation is also very poor. If you are not patient enough, you will not be able to debug it. Stop complaining and let’s get to the point.

The first is to verify the SMS service interface

The SMS interface is necessary. Without an interface, there is no technical implementation. As for which interface to use. It depends on which factors you pay more attention to when choosing. The stability, flexibility, price, etc. of the interface all need to be considered. The table below is “Probably the smartest and most elegant PHP SMS sending library currently, PhpSms” We have compiled several commonly used SMS service providers in China for your reference.

service provider Template SMS Content SMS Voice verification code Minimum consumption Minimum consumption unit price
Luosimao × ¥850(10,000 items) ¥0.085/item
Cloud Patch Network × ¥55(1,000 items) ¥0.055/item
Ronglian Cloud Communication × Recharge ¥500 ¥0.055/item
SUBMAIL × × ¥100(1,000 items) ¥0.100/item
Cloud News × ¥0.050/item
Aggregate data × ¥0.035/item
Ali big fish × ¥0.045/item
SendCloud × ¥0.048/item

Implementation of backend code for sending and verifying SMS messages

Before sending a text message, we must generate a random verification code. While sending the verification code via text message, we also save the verification code in the database for comparison during verification to determine whether the verification code is correct. The following is the simple logic of sending codes when I register and log in to a website. You can refer to it.

Two points need to be noted in the following code: First, before sending the verification code, save the verification code in the database first, so as to prevent the verification code from being sent but the database fails to be saved. At this time, even if the user receives the SMS verification code, the verification will still fail. If the database fails to be saved, just prompt a message that failed to be sent. Do not send SMS anymore and cause waste. Second, when saving the database, you need to consider the situation when the user does not receive the SMS and resends it. At this time, the record in the database is updated instead of creating a new one. If it is a new one, the SMS verification record will be repeated. When verifying the SMS, it is likely to obtain the previous verification record. When the user uses the currently received verification code to verify, the verification will also fail.

In fact, in the verification logic below, there is one missing piece of verification of the correctness of the mobile phone number. Since it was added later, it will not be pasted again.

/**
 * 发送手机验证码
 */
new Dispatch( [
'wizhi/get_phone_code' => function ( $request ) {

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

   if ( $phone ) {

      // 生成随机验证码
      $phone_code = str_pad( mt_rand( 1, 99999 ), 6, '0', STR_PAD_LEFT );

      // 先创建数据库记录,再发送短信,
      // 用 findOrCreate 而不是直接 create 密码发送失败后重试时,创建重复记录导致验证失败
      $code       = R::findOrCreate( CODES, [ 'phone' => $phone ] );
      $code->code = $phone_code;

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

      // 数据库记录创建成功后再发送短信,否则就不用发短信了,发了也验证不了
      $sms = false;
      if ( $success ) {
         $sms = send_sms( $phone, $phone_code );
      } else {
         $msg = [ 
            'success' => 1, 
            'message' => '验证短信发送失败,请重试', 
         ];
      }

      if ( $sms ) {
         $msg = [
            'success' => 1,
            'message' => '验证短信已发送',
         ];
      } else {
         $msg = [
            'success' => 1,
            'message' => '验证短信发送失败,请重试',
         ];
      }

   } else {
      $msg = [
         'success' => 0,
         'message' => '请输入正确的手机号码',
      ];
   }

   wp_send_json( $msg );

},

] );

After receiving the correct request, the above route returns a message string in JSON format. We can perform further processing on the front-end based on the returned string. Let’s take a look at the implementation of the front-end code.

Front-end code implementation of SMS verification code sent

The following code implements the function of requesting the back-end interface and sending a text message to the user after clicking to send the verification code. After one minute of sending the verification text message, it can be resent. What needs to be noted is the triggering time of the timer. The timer must be enabled only after the text message is successfully sent. Otherwise, if the user’s mobile phone number is entered incorrectly, or the text message cannot be sent due to other reasons, the user will have to wait for a minute in vain before he can continue to send the text message. If you are more rigorous, you can add a random verification code mechanism to prevent malicious programs from scanning and sending text message 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, the front-end and back-end implementations are completed. Finally, the user registers or logs in. This step is a relatively routine operation. According to the user’s mobile phone number, the verification code is retrieved from the database and compared with the verification code submitted by the user. If it is consistent, it means that the verification code is correct, and the next step is processed; if it is inconsistent, it means that the verification code is wrong, prompts the user that the verification code is wrong, and allows the user to correct or resend the verification code.

Related Posts

Leave a Reply

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