发送手机短信获取验证码功能

时间:2024-02-17 12:20:05
发送手机短信获取验证码功能
2014-05-05 20:42:05
原创作品,允许转载,转载时请务必以超链接形式标明文章 原始出处 、作者信息和本声明。否则将追究法律责任。http://linhongyu.blog.51cto.com/6373370/1406867

   因为移动端的方便,现在网络上很多的网站与应用都有与实现用户手机绑定的功能。这样做的好处很多,例如账号登陆、修改密码、在线支付……等功能模块都可以与手机实时获取验证码短信结合,来确保用户的安全性操作。

   而这整功能模块的实现,我把它大致分为三个步骤:

(1)前端触发获取验证码,同步显示有效验证倒计时;

(2)后台通过代理平台发送验证短信;

(3)用户提交验证信息,后台逻辑判断处理。

 

一、首先,与大家分享下前端的实现:

wKiom1Nnc0XxcjVdAAFQar-_Rag420.jpg

如图:输入完正确的手机号码后再触发有效验证倒计时。

js代码如下(头部需引入jQuery):

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
function getCode(){
        var tel = $("#mobile").val();//获取手机号码输入框值
        var reg = /^1[3|4|5|8][0-9]\d{4,8}$/;
        if(!reg.test(tel)){ //校验手机号码格式
            alert("请先输入您的正确手机号!");
            document.form1.o_tel.focus();
            return false;
        }
        var paras = "o_tel="+tel;
        //jquery post方法同步提交
        //(提交地址;   data:返回值)
        $.post(\'<%=basePath%>mobile/sendCode?\'+paras,function(data) {
            if(data!=null&&typeof(data)!="undefined"){
                var msg = data.msg;  //返回值为json格式
                if(msg!=null&&typeof(msg)!="undefined"&&msg=="SUCCESS"){
                    get_code_time();  //发送成功则出发get_code_time()函数
                }else{
                    alert("短信验证码发送失败!请重新获取。");
                }
            }else{
                alert("短信验证码发送失败!请重新获取。");
            }
        },"json");
    }
    var wait = 120;
    function get_code_time(){
        if(wait==0){
            $("#updateverify").removeAttr("disabled");//移除获取验证码按钮的disabled属性
            $("#updateverify").val("获取验证码");
            wait = 120;
        }else{
            $("#updateverify").attr("disabled"true);//设置获取验证码按钮为不可触发
            $("#updateverify").val("剩(" + wait + ")秒");
            wait--;
            setTimeout("get_code_time()", 1000);
        }
    }

 

