ASP.NET MVC 手机短信验证

时间:2023-03-09 05:34:35
ASP.NET MVC 手机短信验证

本文来自于stoneniqiu的文章,原文地址 http://www.cnblogs.com/stoneniqiu/p/6234002.html

1.注册一个应用

得到AppKey 和 App Secret     应用管理-->应用列表

ASP.NET MVC 手机短信验证

2.设置签名

配置管理-->验证码

签名是出现短信内容最前面的字段,比如【xx科技】xxxx,

ASP.NET MVC 手机短信验证

这个需要审核。显示是2小时内。

3.设置模板

模板就是用来组织短信内容的部分

ASP.NET MVC 手机短信验证

4. 应用测试

完成上面3步之后,我们就可以测试下,在应用管理--应用测试

https://www.alidayu.com/center/application/test

ASP.NET MVC 手机短信验证

测试选择好模板,输入签名、电话号码就可以发送了。

5.代码调试

需要先下载个sdk,.net是TopSDK.dll。如果是https,对应的地址是:https://eco.taobao.com/router/rest

ASP.NET MVC 手机短信验证
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Niqiu.Core.Helpers;
using Top.Api;
using Top.Api.Request;
using Top.Api.Response; namespace Portal.MVC.Controllers
{
public class AliMessageController : Controller
{
//
// GET: /AliMessage/ public static string url = "http://gw.api.taobao.com/router/rest";
public static string appkey = "--583689";
public static string secret = "0---6861cb74da5ac98c02c1172---0";
public ActionResult Index()
{
var res = SendRandomCodeToMobile("1xxxxxxxxxx", "stoneniqiu");
return res;
} public JsonResult SendRandomCodeToMobile(string phone,string username)
{
ITopClient client = new DefaultTopClient(url, appkey, secret);
AlibabaAliqinFcSmsNumSendRequest req = new AlibabaAliqinFcSmsNumSendRequest();
req.Extend = "";
req.SmsType = "normal";
req.SmsFreeSignName = "好油菜";
var randomCode = GetID();
//req.SmsParam = "{name:'stone',number:'3345'}";
req.SmsParam = "{name:'" + username + "',number:'" + randomCode + "'}";
req.RecNum = phone;
req.SmsTemplateCode = "SMS_36290127";
AlibabaAliqinFcSmsNumSendResponse rsp = client.Execute(req);
Console.WriteLine(rsp.Body);
//存储 结果,发送时间,随机数和手机号
if (rsp.IsError)
{
Logger.Debug(rsp.ErrCode + " " + rsp.ErrMsg);
}
return Json(new { success = !rsp.IsError, message = rsp.ErrMsg, code = rsp.ErrCode },JsonRequestBehavior.AllowGet);
} private int GetID()
{
Random rd = new Random();
int num = rd.Next(1000, 9999);
return num; } }
}
ASP.NET MVC 手机短信验证

每个号码有流量限制:

ASP.NET MVC 手机短信验证

测试的时候一小时超过7条就收不到了。发送短信的逻辑就是这么多了,如果要验证用户收到的验证码是否一致 这个就简单了,存储每次发送的手机号和对应的验证码,验证的时候对比下就行了。然后因为该服务是一分钟一条的,所以需要限制下两次获取验证码的间隔是1分钟。这些逻辑都蛮简单的。每个账号有200条免费的可以玩。

6.用例

短信验证可以用于注册或者忘记密码:

ASP.NET MVC 手机短信验证

html:

ASP.NET MVC 手机短信验证
<div class="page" id="register">
<div class="logbg" >
<div class="logtitle">注册好油菜</div>
<div class="regnum">
<input type="tel" id="regtel" placeholder="输入你的手机号码">
<input type="button" id="getvcode" value="获取验证码" readonly>
</div>
<div class="regyzm">
<p>输入你手机收到的4位验证码</p>
<div class="yzmbox">
<input type="number">
<input type="number">
<input type="number">
<input type="number" class="marg0">
</div>
</div>
<div class="inputbox">
<input type="text" id="name" placeholder="输入昵称">
<input type="text" id="regpwd" placeholder="输入6-12位数字和字母密码">
<input type="text" id="crep" placeholder="再次输入上面的密码">
</div>
<input type="submit" id="registerbt" class="logbtn logbtn1" value="确认注册">
</div>
<div class="btmbg"></div> </div>
ASP.NET MVC 手机短信验证

js:

ASP.NET MVC 手机短信验证
 //获取验证码
