首頁 > 軟體

SpringBoot傳送簡訊驗證碼的範例

2022-02-21 16:00:38

1、註冊簡訊通賬號

網址:http://sms.webchinese.cn

2、匯入依賴

		<dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-security</artifactId>
        </dependency>
        <dependency>
            <groupId>org.thymeleaf</groupId>
            <artifactId>thymeleaf-spring5</artifactId>
        </dependency>
        <dependency>
            <groupId>org.thymeleaf.extras</groupId>
            <artifactId>thymeleaf-extras-java8time</artifactId>
        </dependency>
        <dependency>
            <groupId>org.thymeleaf.extras</groupId>
            <artifactId>thymeleaf-extras-springsecurity5</artifactId>
        </dependency>
		<!--簡訊驗證依賴匯入-->
        <dependency>
            <groupId>commons-logging</groupId>
            <artifactId>commons-logging</artifactId>
            <version>1.1.1</version>
        </dependency>
        <dependency>
            <groupId>commons-codec</groupId>
            <artifactId>commons-codec</artifactId>
            <version>1.4</version>
        </dependency>
        <dependency>
            <groupId>commons-httpclient</groupId>
            <artifactId>commons-httpclient</artifactId>
            <version>3.0.1</version>
        </dependency>

3、隨機驗證碼的工具類

public class CodeUtil {

    @Bean
    public PasswordEncoder passwordEncoder(){
        return new BCryptPasswordEncoder();
    }
    
    /**
     * 隨機生成6位驗證碼
     *
     */
    public String getRandomCode(Integer code){
        Random random = new Random();
        StringBuffer result= new StringBuffer();
        for (int i=0;i<code;i++){
            result.append(random.nextInt(10));
        }
        return result.toString();
    }
    
    //儲存驗證碼和時間
    public Code saveCode(String code){
        Code code1=new Code();
        SimpleDateFormat sf = new SimpleDateFormat("yyyyMMddHHmmss");
        Calendar c = Calendar.getInstance();
        c.add(Calendar.MINUTE, 5);
        String currentTime = sf.format(c.getTime());// 生成5分鐘後時間,使用者校驗是否過期
        //驗證碼加密
        String encode=passwordEncoder().encode(code);
        code1.setCode(encode);
        code1.setCurrentTime(currentTime);
        return code1;
    }
    
    /**
     * 解密處理
     * @param code 輸入
     * @param code1 目標
     */
    public Boolean deciphering(String code,String code1){
        boolean matches = passwordEncoder().matches(code,code1);
        return matches;
    }


}

4、簡訊傳送工具類

@Component
public class TelMessageUtil {
    private static final String SMS_Url = "http://sms.webchinese.cn/web_api/";

    /**
     * @param Uid SMS使用者id
     * @param Key 介面祕鑰:SMS登入可查(非登入密碼)
     * @param sendPhoneNum 簡訊傳送目標號碼
     * @param desc 簡訊內容
     * @return Integer(1:成功碼,其他失敗,具體參見注釋)
     */
    public static Integer send(String Uid,String Key,String sendPhoneNum,String desc){
    
        HttpClient client = new HttpClient();
        PostMethod post = new PostMethod(SMS_Url);
        post.addRequestHeader("Content-Type","application/x-www-form-urlencoded;charset=gbk");// 在標頭檔案中設定轉碼
    
        //設定引數
        NameValuePair[] data = {
                new NameValuePair("Uid", Uid),
                new NameValuePair("Key", Key),//祕鑰
                new NameValuePair("smsMob", sendPhoneNum),
                new NameValuePair("smsText", desc)
        };
    
        post.setRequestBody(data);
    
        try {
            client.executeMethod(post);
        } catch (Exception e) {  e.printStackTrace();  }


        Header[] headers = post.getResponseHeaders();
        int statusCode = post.getStatusCode();
        System.out.println("statusCode:" + statusCode);
        for (Header h : headers) {
            System.out.println(h.toString());
        }
    
        String result ="";
        try {
            result = new String(post.getResponseBodyAsString().getBytes("gbk"));
        } catch (Exception e) {  e.printStackTrace();  }
    
        post.releaseConnection();
    
        return Integer.parseInt(result);
    }
    /**
     *  -1  沒有該使用者賬戶
     -2     介面金鑰不正確 [檢視金鑰]不是賬戶登陸密碼
     -21    MD5介面金鑰加密不正確
     -3     簡訊數量不足
     -11    該使用者被禁用
     -14    簡訊內容出現非法字元
     -4     手機號格式不正確
     -41    手機號碼為空
     -42    簡訊內容為空
     -51    簡訊簽名格式不正確介面簽名格式為:【簽名內容】
     -6     IP限制
     大於0   簡訊傳送數量
     以上作為補充
     */
    public static String getMessage(Integer code){
        String message;
        if(code > 0 ) {
            message = "SMS-f傳送成功!簡訊量還有" + code + "條";
        }else if(code == -1){
            message = "SMS-沒有該使用者賬戶";
        }else if(code == -2){
            message = "SMS-介面金鑰不正確";
        }else if(code == -21){
            message = "SMS-MD5介面金鑰加密不正確";
        }else if(code == -3){
            message = "SMS-簡訊數量不足";
        }else if(code == -11){
            message = "SMS-該使用者被禁用";
        }else if(code == -14){
            message = "SMS-簡訊內容出現非法字元";
        }else if(code == -4){
            message = "SMS-手機號格式不正確";
        }else if(code == -41){
            message = "SMS-手機號碼為空";
        }else if(code == -42){
            message = "SMS-簡訊內容為空";
        }else if(code == -51){
            message = "SMS-簡訊簽名格式不正確介面簽名格式為:【簽名內容】";
        }else if(code == -6){
            message = "SMS-IP限制";
        }else{
            message = "其他錯誤";
        }
        return message;
    }


}

5、測試

	//前臺驗證手機號
    @RequestMapping("/checkTel")
    public String checkTel(@RequestParam("tel") String tel,
                           HttpSession session,
                           Model model){
        Users users=new Users();
        users.setTel(tel);
        if (loginService.CheckOnly(users)) {
            model.addAttribute("msg","沒有此使用者,請註冊!");
            return "register";
        }else {
            model.addAttribute("info","已向你的手機號為"+tel+"傳送了驗證碼");
            Long id = loginService.findIdByTel(tel);
            session.setAttribute("user_id",id);
            //傳送驗證碼
            CodeUtil codeUtil=new CodeUtil();
            //獲取六位驗證碼
            String randomCode = codeUtil.getRandomCode(6);
            //先清除session域
            session.removeAttribute("checkCode");
            //加密驗證碼存放session域中
            session.setAttribute("checkCode",codeUtil.passwordEncoder().encode(randomCode));
            Integer resultCode = TelMessageUtil.send("****","************",tel,
                    "【高校志願者平臺】你的驗證碼為【"+randomCode+"】(若不是本人操作,可忽略該條郵件)"
            );
            System.out.println("紀錄檔資訊"+resultCode);
            return "updatePwd";
        }
    }

到此這篇關於SpringBoot傳送簡訊驗證碼的範例的文章就介紹到這了,更多相關SpringBoot 簡訊驗證碼內容請搜尋it145.com以前的文章或繼續瀏覽下面的相關文章希望大家以後多多支援it145.com!


IT145.com E-mail:sddin#qq.com