二、接下来我们就该在后台进行短息发送处理了(Demo是用Java整合spring MVC框架写的):

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
/**
     * 订单查询发送验证码
     * @param request
     * @param response
     * @return
     */
    @RequestMapping(value="/sendCode",method={RequestMethod.POST,RequestMethod.GET})
    public String sendCode(HttpServletRequest request,HttpServletResponse response){
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                         
        HttpSession session = request.getSession();
        String ret="";
        String o_tel = request.getParameter("o_tel");//获取前端传送过来的电话号码
        if(o_tel!=null&&o_tel!=""){
            int Random  = (int) ((Math.random()*9+1)*1000);//随机生成的4位数(验证码)
            String mes = Random+"(用于测试的验证码,两分钟内有效)【学而思博客】";//需在短信中显示的文字信息描述
            ApiSendMobile asm = new ApiSendMobile();
            String msg = asm.sendSM(o_tel, mes);//发送短信
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                             
            if("发送成功".equals(msg)){
                ret = "{\"msg\":\"SUCCESS\"}";
                //把验证码与电话号码存入session中,并设置120秒有效期限
                session.setAttribute("code", Random);
                session.setAttribute("tel", o_tel);
                session.setMaxInactiveInterval(2*60);
            }else {
                ret = "{\"msg\":\"ERROR\"}";
            }
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                             
        }else{
            ret = "{\"msg\":\"ERROR\"}";
        }
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                         
        response.setContentType("application/json;charset=UTF-8");
        PrintWriter writer = null;
        try {
            writer = response.getWriter();
        catch (IOException e) {
            e.printStackTrace();
        }
        writer.write(ret);//推送回前端
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                         
        return null;
    }

   后台的大概逻辑就是这样,不熟悉SpringMVC的请不要在意太多细节。因为接下来的才是我要说的关键点:

ApiSendMobile asm = new ApiSendMobile();

   String msg = asm.sendSM(o_tel, mes);

   嗯,没错ApiSendMobile这货是我已经封装好的一个类。先来说说目前我们常用的发送短信方法,

1、与运营商联系,调用运营商的接口,把要发送的内容与手机号给运营商,让运营商去发送。(例如Mas机平台,附上相关链接:http://blog.csdn.net/wufeishimeng/article/details/4204093

2、自己去买设备,然后在基于它进行二次开发(例如短信猫,相关链接:http://my.oschina.net/backtract/blog/133629

3、专门的短信服务公司,让后通过网络服务形式调用第三方接口发送(例如飞信)

   额,才疏学浅。目前我知道的就这三种吧,其中第一种方式是稳定快速有保障的(因为运营商们要收费),第二种就出现延迟或者遗漏现象的几率就会很大,最后一种不知道现在是否还可行了。

 

   我们言归正传,本文的例子就是用了第一种方法,上代码:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
package com.xiaoxm.util;
import java.io.BufferedReader;
import com.jasson.im.api.APIClient;
/**
 * ApiTestDemo
 */
public class ApiSendMobile
{
    private long smId = 1;
    private int smType = 0;
    private String host = "mas地址";
    private String dbName = "mas";
    private String apiId = "用户apid";
    private String name = "用户名";
    private String pwd = "密码";
    private APIClient handler = new APIClient();
    BufferedReader in = null;
                                                                                                                                                                                                               
    public ApiSendMobile()
    {
                                                                                                                                                                                                                   
    }
    public void init()
    {
        int connectRe = handler.init(host, name, pwd, apiId,dbName);
        if(connectRe == APIClient.IMAPI_SUCC)
            info("初始化成功");
        else if(connectRe == APIClient.IMAPI_CONN_ERR)
            info("连接失败");
        else if(connectRe == APIClient.IMAPI_API_ERR)
            info("apiID不存在");
        if(connectRe != APIClient.IMAPI_SUCC)
        {
            System.exit(-1);
        }
    }
                                                                                                                                                                                                               
    public void release()
    {
        handler.release();
        Thread.currentThread().interrupt();
    }
                                                                                                                                                                                                               
                                                                                                                                                                                                               
                                                                                                                                                                                                               
                                                                                                                                                                                                               
    public String  sendSM(String mobile,String sendContent)
    {
        init(); //初始化 相关参数
        String  msg = "";
        int result = 0;
        result = handler.sendSM(mobile, sendContent, smId );
        if(result == APIClient.IMAPI_SUCC)
        {     
            msg = "发送成功";
        }
        else if(result == APIClient.IMAPI_INIT_ERR)
            msg = "未初始化";
        else if(result == APIClient.IMAPI_CONN_ERR)
            msg = "数据库连接失败";
        else if(result == APIClient.IMAPI_DATA_ERR)
            msg = "参数错误";
        else if(result == APIClient.IMAPI_DATA_TOOLONG)
            msg = "消息内容太长";
        else if(result == APIClient.IMAPI_INS_ERR)
            msg = "数据库插入错误";
        else
            msg = "出现其他错误";
                                                                                                                                                                                                                   
                                                                                                                                                                                                                   
        release();  //释放资源
                                                                                                                                                                                                                   
        return msg;
    }
                                                                                                                                                                                                               
    public void error(Object obj , Throwable thr)
    {
        info(obj);
        thr.printStackTrace();
    }
    public void info(Object obj)
    {
        System.out.println(obj);
    }
                                                                                                                                                                                                               
    public void quit()
    {
        release();
        System.exit(0);
    }
}

   因为涉及到隐私,所以什么地址、用户名密码之类的,自己去向运营商联系获取吧……

   要注意哦:这个类里引入了importcom.jasson.im.api.APIClient;

   还有就是项目中也必须加一个jar包:ImApi.jar

如果有去和运营商合作的话,他们会给你文档和所需的开发包之类的,所以你大可放心。

 

   嗯,该功能模块的核心内容都已经介绍得差不多了,就只剩下用户查看短信验证信息,输入了传到后台,然后再获取刚才发送短信成功时存入session中连个值进行对比验证。我也就不在此啰嗦……


   结语:天下没有白吃的午餐,垄断行业就是屌。水平不足,文章中也许存在着许多不足之处,还望大家指点与纠正。坚持博客精神,分享是一种快乐!