SpringBoot短信验证(云之讯)

1.下载云之讯SDK。

2.将src里的文件拷贝至SpringBoot启动类同级目录。

3.将src里的config.properties剪切至SpringBoot的application.yml同级位置。

4.调整拷贝到SpringBoot的.java文件(可能会因为文件位置报错调整即可),并增加以下所需依赖。

        
        
            org.apache.httpcomponents
            httpclient
            4.4.1
        
        
            commons-lang
            commons-lang
            2.6
        
        
            log4j
            log4j
            1.2.14
        

5.打开拷贝过来的RestTest.java,这里面已经说明怎样去发送验证码了,下面这段代码便是模板单发方法,需要其他类型的短信可以参照文档截取所需代码。

try {

	String result=InstantiationRestAPI().sendSms(sid, token, appid, templateid, param, mobile, uid);

	System.out.println("Response content is: " + result);

	} catch (Exception e) {

	  e.printStackTrace();

	}

6.Controller

    /**
     * 验证码
     */
    @RequestMapping("/authCode")
    public void authCode() throws Exception {

        String sid = "";//用户的账号唯一标识“Account Sid”
        String token = "";//用户密钥“Auth Token”
        String appid = "";//创建应用时系统分配的唯一标示
        String templateid = "";//可在后台短信产品→选择接入的应用→短信模板-模板ID,查看该模板ID
        String param = generateWord();//模板中的替换参数(验证码)
        String mobile = "";//接收的单个手机号,暂仅支持国内号码
        String uid = "";//用户透传ID,随状态报告返回

        try {
            String result=new JsonReqClient().sendSms(sid, token, appid, templateid, param, mobile, uid);
            System.out.println("Response content is: " + result);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    /**
     * 产生随机的6位数字字符串
     */
    private static String generateWord() {
        int length = 6;
        String[] beforeShuffle = new String[]{"1", "2", "3", "4", "5", "6", "7", "8", "9"};
        List list = Arrays.asList(beforeShuffle);
        Collections.shuffle(list);
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < list.size(); i++) {
            sb.append(list.get(i));
        }
        String afterShuffle = sb.toString();
        return afterShuffle.substring(2, 2 + length);
    }

7.配置完后将config.properties中的is_test改为true。

8.泡壶茶,大功告成。

你可能感兴趣的:(SpringBoot短信验证(云之讯))