Business logic implementation of SMS verification code

Keywords: Mobile MySQL JSON Javascript

Mobile phone verification code is a function that we use in our daily life

So let's assume that we can make this function work

There are many ways to achieve this. Some of them are in slow storage

Here I simply record the implementation process of the latter!

First, make a button to submit the user's mobile number. The submit code of the button and ajax is as follows

<div class="inputbox phone">
    <input type="text" id="phone" value="[[$user.phone]]" disabled>
</div>
<div class="inputbox Vecode">
	<input type="text" id="smscode" placeholder="SMS verification code">
	<a href="javascript:;" class="getVecodeBtn"><p>Get verification code</p></a>
</div>


$('.getVecodeBtn').on('click',function(){
        var obj=$(this);
		var phone='';
        if(obj.attr('is-timer')){
            return true;
        }
        ajax({
            url:global.appurl+'a=getPhoneCode',
            data:{phone:phone,stype:4},
            success:function(json){
                if(json.code!=1){
                    _alert(json.msg);
                    return;
                }
                smsTimer(obj);
            }
        });
    });

getPhoneCode this is our back-end method to get the verification code

public function _getPhoneCode(){
//Get the mobile number submitted by the current user
        $phone = $this->params['phone'];
        //If the mobile number is not submitted
        if(!$phone){
//Judge whether the user has logged in
            $user=isLogin();
//Can't continue without landing
            if(!$user){
                jReturn('-1','Please enter the correct mobile number');
            }
//Get the current user's mobile number when you log in
            $phone=$user['phone'];
        }
        $stype = intval(getParam('stype'));
        if(!isPhone($phone)){
            jReturn('-1','Incorrect mobile number');
        }
        if(!$stype){
            jReturn('-1','Incorrect verification code type');
        }
        $data=array(
            'phone'=>$phone,
            'stype'=>$stype
        );
        $res=getPhoneCode($data);
        exit(json_encode($res));
    }

The getPhoneCode method is mainly used to process the verification code. The code is as follows:

//This parameter serves as an identifier
if(!$data['stype']||!$data['phone']){
		return array('code'=>'-1','msg'=>'Missing validation parameter');//Missing validation parameter
	}
$mysql=new Mysql(0);
$limit_time=60;//Cannot get repeatedly within 60 seconds
$list=$mysql->fetchRows("select * from sys_vcode where phone='{$data['phone']}' and stype='{$data['stype']}' and UNIX_TIMESTAMP()-create_time<{$limit_time}",1,5);
$cnt=count($list);
if($cnt>0){
    //Too often to get verification code, please try again later
	return array('code'=>'-1','msg'=>'Too often to get verification code, please try again later');
}
//This place is the configuration of SMS service providers 
$sys_sms=getConfig('sys_sms',$mysql);
//Generate a random verification code
$code = rand(123456,999999);
//Content of short message	
$content=str_replace('{$code}',$code,$sys_sms['tpl']);
//Send to third party
$result=sendSms($data['phone'],$content);
if($result!='1'){
	return array('code'=>'-1','msg'=>'SMS sending failed'.$result,$content);//SMS sending failed
}
//Record this verification code
$db_data=array(
	'code'=>$code,
	'phone'=>$data['phone'],
	'stype'=>$data['stype'],
	'create_time'=>NOW_TIME,
	'create_ip'=>CLIENT_IP,
	'scon'=>$content
);
$res=$mysql->insert($db_data,'sys_vcode');
if(!$res){
	return array('code'=>'-1','msg'=>'System busy please try again later');//System busy please try again later
}
return array('code'=>'1','msg'=>'Send successfully');//Send successfully

Sort out the generation and recording logic of the verification code: generate a verification code and store it in the database and record the generation time of the verification code

The time interval is 60 seconds. The verification code cannot be generated in time

If the verification code is not generated randomly within the time interval, the verification code will be spliced to the SMS content and mobile phone number

Push together to a third-party service provider

