短信验证

1.项目中创建一个Remote类库,添加一个TenXunYunSMS.cs添

加后在引用的NuGet包管理器中的浏览搜索qcloudsms_csharp下载

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

 

2.在数据库中创建一个表来存储用户接收到的验证码

create table Sms(
smsId int IDENTITY PRIMARY KEY,
smscode int not null,
userTel bigint not null,
smsTime datetime not null,
smsEfficacy datetime not null
}

3.在MVC中的Web.config里配置第三方提供的appId值和appKey值

    <add key="addId" value=""/>
    <add key="addKey" value=""/>

4.在项目中添加一个实体SmsInfo类

    public class SMSInfo
    {
        public int Id { get; set; }
        public int code { get; set; }
        public Int64 phone { get; set; }
        public DateTime ExpireTime { get; set; }
        public DateTime Createtime { get; set; }
    }

5. .UI层 在网页中的"获取验证码"按钮添加一个click事件

$(function () {
        $("#GetCode").click(function () {
            var tel = $("#tel").val();
            $.ajax({
                url: "/Common/GetCode?phone=" + tel,
                type: "post",
                success: function (result) {
                    if (result.Success) {
                        alert("获取成功");
                        IntervalTime();
                    }
                    else {
                        alert("获取失败");
                    }
                }
            })
        })

6.在Login控制器中添加GetCode(string tel)方法:向数据库添加一条消息

GetCodes(string tel)方法:从数据库查询用户是否已有验证码


 public JsonResult GetCode(string tel)
    {
       //调用Operate 对象(Operate类只有一个属性bool类型的Success)
       Operate op = new Operate();
       //调用业务层的SmsGain类
       SmsGain s = new SmsGain();
       //调用业务层的SmsGain类的Sms_Gain(string tel)方法
       op.Success =s.Sms_Gain(tel);
       //返回结果
       return Json(op);
    }
 
 
 
 
//是否已有验证码
 public JsonResult GetCodes(string tel)
        {
            //调用Operate 对象(Operate类只有一个属性bool类型的Success)
            Operate op = new Operate();
            //调用业务层的SmsGain类
            SmsGain s = new SmsGain();
            //调用业务层的SmsGain类的Sms_Gain(string tel)方法
            op.Success = s.Sms_Gains(tel)>0;
            //返回结果
            return Json(op);
        }

7.在业务层的SmsGain类中添加SendCode(string telphone)方法和SendCodes(string tel)方法

 public class SMSInfoService
    {
        public bool SendCode(string telphone)
        {
            TenXunYunSMS tenXunYunSMS = new TenXunYunSMS();
            try
            {
                tenXunYunSMS.appId = Convert.ToInt32(ConfigurationManager.AppSettings["addId"]);
                tenXunYunSMS.appKey = ConfigurationManager.AppSettings["addKey"];
                tenXunYunSMS.SetSMS(telphone);
            }
            catch (Exception)
            {
                return false;
            }
            SMSInfoRepository infoRepository = new SMSInfoRepository();
            SMSInfo sMSInfo = new SMSInfo();
            sMSInfo.code = tenXunYunSMS.Code;
            sMSInfo.phone = Convert.ToInt64(telphone);

            return infoRepository.AddSmsInfo(sMSInfo) > 0;
        }
        
        //是否已有验证码
   public int SendCodes(string tel)
        {
            SSmsInfo ss = new SSmsInfo();
            return ss.selectsmss(tel);
        }
    }

8.数据访问层的SSmsInfo的AddSmsInfo(SmsInfo sMSInfo)方法和 selectsmss(string tel)方法

    public class SMSInfoRepository
    {
        public int AddSmsInfo(SMSInfo sMSInfo) {
            string sql = @"INSERT INTO [Mishop02].[dbo].[SMSInfo]
                       ([code]
                       ,[phone]
                       ,[ExpireTime]
                       ,[Createtime])
                 VALUES
                       (@code
                       ,@phone
                       ,@ExpireTime
                       ,@Createtime)";

            SqlParameter[] parameters =
            {
                new SqlParameter(){
                    DbType = DbType.Int32,
                    ParameterName="@code",
                    Value=sMSInfo.code
                },
                 new SqlParameter(){
                    DbType = DbType.Int32,
                    ParameterName="@phone",
                    Value=sMSInfo.code
                },
                  new SqlParameter(){
                    DbType = DbType.DateTime,
                    ParameterName="@ExpireTime",
                    Value=DateTime.Now
                },
                   new SqlParameter(){
                    DbType = DbType.DateTime,
                    ParameterName="@Createtime",
                    Value=DateTime.Now.AddMinutes(5)
                }

            };
            DBHelper db = new DBHelper();
            return db.ExcuteNoQuery(sql, parameters);
        }

        
public int selectsmss(string tel)
        {
            string sql = @"select COUNT(1) from dbo.Sms where userTel=@userTel and                     
                         smsEfficacy>@smsEfficacy";
            SqlParameter[] parameters = {
                
                new SqlParameter()
                {
                    DbType = DbType.Int64,
                    ParameterName = "@userTel",
                    Value =Convert.ToInt64(tel)
                },
                new SqlParameter()
                {
                    DbType = DbType.DateTime,
                    ParameterName = "@smsEfficacy",
                    Value = DateTime.Now
                }
            };
            SqlHelper db = new SqlHelper();
            return db.ExecuteReader(sql, parameters);
         }
    }

9.工具类SqlHelper 的ENQ(string sql, SqlParameter[] parameters)方法ER(string sql, SqlParameter[] parameters)方法

public int ENQ(string sql, SqlParameter[] parameters) {
            try
            {
                //1:创建连接 
                conn = new SqlConnection(config);
                //2:打开连接 
                conn.Open();
                //3;创建SqlCommand对象
                SqlCommand comm = new SqlCommand(sql, conn);
                //4:预处理 
                if (parameters != null)
                {
                    comm.Parameters.AddRange(parameters);
                }
                //5:执行sql语句 (ExcuteNonQuery)
                i= comm.ExecuteNonQuery();
                //6:处理返回结果、
                return i;
            }
            catch (Exception ex)
            {
                return i;
            }
            finally {
                conn.Close();
            }
        }
 
 
 
 
 
 
 public int ER(string sql, SqlParameter[] parameters)
        {
            try
            {
                //1:创建连接 
                conn = new SqlConnection(config);
                //2:打开连接 
                conn.Open();
                //3;创建SqlCommand对象
                SqlCommand comm = new SqlCommand(sql, conn);
                //4:预处理 
                if (parameters != null)
                {
                    comm.Parameters.AddRange(parameters);
                }
                //5:执行sql语句 (ExcuteNonQuery)
                i =Convert.ToInt32(comm.ExecuteScalar());
                //6:处理返回结果、
                return i;
            }
            catch (Exception ex)
            {
                return i;
            }
            finally
            {
                conn.Close();
            }
        }
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值