springboot手機驗證碼


阿里短信平台

accessKeyId和accessKeySecret這兩個參數是需要項目組提供

 

下面是pom導入阿里的sdk包

<dependency>
    <groupId>com.aliyun</groupId>
    <artifactId>aliyun-java-sdk-core</artifactId>
    <version>4.1.0</version>
</dependency>

之后寫一個配置類 配置發送手機驗證碼的相關參數

private  static final String product = "Dysmsapi";
    //產品域名,開發者無需替換
    private  static final String domain = "dysmsapi.aliyuncs.com";

    private  static final String accessKeyId = "keyId填寫自己的";
    private  static final String accessKeySecret = "KeySercret填寫自己的";

    public SendSmsResponse sendALiSms(String telephone, String code)throws Exception{
        System.setProperty("sun.net.client.defaultConnectTimeout", "10000");
        System.setProperty("sun.net.client.defaultReadTimeout", "10000");
        //初始化acsClient,暫不支持region化
        IClientProfile profile = DefaultProfile.getProfile("cn-hangzhou", accessKeyId, accessKeySecret);
        DefaultProfile.addEndpoint("cn-hangzhou", "cn-hangzhou", product, domain);
        IAcsClient acsClient = new DefaultAcsClient(profile);
        //組裝請求對象-具體描述見控制台-文檔部分內容
        SendSmsRequest request = new SendSmsRequest();
        //必填:待發送手機號
        request.setPhoneNumbers(telephone);
        //必填:短信簽名-可在短信控制台中找到
        request.setSignName("短信簽名");
        //必填:短信模板-可在短信控制台中找到
        request.setTemplateCode("SMS_157975162");
        //可選:模板中的變量替換JSON串,如模板內容為"親愛的${name},您的驗證碼為${code}"時,此處的值為
//        request.setTemplateParam("{\"name\":\"Tom\", \"code\":\"123\"}");
        request.setTemplateParam("{\"code\":\"" + code + "\"}");
        //選填-上行短信擴展碼(無特殊需求用戶請忽略此字段)
        //request.setSmsUpExtendCode("90997");
        //可選:outId為提供給業務方擴展字段,最終在短信回執消息中將此值帶回給調用者
        request.setOutId("yourOutId");
        //hint 此處可能會拋出異常,注意catch
        SendSmsResponse sendSmsResponse = acsClient.getAcsResponse(request);
        return sendSmsResponse;

以上keyId和keySercret可以寫在配置文件里

然后可以對這個方法封裝一下 當然不封裝直接調用也可以

public SendSmsResponse sendSms(String telephone,String code)throws Exception{
    AliSmsConfig aliSmsConfig=new AliSmsConfig();
    SendSmsResponse response=aliSmsConfig.sendALiSms(telephone,code);
    return response;
}

之后寫Service層 下面直接貼出impl代碼

@Override
public int sendSms(String telephone) {
    //這里生成六位隨機數
    Integer random=(int)((Math.random()*9+1)*100000);
    String code=random.toString();
    AliSmsUtil aliSmsUtil=new AliSmsUtil();
    SendSmsResponse response = null;
    try {
        response=  aliSmsUtil.sendSms(telephone,code);
    }catch (Exception e){
        e.printStackTrace();
    }
    if (response!=null&&response.getCode().equals("OK")){
        return 0;
    }
    //TODO 在此 驗證碼應存入數據庫
    /*
     * 加一個存庫方法 用於之后驗證
     *
     */
    return 500;
}

上面那個方法生成了6位隨機數 這里根據需求生成不同長度的隨機數

最后用controller層調用service層

@Resource
SmsService smsService;

@GetMapping("/sendSms")
public CommonResult companyApproveList(@RequestParam(value = "phone") String phone) {
    //再次驗證手機號是否有誤
    if (PhoneUtil.confPhone(phone)){
        int sms=smsService.sendSms(phone);
        if (sms==0){
            return CommonResult.success(null);
        }else {
            return CommonResult.error(501,"短信發送失敗");
        }
    }else {
        return CommonResult.error(500,"請填寫正確的手機號");
    }
}

controller層: 前端傳入一個手機號 雖然這個手機號經過了前端的判斷 但是我們還是需要再次判斷一下 這里寫一個判斷手機號的方法 之后手機號都可以放進這里驗證

確定這個手機號是可用的以后就可以將這個手機號傳到service層 進行發送驗證碼

 

之后處理可以將這個驗證碼存到redis或者數據庫中 當用戶手機接收到驗證碼並填寫給前端的時候 根據存到redis/mysql中的數據 進行判斷驗證碼是否正確 等等操作

PhoneUtils.confPhone()這個方法跳過也可以 這就是一個判斷手機號是否正確的工具

public static boolean confPhone(String phone){
    if (phone.length() != 11)
    {
        return false;
    }else{
        /**
         * 移動號段正則表達式
         */
        String pat1 = "^((13[4-9])|(147)|(15[0-2,7-9])|(178)|(18[2-4,7-8]))\\d{8}|(1705)\\d{7}$";
        /**
         * 聯通號段正則表達式
         */
        String pat2  = "^((13[0-2])|(145)|(15[5-6])|(176)|(18[5,6]))\\d{8}|(1709)\\d{7}$";
        /**
         * 電信號段正則表達式
         */
        String pat3  = "^((133)|(153)|(177)|(18[0,1,9])|(149))\\d{8}$";
        /**
         * 虛擬運營商正則表達式
         */

        String pat4 = "^((170))\\d{8}|(1718)|(1719)\\d{7}$";

        Pattern pattern1 = Pattern.compile(pat1);
        Matcher match1 = pattern1.matcher(phone);
        boolean isMatch1 = match1.matches();
        if(isMatch1){
            return true;
        }
        Pattern pattern2 = Pattern.compile(pat2);
        Matcher match2 = pattern2.matcher(phone);
        boolean isMatch2 = match2.matches();
        if(isMatch2){
            return true;
        }
        Pattern pattern3 = Pattern.compile(pat3);
        Matcher match3 = pattern3.matcher(phone);
        boolean isMatch3 = match3.matches();
        if(isMatch3){
            return true;
        }
        Pattern pattern4 = Pattern.compile(pat4);
        Matcher match4 = pattern4.matcher(phone);
        boolean isMatch4 = match4.matches();
        if(isMatch4){
            return true;
        }
        return false;
    }
}

這個工具的返回值是boolean 調用這個方法就是判斷手機號是否正確 如果正確我就可以進行下一步的操作 如果錯誤就返回給前端 這個手機號是錯誤的


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM