欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

.NET MVC 短信验证码过程

程序员文章站 2022-05-13 09:47:10
...

1:创建一个项目用来调用第三方的类,右键Nuget添加第三方的引用类库 qcloudsms_csharp

2:把第三方的公共类放入到我们的项目里

using qcloudsms;
using qcloudsms_csharp.httpclient;
using qcloudsms_csharp.json;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace MiShop.Remote
{
    public class TenXunYunSMS
    {
        //appId
        public int appId;
        //appKey
        public string appKey = "";
        //短信模板ID
        private int tmplateId = 379257;
        //签名内容
        private string smsSign = "7hhhcn";
        /// <summary>
        /// 验证码
        /// </summary>
        public int Code { get; set; }
        /// <summary>
        /// 发送验证码
        /// </summary>
        /// <param name="phone"></param>
        /// <returns></returns>
        public void SetSMS(string phone)
        {
            Random random = new Random();
            int code = random.Next(100000, 999999);
            try
            {
                SmsSingleSender ssender = new SmsSingleSender(appId, appKey);
                var result = ssender.sendWithParam("86", phone,
                tmplateId, new[] { code.ToString() }, smsSign, "", "");  // 签名参数未提供或者为空时,会使用默认签名发送短信
            }
            catch (JSONException ex)
            {
                throw;
            }
            catch (HTTPException ex)
            {
                throw;
            }
            catch (Exception ex)
            {
                throw;
            }
            Code = code;
        }
    }
}

3:创建一张短信发送记录表 

//信息记录表
public class SMSInfo
    {
            public int Id { get; set; }
            public int Code { get; set; }
            public Int64 TelPhone { get; set; }
            //创建时间
            public DateTime CreateTime { get; set; }
            //短信过期时间
            public DateTime ExpireTime { get; set; }
    }

4:数据访问层写插入短信信息表方法

public class SMSInfoRepository
    {   
        /// <summary>
        /// 将验证码和电话保存至数据库
        /// </summary>
        /// <param name="sMSInfo"></param>
        /// <returns></returns>
        public int InsertSMSInfo(SMSInfo sMSInfo)
        {
            int result = -1;
            string sql = @"insert into SMSInfo values(@Code, @TelPhone, @CreateTime, @ExpireTime)";
            SqlParameter[] sqlParameter = {
                new SqlParameter(){
                    DbType=DbType.Int32,
                    ParameterName="@Code",
                    Value=sMSInfo.Code
                },
                 new SqlParameter(){
                    DbType=DbType.Int64,
                    ParameterName="@TelPhone",
                    Value=sMSInfo.TelPhone
                },
                  new SqlParameter(){
                    DbType=DbType.DateTime,
                    ParameterName="@CreateTime",
                    Value=DateTime.Now
                },
                   new SqlParameter(){
                    DbType=DbType.DateTime,
                    ParameterName="@ExpireTime",
                    Value=DateTime.Now.AddMinutes(5)
                }
            };
            DBHelper dBHelper = new DBHelper();
            result =dBHelper.ExcuteNoQuery(sql,sqlParameter);
            return result;
        }
        /// <summary>
        /// 查询电话和验证码是否正确
        /// </summary>
        /// <param name="sMSInfo"></param>
        /// <returns></returns>
        public int SelCodePhone(SMSInfo sMSInfo)
        {
            int result = -1;
            string sql = @"select COUNT(1) from SMSInfo where [email protected] and [email protected] and ExpireTime>@ExpireTime";
            SqlParameter[] sqlParameter = {
                new SqlParameter(){
                    DbType=DbType.Int32,
                    ParameterName="@Code",
                    Value=sMSInfo.Code
                },
                 new SqlParameter(){
                    DbType=DbType.Int64,
                    ParameterName="@TelPhone",
                    Value=sMSInfo.TelPhone
                },
                    new SqlParameter(){
                    DbType=DbType.DateTime,
                    ParameterName="@ExpireTime",
                    Value=DateTime.Now
                }
            };
            DBHelper dBHelper = new DBHelper();
            result = dBHelper.ExecuteScalar(sql, sqlParameter);
            return result;
        }
    }