$(document).on("click", "#getvcode", function() {
//先验证正确的手机号
var tel = $("#regtel").val();
var btn = $(this);
var myreg = /^(((13[0-9]{1})|(15[0-9]{1})|(18[0-9]{1}))+\d{8})$/;
if (!myreg.test(tel)) {
$.alert("请输入正确的手机号码");
return false;
}
//触发后台发送
//post
$.post("/AliMessage/SendRandomCodeToMobile", { phone: tel }, function(data) {
if (data.success) { $.toast("验证码发送成功,15分钟内有效哦!");
//开始倒计时
var count = 60;
//disabled
btn.css("font-size", "1rem").val(count).attr("disabled", "disabled");
var st = setInterval(function () {
count--;
btn.val(count);
if (count <= 1) {
//恢复点击
btn.css("font-size", ".5rem").val("获取验证码").removeAttr("disabled");
clearInterval(st);
}
}, 1000); }
});
});
//验证码输入
$(document).on("keyup", ".yzmbox input", function() {
$(this).next().focus();
});
ASP.NET MVC 手机短信验证
ASP.NET MVC 手机短信验证
 var pathname = location.href;
var repath = "/";
if (pathname.indexOf("returnUrl") > -1) {
repath = pathname.split('returnUrl=')[1];
}
console.log(pathname,repath);
$(document).on("click", "#registerbt", function () {
var mobile = $("#regtel").val();
var name = $("#name").val();
var pwd = $("#regpwd").val();
var cpwd = $("#crep").val();
var code = $(".yzmbox input").eq(0).val() + $(".yzmbox input").eq(1).val() + $(".yzmbox input").eq(2).val() + $(".yzmbox input").eq(3).val();
if (!mobile) {
$.toast("请输入手机号码");
return;
}
if (!name|| !pwd) {
$.toast("请输入用户名和密码");
return;
}
if (pwd != cpwd) {
$.toast("两次输入密码不一致");
return;
}
console.log("code",code);
$.post('@Url.Action("RegisterJson")', { mobile: mobile, name: name, password: pwd, compassword: cpwd ,code:code}, function (res) {
if (res === 1) {
$.toast("注册成功");
setTimeout(function() {
location.href = repath;
}, 1000); } else {
$.toast(res);
}
});
})
ASP.NET MVC 手机短信验证

serivces:

ASP.NET MVC 手机短信验证
public class PhoneCodeSerice : IPhoneCodeSerice
{
private readonly IRepository<PhoneCode> _pRepository;
public PhoneCodeSerice(IRepository<PhoneCode> repository)
{
_pRepository = repository;
} public void Insert(PhoneCode model)
{
_pRepository.Insert(model);
} public bool Valid(string code, string phone)
{
//多长时间内有效 15分钟呢
var endTime = DateTime.Now.AddMinutes(-15);
return _pRepository.Table.Any(n => n.CreateTime >= endTime && n.Mobile == phone && n.Code == code);
}
}
ASP.NET MVC 手机短信验证

忘记密码就大同小异了

ASP.NET MVC 手机短信验证

ASP.NET MVC 手机短信验证
        public ActionResult ForgetPwdJson(string mobile,string code,string password)
{
var codevalid = _phoneCodeSerice.Valid(code, mobile);
if (!codevalid) return Json("验证码错误", JsonRequestBehavior.AllowGet); if (string.IsNullOrEmpty(password) || password.Length < 6)
{
return Json("密码不能", JsonRequestBehavior.AllowGet);
} var user = _service.GetUserByMobile(mobile);
_accountService.ChangePassword(user.Id, mobile);
AuthenticationService.SignIn(user, true); return Json(1);
}
ASP.NET MVC 手机短信验证
ASP.NET MVC 手机短信验证
 $(document).on("click", "#forgetbt", function () {
var mobile = $("#regtel").val();
var pwd = $("#regpwd").val();
var cpwd = $("#crep").val();
var code = $(".yzmbox input").eq(0).val() + $(".yzmbox input").eq(1).val() + $(".yzmbox input").eq(2).val() + $(".yzmbox input").eq(3).val();
if (!mobile) {
$.toast("请输入手机号码");
return;
}
if (pwd != cpwd) {
$.toast("两次输入密码不一致");
return;
}
console.log("code", code);
$.post('@Url.Action("ForgetPwdJson")', { mobile: mobile, code: code, password: pwd }, function (res) {
if (res === 1) {
$.toast("修改成功");
setTimeout(function () {
location.href = '@Url.Action("Index","Home")';
}, 1000);
} else {
$.toast(res);
}
});
})
ASP.NET MVC 手机短信验证