会员注册等手机验证码
这个很常用的
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
var timeout; var time = 60; var timer = function () { time = time - 1; $(".getPhoneCode").html('<em style="color:#e0e7e4">' + time + '秒后获取</em>'); if (time == 0) { time = 60; $(".getPhoneCode").attr('status', '0'); $(".getPhoneCode").html("获取验证码"); clearInterval(timeout); } } $('.getPhoneCode').click(function () { var phone = $("#txtPhone").val(); var status = $(this).attr('status'); if(phone=='') { layer.msg("手机号码不能为空"); return; } else if (!regPhone.test(phone)) { layer.msg("您输入的手机号格式有误"); return; } else { $(this).attr('status', '1'); if (status == 1) return false; timeout = setInterval(timer, 1000); $.get("/Handler/SiteHandler.ashx?action=CheckPhoneCode", { Phone: phone, Type: 1 }, function (data) { var result = GetResult(data); if (result.IsSuccess) { layer.msg(result.Message); } else { if (result.Message != "") { layer.alert(result.Message); } } }) } }) <label class="label_content" style="margin-top:7px"> <input type="text" id="txtCode" name="txtCode" class="text_input f_left" value="" style="width:70%" maxlength="6" placeholder="验证码" onkeyup="value=value.replace(/[^\d]/g,'') " /> <em class="getPhoneCode" status="0" style="margin-left:3% ;text-align:right" >获取验证码</em> </label>
注册时获取短信验证码,并且去Redis里面取验证码,进行比较,如果相等,再进行注册编码
int phoneCode = _httpReuqestString["phoneCode"].ToInt(); int backCode = GetLogCode(users.Phone, (int)SendSMS.注册短信发送); if (phoneCode == backCode) { ... }
存取验证码
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
/// <summary> /// 存验证码 /// </summary> /// <param name="strPhone"></param> /// <param name="code"></param> /// <param name="num"></param> public void SetLogCode(string strPhone, int code, int num, int type) { Msg_verificationcode codelog = new Msg_verificationcode("IDPlus=" + num, false); if (codelog.HaveData) { string LogCodeKey = "LogCode_" + type + strPhone; try { RedisClient redisClient = RedisHelper.GetConnection(); redisClient.Set<int>(LogCodeKey, code, codelog.Endtime.ToDateTime()); } catch (Exception ex) { LogHelper.MyWriteLogTxt("LogCode Error:" + ex.ToString(), 16); } } } /// <summary> /// 取验证码 /// </summary> /// <param name="strPhone"></param> /// <returns></returns> public int GetLogCode(string strPhone, int type) { int r = 0; string LogCodeKey = "LogCode_" + type + strPhone; try { RedisClient redisClient = RedisHelper.GetConnection(); var result = redisClient.Get<int>(LogCodeKey); r = result; } catch (Exception ex) { LogHelper.MyWriteLogTxt("LogCode Error:" + ex.ToString(), 16); } return r; }
获取验证码(限制每日发送次数)
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
/// <summary> /// 获取验证码 /// </summary> public void CheckPhoneCode() { DateTime dtDay = DateTime.Now; string strPhone = _httpReuqestString["Phone"].ToString(); int type = _httpReuqestString["Type"].ToInt(); int count = 0; List<XS.Nh.Entity.Msg_VerificationCode> codelog = new DbService<XS.Nh.Entity.Msg_VerificationCode>().GetQuery().Where(o => o.Phone == strPhone && o.Type == type && o.AddTime.Date == new DateTime(dtDay.Year, dtDay.Month, dtDay.Day)).ToList(); XS.Nh.Entity.Shop_Customer ShopCustomerEntity = HttpContext.Current.Session["ShopCustomerEntity"] as XS.Nh.Entity.Shop_Customer; if (type == (int)SendSMS.注册短信发送) { Users users = new Users(string.Format("Phone='{0}'", strPhone), false); if (users.HaveData) { PrintErrorJson("对不起,此手机号已被注册!"); return; } count = CommonHelper.GetAppSettings("sendRegistCodeCount").ToInt(); } if (type == (int)SendSMS.重置密码短信发送) { Users users = new Users(string.Format("Phone='{0}'", strPhone), false); if (!users.HaveData) { PrintErrorJson("对不起,此手机号尚未注册!"); return; } count = CommonHelper.GetAppSettings("sendUpdateCodeCount").ToInt(); } if (type == (int)SendSMS.修改用户信息短信发送) { Users user = new Users(string.Format("CustomerID={0}", ShopCustomerEntity.CustomerId), false); if (user.HaveData) { if (user.Phone != strPhone) { Users users = new Users(string.Format("Phone='{0}'", strPhone), false); if (users.HaveData) { PrintErrorJson("对不起,此手机号已被注册!"); return; } } else { PrintErrorJson("手机号尚未变更,无需验证码!"); return; } } count = CommonHelper.GetAppSettings("sendUpdateUserInfoCodeCount").ToInt(); } if (type == (int)SendSMS.绑定用户短信发送) { Users users = new Users(string.Format("Phone='{0}'", strPhone), false); //判断这个手机号的用户是否存在,不存在则可以发送短信 if (users.HaveData) { //判断这个会员的customerid是否有值 if (users.Customerid == ShopCustomerEntity.CustomerId) { PrintErrorJson("此手机号已绑定!"); return; } else { Shop_customer customer = new Shop_customer(string.Format("CustomerId='{0}'", users.Customerid), false); if(customer.HaveData) { if(!string.IsNullOrEmpty(customer.Openid)) { PrintErrorJson("此手机号已绑定!"); return; } } } } count = CommonHelper.GetAppSettings("sendBindUserCodeCount").ToInt(); } if (codelog.Count < count) { int sendInt = GetLogCode(strPhone, type); if (sendInt > 0) { PrintErrorJson("验证码尚未过期,请查收短信!"); } else { Random rand = new Random(); int code = rand.Next(100000, 999999); string extend = "123456";//回传参数 可选 string param = "{\"code\":\"" + code + "\",\"product\":\"omg\"}";//参数 string recNum = strPhone; string format = "";//数据格式 TopSdk.GetSdkAPI(extend, param, recNum, format); int num = InsertPhoneCodeLog(strPhone, code, type); if (num > 0) { SetLogCode(strPhone, code, num, type); } PrintSuccessJson("短信已发送,请注意查收!"); } } else { PrintErrorJson("您今天的发送次数满了,请明天再来!"); } }
插入验证码日志记录
/// <summary> /// 插入验证码日志记录 /// </summary> /// <param name="strPhone"></param> /// <param name="code"></param> public int InsertPhoneCodeLog(string strPhone, int code, int type) { XS.Nh.Entity.Msg_VerificationCode codelog = new XS.Nh.Entity.Msg_VerificationCode(); codelog.Id = Guid.NewGuid().ToString(); codelog.AddTime = DateTime.Now; codelog.DelStatus = 0; codelog.Phone = strPhone; codelog.Code = code.ToString(); codelog.Type = type; codelog.EndTime = codelog.AddTime.ToDateTime().AddMinutes(CommonHelper.GetAppSettings("ExpiredTime").ToInt()); return new DbService<XS.Nh.Entity.Msg_VerificationCode>().SaveModel(codelog); }
验证码接口(第三方)
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
public class TopSdk { static string url = System.Configuration.ConfigurationManager.AppSettings["SmsUrl"];//调用地址 static string appkey = System.Configuration.ConfigurationManager.AppSettings["AppKey"];//appkey static string Code = System.Configuration.ConfigurationManager.AppSettings["SmsCode"];//模版id static string SignNname = System.Configuration.ConfigurationManager.AppSettings["SmsSignNname"];//签名 static string secret = System.Configuration.ConfigurationManager.AppSettings["AppScrect"]; static string SmsType = System.Configuration.ConfigurationManager.AppSettings["SmsType"];//短信类型 /// <summary> /// /// </summary> /// <param name="extend">回传参数 可选</param> /// <param name="smsParam"> 短信模版变量</param> /// <param name="recNum">电话号码</param> /// <format name="format">参数格式</format> /// <returns></returns> public static void GetSdkAPI(string extend, string smsParam, string recNum, string format) { try { if (format == "" || format == null) format = "json"; ITopClient client = new DefaultTopClient(url, appkey, secret, format); AlibabaAliqinFcSmsNumSendRequest req = new AlibabaAliqinFcSmsNumSendRequest(); req.Extend = extend; req.SmsType = SmsType; req.SmsFreeSignName = SignNname; req.SmsParam = smsParam; req.RecNum = recNum; req.SmsTemplateCode = Code; AlibabaAliqinFcSmsNumSendResponse rsp = client.Execute(req); } catch (Exception ex) { LogHelper.MyWriteLogTxt(ex.Message); } } }