阿里云驗(yàn)證碼發(fā)送

實(shí)現(xiàn)阿里云的短信驗(yàn)證碼服務(wù)實(shí)現(xiàn)的功能

1.開通阿里云短信服務(wù)

添加簽名和模板

image.png

image.png

下面寫代碼來實(shí)現(xiàn)短信驗(yàn)證碼的發(fā)送

 //發(fā)送短信的方法
    @Override
    public boolean send(Map<String, Object> param, String phone) {
        if(StringUtils.isEmpty(phone)) return false;
       //申請(qǐng)oss對(duì)象的密鑰
        DefaultProfile profile =
                DefaultProfile.getProfile("default", "LTAI4G3DxLCmrmF2pD8PHc83", "WraTKDlqJFL4vaI0UCWsnZZp7R0Wk");
        IAcsClient client = new DefaultAcsClient(profile);

        //設(shè)置相關(guān)固定的參數(shù)
        CommonRequest request = new CommonRequest();
        //request.setProtocol(ProtocolType.HTTPS);
        request.setMethod(MethodType.POST);
        request.setDomain("dysmsapi.aliyuncs.com");
        request.setVersion("2017-05-25");
        request.setAction("SendSms");

        //設(shè)置發(fā)送相關(guān)的參數(shù)
        request.putQueryParameter("PhoneNumbers",phone); //手機(jī)號(hào)
        request.putQueryParameter("SignName","簽名名稱"); //申請(qǐng)阿里云 簽名名稱
        request.putQueryParameter("TemplateCode","SMS_***********"); //申請(qǐng)阿里云 模板code  SMS
        request.putQueryParameter("TemplateParam", JSONObject.toJSONString(param)); //驗(yàn)證碼數(shù)據(jù),轉(zhuǎn)換json數(shù)據(jù)傳遞

        try {
            //最終發(fā)送
            CommonResponse response = client.getCommonResponse(request);
            boolean success = response.getHttpResponse().isSuccess();
            return success;
        }catch(Exception e) {
            e.printStackTrace();
            return false;
        }

    }

controller類調(diào)用此方法


    @Autowired
    private MsmService msmService;

    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    //發(fā)送短信的方法
    @GetMapping("send/{phone}")
    public R sendMsm(@PathVariable String phone) {
        //1 從redis獲取驗(yàn)證碼,如果獲取到直接返回
        String code = redisTemplate.opsForValue().get(phone);
        if(!StringUtils.isEmpty(code)) {
            return R.ok();
        }
        //2 如果redis獲取 不到,進(jìn)行阿里云發(fā)送
        //生成隨機(jī)值,傳遞阿里云進(jìn)行發(fā)送
        code = RandomUtil.getFourBitRandom();
        Map<String,Object> param = new HashMap<>();
        param.put("code",code);
        //調(diào)用service發(fā)送短信的方法
        boolean isSend = msmService.send(param,phone);
        if(isSend) {
            //發(fā)送成功,把發(fā)送成功驗(yàn)證碼放到redis里面
            //設(shè)置有效時(shí)間
            redisTemplate.opsForValue().set(phone,code,60, TimeUnit.SECONDS);
            return R.ok();
        } else {
            return R.error().message("短信發(fā)送失敗");
        }
    }

這里使用一個(gè)工具類生成驗(yàn)證碼code,可以自己設(shè)置。使用redis存儲(chǔ)驗(yàn)證碼的有效時(shí)間。

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

友情鏈接更多精彩內(nèi)容