asp.net mvc 接入阿里大於 短信驗證碼發送

項目前端頁面實例前端

 

 

1步:登陸阿里大於控制檯ajax

https://www.alidayu.com/center/user/account?spm=0.0.0.0.P1K1jG瀏覽器

2步:建立應用緩存

 

3步:配置短信簽名cookie

4步:配置短信模板app

5步:前端dom

 

      <tr class="margin-top">
           <td class="padding-top text-center">手機號</td>
           <td><input type="text" class="inputs" id="Phone" name="Phone"> </td>
           <td><input type="button" value="獲取驗證碼" id="sms" onclick="sendemail()"></td>
      </tr>
      <tr>
           <td class="padding-top text-center">驗證碼</td>
           <td><input type="text" class="inputs" id="Code" name="Code"></td>
       </tr>

 

6步:js處理post

$(function () {
    $("#sms").click(function () {
        sendCode($("#sms"));
    });
    v = getCookieValue("secondsremained");//獲取cookie值
    if (v > 0) {
        settime($("#sms"));//開始倒計時
    }
})

 

//發送驗證碼
function sendCode(obj) {
    var phoneNumber = $("#Phone").val();
    var result = isPhoneNum(phoneNumber);
    if (result) {
        //將手機利用ajax提交到後臺的發短信接口
        $.post("/College/Code", { Phone: phoneNumber }, function (data) {
            if (data == "ok") {
                alert("驗證碼發送成功!");
            } else {
                alert("驗證碼發送失敗,請從新發送!");
            }
        });
        addCookie("secondsremained", 60, 60);//添加cookie記錄,有效時間60s
        settime(obj);   //開始倒計時
    }
}
//開始倒計時
var countdown;
function settime(obj) {
    countdown = getCookieValue("secondsremained");
    if (countdown == 0) {
        obj.removeAttr("disabled");
        obj.val("獲取驗證碼");
        return;
    } else {
        obj.attr("disabled", true);
        obj.val("從新發送(" + countdown + ")");
        countdown--;
        editCookie("secondsremained", countdown, countdown + 1);
    }
    setTimeout(function () { settime(obj) }, 1000) //每1000毫秒執行一次
}

//校驗手機號是否合法
function isPhoneNum(phoneNumber) {
    var myreg = /^(((13[0-9]{1})|(15[0-9]{1})|(18[0-9]{1}))+\d{8})$/;
    if (!myreg.test(phoneNumber)) {
        alert('請輸入有效的手機號碼!');
        return false;
    } else {
        return true;
    }
}

//發送驗證碼時添加cookie
function addCookie(name, value, expiresHours) {
    var cookieString = name + "=" + escape(value);
    //判斷是否設置過時時間,0表明關閉瀏覽器時失效
    if (expiresHours > 0) {
        var date = new Date();
        date.setTime(date.getTime() + expiresHours * 1000);
        cookieString = cookieString + ";expires=" + date.toUTCString();
    }
    document.cookie = cookieString;
}

//修改cookie的值
function editCookie(name, value, expiresHours) {
    var cookieString = name + "=" + escape(value);
    if (expiresHours > 0) {
        var date = new Date();
        date.setTime(date.getTime() + expiresHours * 1000); //單位是毫秒
        cookieString = cookieString + ";expires=" + date.toGMTString();
    }
    document.cookie = cookieString;
}

//根據名字獲取cookie的值
function getCookieValue(name) {
    var strCookie = document.cookie;
    var arrCookie = strCookie.split("; ");
    for (var i = 0; i < arrCookie.length; i++) {
        var arr = arrCookie[i].split("=");
        if (arr[0] == name) {
            return unescape(arr[1]);
            break;
        } else {
            return "";
            break;
        }
    }
}

7步:後臺控制器處理ui

 

        #region 商學院報名發送驗證碼

        public ActionResult ValidateCode()
        {
            string Code = GetRandomString(6);
            string url = "https://eco.taobao.com/router/rest";
            string appkey = "****";  //此處填寫你本身的
            string secret = "****";   //此處填寫你本身的
            ITopClient client = new DefaultTopClient(url, appkey, secret);
            AlibabaAliqinFcSmsNumSendRequest req = new AlibabaAliqinFcSmsNumSendRequest();
            req.Extend = "";              //可空,返回狀態
            req.SmsType = "normal";             //不可更改
            req.SmsFreeSignName = "我的小站";       //申請的短信簽名,不可填寫與申請的不一
            req.SmsParam = "{VCode:'" + Code + "'}";  //模板內參數必填
            req.RecNum = Request["Phone"];         //接收者手機號碼
            req.SmsTemplateCode = "SMS_74235011";    //短信模板的編號,不可出錯
            AlibabaAliqinFcSmsNumSendResponse rsp = client.Execute(req); 

            if (rsp.IsError == false)
            {
                Console.WriteLine(rsp.Body);
                //return Content(rsp.Body);
            }

            //將驗證碼設置緩存
            var CodeInfo = (Object)Code;
            CacheOpt.SetCache("Code", CodeInfo, Convert.ToInt32(60));
            return Content("ok");
        } 

        #region 生成6位驗證碼
        public string GetRandomString(int iLength)
        {
            string buffer = "0123456789";    // 隨機字符中也能夠爲漢字(任何)
            StringBuilder sb = new StringBuilder();
            Random r = new Random();
            int range = buffer.Length;
            for (int i = 0; i < iLength; i++)
            {
                sb.Append(buffer.Substring(r.Next(range), 1));
            }
            return sb.ToString();
        }
        #endregion

 

8:緩存處理url


    public class CacheOpt
    {
        /// <summary>
        /// 設置緩存
        /// </summary>
        /// <param name="CacheKey"></param>
        /// <param name="objObject"></param>
        /// <param name="Seconds">超過多少秒後過時</param>
        public static void SetCache(string CacheKey, object objObject, long Seconds)
        {
            System.Web.Caching.Cache objCache = HttpRuntime.Cache;
            objCache.Insert(CacheKey, objObject, null, System.DateTime.Now.AddSeconds(Seconds), TimeSpan.Zero);
        }
        /// <summary>
        /// 獲取數據緩存
        /// </summary>
        /// <param name="CacheKey"></param>
        public static object GetCache(string CacheKey)
        {
            System.Web.Caching.Cache objCache = HttpRuntime.Cache;
            return objCache[CacheKey];
        }
    }

 

注:完整版項目地址:http://www.gmkcn.com/ 

相關文章
相關標籤/搜索