ElleryO

键盘上的“舞者”,伴随着嘀嗒悠然起舞.
  博客园  :: 首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理

今天 突然发神经想到要做一个发送手机验证码的功能,因为看到很多用户注册这个模块都有手机验证这个功能,于是乎,俺就上网查了很多资料,整理了一下,做了一个简单的手机验证码实现功能。不过我用的是试用账号,只可以发送30个短信,如果要更多的话,需要充值,这是我感到很遗憾的事情。下面跟着我来实现这个功能吧,大神勿喷哈。

1、首先,上互亿无线注册一个账号,http://www.ihuyi.com/,注册后你可以看到你的账号参数信息:

 

2、使用VS创建一个空的Web应用程序:

注册静态页面:index.html

  1 <!doctype html>
  2 <html xmlns="http://www.w3.org/1999/xhtml">
  3 <head>
  4     <meta http-equiv="content-type" content="text/html; charset=gb2312" />
  5     <title>demo</title>
  6     <style>
  7         h3 {
  8             display:block;
  9             width:200px;
 10             margin:30px auto;
 11             text-align:center
 12         }
 13         table {
 14             width:400px;
 15             margin:10px auto;
 16 
 17         }
 18            
 19         #codeInput {
 20             width:90px;
 21         }
 22         .la {
 23             text-align:right
 24         }
 25         .control {
 26             line-height:50px;
 27         }
 28     </style>
 29     <script type="text/javascript" src="jquery.js"></script>
 30     <script language="javascript">
 31         function get_mobile_code() {
 32 
 33             var mobile = $("#mobile").val();
 34             if (!isMobile(mobile)) {
 35                 alert("手机号码格式错误,请重新输入");
 36             }
 37             else {
 38                 $.get("Post.aspx", { mobile: jQuery.trim($("#mobile").val()) }, function (msg) {
 39                     //alert(jQuery.trim(unescape(msg)));//unescape:对已经使用escape()函数编码的字符串msg 进行解码
 40                     if (msg == "提交成功") {
 41                         RemainTime();
 42                     }
 43                     else {
 44                         alert("手机验证码发送失败");
 45                     }
 46                 });
 47             }
 48             
 49         };
 50 
 51 
 52         var iTime = 59;
 53         var Account;
 54         function RemainTime() {
 55             document.getElementById("zphone").disabled = true;
 56             var iSecond, sSecond = "", sTime = "";
 57             if (iTime >= 0) {
 58                 iSecond = parseInt(iTime % 60);
 59                 iMinute = parseInt(iTime / 60)
 60                 if (iSecond >= 0) {
 61                     if (iMinute > 0) {
 62                         sSecond = iMinute + "" + iSecond + "";
 63                     } else {
 64                         sSecond = iSecond + "";
 65                     }
 66                 }
 67                 sTime = sSecond;
 68                 if (iTime == 0) {
 69                     clearTimeout(Account);
 70                     sTime = "获取手机验证码";
 71                     iTime = 59;
 72                     document.getElementById("zphone").disabled = false;
 73                 } else {
 74                     Account = setTimeout("RemainTime()", 1000);
 75                     iTime = iTime - 1;
 76                 }
 77             } else {
 78                 sTime = "没有倒计时";
 79             }
 80             document.getElementById("zphone").value = sTime+"后重新获取";
 81         }
 82 
 83         //手机号码验证
 84         function isMobile(s) {
 85             var reg=/^((13[0-9])|(15[^4,\D])|(18[0-9]))\d{8}$/; 
 86             if (!reg.exec(s)) {
 87                 return false;
 88             }
 89             return true;
 90             
 91         }
 92     </script>
 93 </head>
 94 
 95 <body>
 96     <form  method="post"action="judgeData.aspx">
 97         <h3>发送手机验证码</h3>
 98         <table>
 99             <tr>
100                 <td class="la"><label>手机:</label></td>
101                 <td>
102                     <input id="mobile" name="phone" type="text" required="required" /><span style="color:#FF0000"> *</span>
103                     <input id="zphone" type="button" value=" 发送手机验证码 " onclick="get_mobile_code();">
104                 </td>
105             </tr>
106             <tr class="control">
107                 <td class="la"><label>验证码:</label></td>
108                 <td><input type="text" name="captcha" id="codeInput" required="required" /></td>
109             </tr>
110             <tr>
111                 <td></td>
112                 <td><input type="reset" value="重置" />
113                 <input type="submit" value="提交"/></td>
114             </tr>
115         </table>
116     </form>
117 </body>
118 </html>

 

接收index.html Ajax过来的数据,并发送验证码到指定手机上:Post.aspx.cs

 1 using System;
 2 using System.Data;
 3 using System.Configuration;
 4 using System.Collections;
 5 using System.IO;
 6 using System.Net;
 7 using System.Text;
 8 using System.Web;
 9 using System.Web.Security;