And record the creation time of the verification code mobile number in the table

The sql statement of the table recording the verification code:

CREATE TABLE `sys_vcode` (
	`id` INT(11) NOT NULL AUTO_INCREMENT,
	`stype` TINYINT(4) NULL DEFAULT NULL COMMENT 'Verification code classification',
	`phone` VARCHAR(16) NULL DEFAULT NULL COMMENT 'Cell-phone number',
	`code` VARCHAR(8) NULL DEFAULT NULL COMMENT 'Verification Code',
	`status` TINYINT(2) NULL DEFAULT '0' COMMENT 'state',
	`verify_num` TINYINT(4) NULL DEFAULT '0' COMMENT 'Verification times',
	`create_time` INT(11) NULL DEFAULT NULL COMMENT 'Creation time',
	`verify_time` INT(11) NULL DEFAULT '0' COMMENT 'Contrast time',
	`create_ip` VARCHAR(16) NULL DEFAULT NULL COMMENT 'generate ip',
	`scon` VARCHAR(256) NULL DEFAULT NULL COMMENT 'Content of short message',
	PRIMARY KEY (`id`) USING BTREE,
	INDEX `sp` (`stype`, `phone`) USING BTREE
)
COLLATE='utf8_general_ci'
ENGINE=InnoDB
ROW_FORMAT=COMPACT
AUTO_INCREMENT=5631
;

How to judge whether it is correct according to the submitted verification code in the last step

//Validation parameters
if(!$data['stype']||!$data['code']||!$data['phone']){
	return array('code'=>'-1','msg'=>'Missing validation parameter');//Missing validation parameter
}
$mysql=new Mysql(0);
//Query whether there is data corresponding to the QR code and mobile phone in the above created table
$item=$mysql->fetchRow("select * from sys_vcode where phone='{$data['phone']}' and stype='{$data['stype']}' order by id desc");
//If not
if(!$item['id']){
	return array('code'=>'-1','msg'=>'The SMS verification code is incorrect');//The SMS verification code is incorrect
}
//If this verification code is verified more than twice
if($item['status']||$item['verify_num']>2){
	return array('code'=>'-1','msg'=>'Please get the SMS verification code again');//Please get the SMS verification code again
}
//The verification code is found and the number of verification uses is not up to the limit
$msg='';
$db_data=array('verify_num'=>$item['verify_num']+1);
if($data['code']==$item['code']){
//Validity of detection verification code
if(NOW_TIME-$item['create_time']>1800){
	$msg='The SMS verification code has expired';//The SMS verification code has expired
	$db_data['status']=1;
    }else{
	    $db_data['status']=2;
    }
}else{
	$msg='The SMS verification code is incorrect';//The SMS verification code is incorrect
	if($db_data['verify_num']>2){
			$db_data['status']=1;
		}
	}
$db_data['verify_time']=NOW_TIME;
$res=$mysql->update($db_data,"id={$item['id']}",'sys_vcode');
if(!$res){
	$msg='The SMS verification code is incorrect';//The SMS verification code is incorrect
}
if($msg){
	return array('code'=>'-1','msg'=>$msg);
}
return array('code'=>'1','msg'=>'Verifying and passing');//Verifying and passing

The logic of verification is to determine whether the library exists according to the submitted verification code

If there are several times more than twice to judge the verification number of this verification code, it is necessary to obtain it again

If there is no problem, then judge whether the verification code is within the valid range

Add 1 to the number of verification codes and update the corresponding code information

Return true if there is no problem

This method is called at the place where the interface submitted is verified

The function of SMS verification code is realized here!

Because it's not purely native and useful to write some helper functions

If you have any questions, please leave a message in the comment area

If you think it's useful, please pay attention to it!

 

 

 

 

 

 

 

 

139 original articles published, praised 63, visited 180000+
Private letter follow

Posted by tsilenzio on Tue, 25 Feb 2020 19:56:11 -0800