SMS Verification Code implementation when we use mobile, telecommunications and other operators online business, in order to ensure the integrity and correctness of the service, often need to use SMS verification code. A similar function has been done recently because of the business needs of a province. The principle is very simple, is the user clicks"Get Verification Code", Ajax obtains a fixed number of digits, then writes the database text message, writes the cookie to set the validity period of the verification code. The JS request verification code is as follows: $.ajax ({type:"GET", URL:".. /ajax/smsrandcodetest.ashx?phone="+ phone.val () +"&smscoderand="+num, success:function (result) {if(Result = ="Y") {alert ("The verification code has been sent to the phone number you entered! Valid for 5 minutes"); Remaintime (); } Else{alert ("Verification Code acquisition failed! Please re-obtain"); }}, Error:function () {alert ("Error"); } });//get 6-bit random verification codefunction Random () {varnum =""; for(i =0; I <6; i++) {num= num + Math.floor (math.random () *Ten); } returnnum;}//Verification Code Validity Countdownfunction Remaintime () {varIsecond; varSsecond ="", stime =""; if(Itime >=0) {Isecond= parseint (itime% -); if(Isecond >=0) {Ssecond= Itime +"seconds"; } 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 ()", +); } itime= Itime-1; } $("#endtime"). HTML (stime);} The front-end to deal with the work basically as above, now to add logic in the HttpHandler, in order to prevent JS generated code mismatch, we re-generated at the backend:if(Smscoderand. Length! =6)//if the random code generated by JS does not match, a random code is generated in C #{Smscoderand=getrandom ();}//Write SMS data, send SMS//Write a cookie, set the validity of the verification code, such as 5 minutes//Note: If all of the above processing succeeds, return "Y", processing fails, return "N"for convenience, verification of the validity of the validation code is done with a cookie. When the business commits, it gets the client's cookie to see if it exists, and if it does not exist, it must expire. If a subsequent business extension might consider adding a database's validity period validation, as well as some other rules, such as limiting the number of codes to be sent in an hour or a day (you can't always send text messages indefinitely), and so on.
The realization of SMS Verification code JS