ASP.NET MVC 手機短信驗證


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

1.注冊一個應用

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

 

2.設置簽名  

配置管理-->驗證碼

簽名是出現短信內容最前面的字段,比如【xx科技】xxxx,

 這個需要審核。顯示是2小時內。

3.設置模板

模板就是用來組織短信內容的部分

4. 應用測試

完成上面3步之后,我們就可以測試下,在應用管理--應用測試   

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

測試選擇好模板,輸入簽名、電話號碼就可以發送了。

5.代碼調試

需要先下載個sdk,.net是TopSDK.dll。如果是https,對應的地址是:https://eco.taobao.com/router/rest

復制代碼
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;

        }

    }
}
復制代碼

每個號碼有流量限制:

測試的時候一小時超過7條就收不到了。發送短信的邏輯就是這么多了,如果要驗證用戶收到的驗證碼是否一致 這個就簡單了,存儲每次發送的手機號和對應的驗證碼,驗證的時候對比下就行了。然后因為該服務是一分鍾一條的,所以需要限制下兩次獲取驗證碼的間隔是1分鍾。這些邏輯都蠻簡單的。每個賬號有200條免費的可以玩。

6.用例

短信驗證可以用於注冊或者忘記密碼:

html:

復制代碼
<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>
復制代碼

js:

復制代碼
 //獲取驗證碼
        $(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();
        });
復制代碼
復制代碼
 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);
            }
        });
    })
復制代碼

serivces:

復制代碼
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);
        }
    }
復制代碼
  View Code

忘記密碼就大同小異了

 

復制代碼
        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);
        }
復制代碼
復制代碼
 $(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);
            }
        });
    })
復制代碼


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM