c#发送短息验证码

<add key="WebReference.Service.PostUrl" value="http://106.ihuyi.cn/webservice/sms11.php?method=Submit" />

前台页面:

<input type="button" name="PassWord" id="btyzm" onclick="time(this)" value="获取验证码" />
<script type="text/javascript">
 
    var wait = 60;
    function time(o) {
        if(wait === 0) {
            o.removeAttribute("disabled");
            o.value = "获取验证码";
            wait = 60;
        } else {
            if(wait === 60) {
                o.setAttribute("disabled", true);
                var loginName = getUserInfo();
                if(loginName === "") {
                    o.removeAttribute("disabled");
                    o.value = "获取验证码";
                    return false;
                } else {
                    var obj = new Object();
                    $.InvokeAjaxV3({
                        url: "Api/V3/PhoneSMS/SendMessage",
                        data: {
                            Phone: loginName
                        },
                        async: false,
                        callBack: function(data) {
                            obj = $.StrToJson(data).Results;
                            if(obj.Status != 0) {
                                alert(obj.Msg);
                                o.removeAttribute("disabled");
                                o.value = "获取验证码";
                            }
                        }
                    });
                    if(obj.Status != 0) {
                        return false;
                    }
                }
 
            }
 
            o.value = "重新获取(" + wait + ")";
            wait--;
            setTimeout(function() {
                time(o);
            }, 1000);
        }
    }
 
    function getUserInfo() {
        var loginName = $.trim($("#LoginName").val());
        if(loginName === "") {
            alert("请输入手机号!");
            return "";
        }
        return loginName;
    }
</script>
后台开发:
/// <summary>
/// 发送短信  1失败 0 成功
/// </summary>
/// <param name="user"></param>
/// <returns></returns>
[Validation(false), Results(false), HttpPost, Route("SendMessage"), Description("发送短信  1失败 0 成功")]
public object SendMessage(SendMessage user)
{
    if (user.Phone == null || user.Phone.Length > 11)
    {
        return new {Status = 1, Msg = "手机号码不正确!"};
    }
 
    var userInfo = GetUserInfoQueryable(w => w.LoginName == user.Phone).FirstOrDefault(); ;          
    if (userInfo == null)
    {            
        return new { Status=1, Msg = "手机号码不存在" };
    }            
    DateTime time =DateTime.Now.AddMinutes(-1);
    int count = GetPhoneSmsQueryable(ex => ex.Phone == user.Phone && ex.CreateTime > time).Count();
    if (count > 0)
    {         
        return new { Status = 1, Msg = "码获验证需间隔60秒!" };
    }
    var obj = new EntityModel.T_PhoneSMS
    {
        Phone = userInfo.LoginName,
        Code = new Random().Next(100000, 999999).ToString()
    };
    DBContext.ExAdd(obj);
    //调用发送短息接口
    BaseInfoController ba = new BaseInfoController();
    ba.SendMSG("", "", new EntityModel.Custom.MSGEntity()
    {
        mobile = obj.Phone,
        content = "您的验证码是:【" + obj.Code + "】。请不要把验证码泄露给其他人!",
    });
 
    return    new { Status = 0, Msg = "成功" }; 
}
[System.Web.Http.HttpPost, System.Web.Http.Route("SendMSG"), DescriptionAttribute("发送短信")]
[NoValidationAttribute]
public string SendMSG(string format, string LoginKey, EntityModel.Custom.MSGEntity entity)
{
    try
    {
        string PostUrl = ConfigurationManager.AppSettings["WebReference.Service.PostUrl"];
        string account = "";//用户名是登录用户中心->验证码、通知短信->帐户及签名设置->APIID
        string password = ""; //密码是请登录用户中心->验证码、通知短信->帐户及签名设置->APIKEY
        string mobile = entity.mobile;
        string content = entity.content;
 
        //Session["mobile"] = mobile;
        //Session["mobile_code"] = mobile_code;
 
        string postStrTpl = "account={0}&password={1}&mobile={2}&content={3}";
 
        UTF8Encoding encoding = new UTF8Encoding();
        byte[] postData = encoding.GetBytes(string.Format(postStrTpl, account, password, mobile, content));
 
        HttpWebRequest myRequest = (HttpWebRequest)WebRequest.Create(PostUrl);
        myRequest.Method = "POST";
        myRequest.ContentType = "application/x-www-form-urlencoded";
        myRequest.ContentLength = postData.Length;
 
        Stream newStream = myRequest.GetRequestStream();
        // Send the data.
        newStream.Write(postData, 0, postData.Length);
        newStream.Flush();
        newStream.Close();
 
        HttpWebResponse myResponse = (HttpWebResponse)myRequest.GetResponse();
        if (myResponse.StatusCode == HttpStatusCode.OK)
        {
            StreamReader reader = new StreamReader(myResponse.GetResponseStream(), Encoding.UTF8);
 
            //Response.Write(reader.ReadToEnd());
 
            string res = reader.ReadToEnd();
            int len1 = res.IndexOf("</code>");
            int len2 = res.IndexOf("<code>");
            string code = res.Substring((len2 + 6), (len1 - len2 - 6));
            //Response.Write(code);
 
            int len3 = res.IndexOf("</msg>");
            int len4 = res.IndexOf("<msg>");
            string msg = res.Substring((len4 + 5), (len3 - len4 - 5));
            return msg;
 
        }
        else
        {
            return "发送失败!";
            //访问失败
        }
    }
    catch (Exception e)
    {
        throw e;
    }
}
posted @ 2019-01-14 13:56  笑兮兮  阅读(296)  评论(0编辑  收藏  举报