10 using System.Web.UI;
11 using System.Web.UI.WebControls;
12 using System.Web.UI.WebControls.WebParts;
13 using System.Web.UI.HtmlControls;
14 
15 public partial class Post : System.Web.UI.Page
16 {
17     public static string PostUrl = ConfigurationManager.AppSettings["WebReference.Service.PostUrl"];
18     protected void Page_Load(object sender, EventArgs e)
19     {
20         //定义你的账号密码(你在互亿无线注册的账号密码)
21         string account = "互亿无线注册的账号";
22       string password = "互亿无线注册的密码";//密码可以使用明文密码或使用32位MD5加密
23 
24         //获取Ajax传输过来的手机号码
25         string mobile = Request.QueryString["mobile"];
26 
27         //在1000-10000之间随机获取一个数值 作为你的 手机验证码
28         Random rad = new Random();
29         int mobile_code = rad.Next(1000, 10000);
30 
31         //定义发送至手机中显示的信息
32         string content = "您的验证码是:" + mobile_code + " 。请不要把验证码泄露给其他人。";
33 
34         //将你的手机号码存入Session中
35         Session["mobile"] = mobile;
36 
37         //将你的手机验证码存入Session中
38         Session["mobile_code"] = mobile_code;
39 
40         string postStrTpl = "account={0}&password={1}&mobile={2}&content={3}";
41 
42         //将账号,密码,手机号码,手机验证码等字符串进行编码,并将它们存储在字节数组postData中
43         UTF8Encoding encoding = new UTF8Encoding();
44         byte[] postData = encoding.GetBytes(string.Format(postStrTpl, account, password, mobile, content));
45 
46         //设置发送请求报文
47         HttpWebRequest myRequest = (HttpWebRequest)WebRequest.Create(PostUrl);//PostUrl在Web.config中定义
48         myRequest.Method = "POST";
49         myRequest.ContentType = "application/x-www-form-urlencoded";
50         myRequest.ContentLength = postData.Length;
51 
52         //创建流
53         Stream newStream = myRequest.GetRequestStream();
54 
55         //发送数据
56         newStream.Write(postData, 0, postData.Length);
57         newStream.Flush();
58         newStream.Close();
59 
60         //获取返回信息(xml)
61         HttpWebResponse myResponse = (HttpWebResponse)myRequest.GetResponse();
62         if (myResponse.StatusCode == HttpStatusCode.OK)
63         {
64             StreamReader reader = new StreamReader(myResponse.GetResponseStream(), Encoding.UTF8);
65 
66             
67             string res = reader.ReadToEnd();
68 
69             //获取返回枚举值
70             int len1 = res.IndexOf("</code>");
71             int len2 = res.IndexOf("<code>");
72             string code = res.Substring((len2 + 6), (len1 - len2 - 6));
73 
74             //获取返回信息
75             int len3 = res.IndexOf("</msg>");
76             int len4 = res.IndexOf("<msg>");
77             string msg = res.Substring((len4 + 5), (len3 - len4 - 5));
78             Response.Write(msg);
79 
80             Response.End();
81 
82         }
83         else
84         {
85             //访问失败
86             Response.Write("err");
87         }
88     }
89 
90    
91 
92 
93 }


Post.aspx返回的是一个XML,我们需要返回给index.html的信息的是<msg>里面的内容。

1 <?xml version=\"1.0\" encoding=\"utf-8\"?>
2     <submitresult xmlns=\"http://106.ihuyi.cn/\">
3         <code>2</code>
4         <msg>提交成功</msg>
5         <smsid>401514767</smsid>
6     </submitresult>

 

发送验证码成功后,用户输入来自手机的验证码信息,并提交到judgeData.aspx:

 1 using System;
 2 using System.Collections.Generic;
 3 using System.Linq;
 4 using System.Web;
 5 using System.Web.UI;
 6 using System.Web.UI.WebControls;
 7 
 8 namespace phoneCheckCode
 9 {
10     public partial class judgeData : System.Web.UI.Page
11     {
12         protected void Page_Load(object sender, EventArgs e)
13         {
14             if (Session["mobile"] != null && Session["mobile_code"] != null)
15             {
16                 //获取Session的数值
17                 string mobile = Session["mobile"].ToString();
18                 string mobile_code = Session["mobile_code"].ToString();
19 
20                 //获取表单传过来的值
21                 string f_mobile = Request.Form["phone"].ToString();
22                 string f_mobile_code = Request.Form["captcha"].ToString();
23                 if(f_mobile==""||f_mobile_code==""){
24                     Response.Write("<script>alert('验证失败');window.location = 'index.html';</script>");
25                 }
26                 else{
27                     if (mobile.Equals(f_mobile) && mobile_code.Equals(f_mobile_code))
28                     {
29                         Response.Write("<script>alert('验证成功');window.location = 'main.html';</script>");
30                     }
31                     else {
32                         Response.Write("<script>alert('验证失败');window.location = 'index.html';</script>");
33                     }
34                 }
35 
36                 
37             }
38             else {
39                 Response.Write("<script>alert('验证失败');window.location = 'index.html';</script>");
40             }
41             
42         }
43     }
44 }

 

Web.config配置文件

 1 <?xml version="1.0" encoding="utf-8"?>
 2 
 3 <!--
 4   有关如何配置 ASP.NET 应用程序的详细信息,请访问
 5   http://go.microsoft.com/fwlink/?LinkId=169433
 6   -->
 7 
 8 <configuration>
 9   <appSettings>
10       <add key="WebReference.Service.PostUrl" value="http://106.ihuyi.cn/webservice/sms.php?method=Submit"/>
11       <add key="WebReference.sms" value="http://106.ihuyi.cn/webservice/sms.php?smsService"/>
12     </appSettings>
13   
14     <system.web>
15       <compilation debug="true" targetFramework="4.0" />
16       
17       
18       <!--设置Session失效时间为1分钟-->
19       <sessionState mode="InProc" timeout="1"/>
20       
21     </system.web>
22 
23 </configuration>


3.最后进行测试实现:

 

 

 

好了,我只是一个小小的菜鸟,很多东西都不太懂,有什么错误或者不足请大家多多指教,谢谢啦。

2016-07-28