短信验证码


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

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值