.NET发送短信验证码过程

1.新建一个项目来调用第三方类

using qcloudsms_csharp;
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)
            {

            }
            catch (HTTPException ex)
            {

            }
            catch (Exception ex)
            {

            }
            Code = code;
        }
    }
}

然后引入类库 qcloudsms_csharp

2.把第三方的公共类放入项目中

3.创建一张关于短信发送记录的数据库表

create table SMSInfo(
    Id int identity primary key,
    Code int,
    TelPhone bigint,
    CreateTime datetime,
    ExpireTime datetime

)

编写实体类

 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 int AddSmsInfo(SMSInfo sMSInfo)
        {
            int result = -1;
            string sql = @"INSERT INTO [Student].[dbo].[SMSInfo]
           ([Code]
           ,[TelPhone]
           ,[CreateTime]
           ,[ExpireTime])
     VALUES
           (Code
           , TelPhone
           , CreateTime
           , ExpireTime)";

            SqlParameter[] parameters = {
                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
                }
            };
            sqlHelper sqlHelper = new sqlHelper();
            sqlHelper.ExcuteNoQuery(sql, parameters);
            return result;
        }

业务层引用第三方项目先调用第三方的类

public bool SendCode(string telphone)
        {

            TenXunYunSMS tenXunYunSMS = new TenXunYunSMS();
            try
            {
                //设置开发账号
                tenXunYunSMS.appId = Convert.ToInt32(ConfigurationManager.AppSettings["appId"]);
                tenXunYunSMS.appKey = ConfigurationManager.AppSettings["appKey"];
                //发送验证码
                tenXunYunSMS.SetSMS(telphone);
            }
            catch (Exception)
            {

                return false;
            }
/// <summary>
        /// 查询短信发送记录
        /// </summary>
        /// <param name="telPhone"></param>
        /// <returns></returns>
         public int QuerySmsInfo(SMSInfo sMSInfo)
        {
            //数据访问
            SMSInfoRepoository infoRepoository = new SMSInfoRepoository();
            return infoRepoository.QuerySmsInfo(sMSInfo);
        }
        

发送验证码,然后将验证码存储到短信信息对象,最后调用数据访问层的插入短信的方法。

 public int QuerySmsInfo(SMSInfo sMSInfo)
        {
            int result = -1;
            string sql = @"select COUNT(1) from dbo.SMSInfo where Code = @Code and TelPhone = @TelPhone and ExpireTime>@ExpirtTime";

            SqlParameter[] parameters = {
                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
                }
            };
            //执行sql语句
            sqlHelper sqlHelper = new sqlHelper();
            sqlHelper.ExecuteScalar(sql, parameters);
            return result;
        }

然后新建一个公共的控制器并在控制器中编写一个JsonResult 的发送验证码方法

 /// <summary>
        /// 发送验证码
        /// </summary>
        /// <param name="tel"></param>
        /// <returns></returns>
        public JsonResult SendCode(string tel)
        {
            OperateResult operateResult = new OperateResult();
            //业务层
            SMSInfoService sMSInfoService = new SMSInfoService();
            operateResult.Success = sMSInfoService.SendCode(tel);
            return Json(operateResult);
        }

再在控制器中编写一个校检验证码接受短信信息的对象

  public JsonResult ValidateCode(SMSInfo sMSInfo)
        {
            OperateResult operateResult = new OperateResult();
            SMSInfoService sMSInfoService = new SMSInfoService();
            operateResult.Success = sMSInfoService.QuerySmsInfo(sMSInfo)>0;
            return Json(operateResult);
        }

编写好后在网页里点击验证码按钮,先禁用按钮,然后ajax post提交到控制器对应的发送验证码方法,传入手机号,然后success处理返回的结果

$("#button").click(function () {
            $(this).attr("disable", "disabled");
            $(this).css("color", "black");
            var time = 60;
            $(this).val(time + "S后可在发送");
            var timer = setInterval(function () {
                if (time > 0) {
                    time--;
                    $("#button").val(time + "S后可在发送");
                }
                else {
                    $("#button").removeAttr("disable").css("color", "white");
                    clearInterval(timer);
                }
            }, 1000);
        })
 //获取验证码
        $("#button").click(function () {
            var telPhone = $("tel").val();
            $.ajax({
                type: "post",
                url: "/Common/SendCode?tel" + telPhone,
                success: function (json) {
                    if (json.success) {
                        alert("成功");
                        IntervalCode()
                    }
                    else {
                        alert("失败");
                    }
                },
            })
        })
    })
   //设置提交
    $("btn").on("click", function () {

        var check = UserName && UserPwd && UserPwdCheck && btnt && validateCode();
        if (!check)
            return;
        var data = {};
        data.Code = $("#Code").val();
        data.TelPhone = $("#tel").val();
        $.ajax({
            type: "post",
            url: "/Common/ValidateCode",
            data: data,
            success: function (json) {
                if (json.success) {
                    SaveRegisterInfo()
                } else {
                    alert("验证码已失效!");
                }
            },
        });
    });

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

//保存注销信息
    function SaveRegisterInfo() {
        var data = {};
        data.UserName = $('#UserName').val();
        data.UeerPwd = $('#UserPwd').val();
        data.UserMobile = $('#tel').val();
        $.ajax({
            type: "post",
            url: "/Login/SaveRegisterInfo",
            dat: data,
            success: function (json) {
                if (json.success) {
                    alert("成功");
                    window.location.href = "Login/Login"
                }
                else {
                    alert("失败");
                }
            }

        })
    })

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值