5:业务层:先引用第三方项目,先调用第三方类,发送验证码,然后将验证码存储到短信信息对象,最后调用数据访问层的插入短信的方法。

 public class SMSInfoSerivice
    {
        /// <summary>
        /// 获取验证码同时将验证码保存至数据库
        /// </summary>
        /// <param name="phone"></param>
        /// <returns></returns>
        public bool GetCode(string phone)
        {
            //调用第三方类
            TenXunYunSMS tenXunYunSMS;
            try
            {
                tenXunYunSMS = new TenXunYunSMS();
                tenXunYunSMS.appId = Convert.ToInt32(ConfigurationManager.AppSettings["appId"]);
                tenXunYunSMS.appKey = ConfigurationManager.AppSettings["appKey"];
                tenXunYunSMS.SetSMS(phone);
            }
            catch (Exception)
            {

                return false;
            }
            SMSInfoRepository sMSInfoRepository = new SMSInfoRepository();
            //创建信息对象保存验证码和电话号码
            SMSInfo sMSInfo = new SMSInfo();
            //将验证码存储到短信信息对象
            sMSInfo.Code = tenXunYunSMS.Code;
            sMSInfo.TelPhone = Convert.ToInt64(phone);
            //调用插入短信信息的方法 成功返回true
            return sMSInfoRepository.InsertSMSInfo(sMSInfo)>0;
        }
        /// <summary>
        /// 查询电话和验证码是否正确
        /// </summary>
        /// <param name="sMSInfo"></param>
        /// <returns></returns>
        public bool SelCodePhone(SMSInfo sMSInfo)
        {
            SMSInfoRepository sMSInfoRepository = new SMSInfoRepository();
            return sMSInfoRepository.SelCodePhone(sMSInfo)>0;
        }
    }


6:控制器写一个JsonResult的发送验证码方法需要接收手机号 

public JsonResult GetCode(string phone)
        {
            Operate operate = new Operate();
            SMSInfoSerivice sMSInfoSerivice = new SMSInfoSerivice();
            operate.Success = sMSInfoSerivice.GetCode(phone);
            return Json(operate);
        }


7:控制器写一个JsonResult的校验验证码方法需要接收短信信息对象 

//点击注册时查询电话号码与短信验证码是否存在
public JsonResult SelCodePhone(SMSInfo sMSInfo)
        {
            Operate operate = new Operate();
            SMSInfoSerivice sMSInfoSerivice = new SMSInfoSerivice();
            operate.Success = sMSInfoSerivice.SelCodePhone(sMSInfo);
            return Json(operate);
        }


8:页面点击获取验证码按钮:先禁用按钮,然后ajax post提交到控制器对应的发送验证码方法,传入手机号,然后success处理返回的结果。

     //点击获取验证
        $("#GetCode").click(function () {
            var tel = $("#tel").val();
            $.ajax({
                url: "/SMSCode/GetCode?phone=" + tel,
                type: "post",
                success: function (result) {
                    if (result.Success) {
                        alert("获取成功");
                        //调用短信验证计时器方法
                        IntervalSMS();
                    }
                    else {
                        alert("获取失败");
                    }
                }
            })
        })

//短信验证计时器
    function IntervalSMS() {

        $("#GetCode").attr("disable", "disabled");
        $("#GetCode").css("color", "red");

        var time = 30;
        $("#GetCode").val(time + " S后重新获取验证码");

        var timer = setInterval(function () {
            if (time > 0) {
                time--;
                $("#GetCode").val(time + " S后重新获取验证码");
            }
            else {
                $("#GetCode").removeAttr("disable").css("color", "black");
                $("#GetCode").val("重新获取验证码");
                clearInterval(timer);
            }
        }, 1000)
    }


9:点击注册按钮,写一个校验验证码的方法,校验通过之后才能注册。 

    //注册按钮  查询记录  为true进行保存注册
        $("#btnRe").click(function () {

            if (ckname == true && ckphone == true && ckrepwd == true && ckpwd == true) {

                var SMSInfo = {};
                SMSInfo.TelPhone = $("#tel").val();
                SMSInfo.Code = $("#yan").val();
                $.ajax({
                    url: "/SMSCode/SelCodePhone",
                    type: "post",
                    data: SMSInfo,
                    success: function (result) {
                        if (result.Success) {
                    //点击注册时查询电话和验证码是否正确 正确则调用该方法进行注册
                            reg();
                        }
                        else {
                            alert("短信验证码不存在");
                            return;
                        }
                    }
                })
            }
            else {
                alert("信息验证未通过无法注册成功");
            }


//点击注册时查询电话和验证码是否正确 正确则调用该方法进行注册
    function reg() {
        var userInfo = {};
        userInfo.UserName = $("#username").val();
        userInfo.UserPwd = $("#password").val();
        userInfo.UserPhone = $("#tel").val();
        $.ajax({
            url: "/Register/SaveUserInfo",
            data: userInfo,
            type: "post",
            success: function (result) {
                if (result.Success) {
                    alert("注册成功");
                }
                else {
                    alert("注册失败");
                }
            }
        })
    }