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

短信验证码

程序员文章站 2022-05-13 15:54:53
...


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

  public class TenXunYunSMS
    {
        //appId
        public int appId;
        //appKey
        public string appKey = "";
        //短信模板ID

        private int tmplateId = 123456;
        //签名内容
        private string smsSign = "ljhhhnb";
        /// <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)
            {
            }
            catch (HTTPException ex)
            {
            }
            catch (Exception ex)
            {

            }
            Code = code;
        }
    }


2:把第三方的公共类放入到我们的项目里
3:创建一张短信发送记录表

/*指定数据库*/
use MiShop
/*创建表*/
create table Hda(
Id int IDENTITY PRIMARY KEY,
Code int not null,
TelPhone bigint not null,
CreateTime datetime not null,
ExpireTime datetime not null
)


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

         //将数据保存到数据库
        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;
        }


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

//调用第三方类,发送验证码
 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)
            {
            }
            catch (HTTPException ex)
            {
            }
            catch (Exception ex)
            {

            }
            Code = code;
        }




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);
            return sMSInfoRepository.InsertSMSInfo(sMSInfo)>0;
        }


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

 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);
            return sMSInfoRepository.InsertSMSInfo(sMSInfo)>0;
        }


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


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

public bool SelCodePhone(SMSInfo sMSInfo)
        {
            SMSInfoRepository sMSInfoRepository = new SMSInfoRepository();
            return sMSInfoRepository.SelCodePhone(sMSInfo)>0;
        }

public JsonResult SelCodePhone(SMSInfo sMSInfo)
        {
            Operate operate = new Operate();
            SMSInfoSerivice sMSInfoSerivice = new SMSInfoSerivice();
            operate.Success = sMSInfoSerivice.SelCodePhone(sMSInfo);
            return Json(operate);
        }


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

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)
    }

$(function () {
        $("#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("获取失败");
                    }
                }
            })
        })


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

$("#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("信息验证未通过无法注册成功");
            }
        })
        $("#username").blur(Checkname);
        $("#password").blur(Checkpwd);
        $("#repassword").blur(Checkrepwd);
        $("#tel").blur(Checktel);
    });



    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("注册失败");
                }
            }
        })
    }