When we use online business halls of mobile, telecom and other operators, we often need to use SMS verification codes to ensure the integrity and correctness of our business. Recently, a similar function has been made due to the business needs of a certain province.
The principle is very simple. When the user clicks "Get verification code", Ajax gets a string of fixed digits, then writes a database to send a text message, and writes a cookie to set the validity period of the verification code.
The JS request verification code is as follows:
$.ajax({ type: "GET", url: "../Ajax/?phone=" + () + "&smsCodeRand=" + num, success: function(result) { if (result == "Y") { alert("The verification code has been sent to the mobile phone number you entered! Valid for 5 minutes"); RemainTime(); } else { alert("Verification code failed to be retrieved! Please re-acquire"); } }, error: function() { alert("error"); } }); //Get 6-digit random verification codefunction random() { var num = ""; for (i = 0; i < 6; i++) { num = num + (() * 10); } return num; } //Countdown to the validity period of the verification codefunction RemainTime() { var iSecond; var sSecond = "", sTime = ""; if (iTime >= 0) { iSecond = parseInt(iTime % 300); if (iSecond >= 0) { sSecond = iTime + "Second"; } sTime = "<span style='color:darkorange;font-size:13px;'>" + sSecond + "</span>"; if (iTime == 0) { clearTimeout(Account); sTime = "<span style='color:red;font-size:12px;'>Verification code has expired</span>"; } else { Account = setTimeout("RemainTime()", 1000); } iTime = iTime - 1; } $("#endtime").html(sTime); }
The work to be processed by the front-end is basically as above. Now we need to add logic to the HttpHandler. In order to prevent the verification code generated by Js from not complying with the rules, we regenerate it in the back-end:
if ( != 6) //If the random code generated by JS does not match, use C# Generate random codes{smscoderand = GetRandom(); } //Write SMS data and send SMS//Write cookies and set the validity period of the verification code, such as 5 minutes//Note:If all the above are successfully processed,return"Y",Processing failed,return"N"
For convenience, the validity period verification of the verification code is done using cookies. When submitting the business, the client's cookie will be obtained to see if it exists. If it does not exist, it will definitely expire. If you expand the business in the future, you may consider adding database validation period verification, as well as some other rules, such as limiting the number of verification codes sent within one hour or one day (you can't send text messages without limit), etc.
The above is a detailed introduction to how to implement JavaScript SMS verification code, and I hope it will be helpful to everyone.