当前位置:   article > 正文

SpringBoot发送短信验证码_springboot 短信验证码

springboot 短信验证码

SpringBoot发送短信验证码

一、申请短信模板等信息

此处我申请的是阿里云的短信服务,登录阿里云账号号,搜索短信服务,进入控控制台,即可按自己的需求申请

二、java代码部分

1.添加依赖
<dependency>
    <groupId>com.aliyun</groupId>
    <artifactId>aliyun-java-sdk-core</artifactId>
    <version>3.0.0</version>
</dependency>
<dependency>
   <groupId>com.aliyun</groupId>
   <artifactId>aliyun-java-sdk-dysmsapi</artifactId>
   <version>2.1.0</version>
</dependency>
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10

2.编写生成随机验证码的工具类

import java.util.Random;

public class CodeUtils {
    /**
     * 随机生成验证码
     * @param length 长度为4位或者6位
     * @return
     */
    public static Integer generateValidateCode(int length){
        Integer code =null;

        //长度为4
        if(length == 4){
            //生成随机数,最大为9999
            code = new Random().nextInt(9999);
            if(code < 1000){
                //保证随机数为4位数字
                code = code + 1000;
            }
        //长度为6
        }else if(length == 6){
            //生成随机数,最大为999999
            code = new Random().nextInt(999999);
            if(code < 100000){
                //保证随机数为6位数字
                code = code + 100000;
            }
        //其他情况
        }else{
            throw new RuntimeException("只能生成4位或6位数字验证码");
        }
        return code;
    }
}
  • 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

3.编写发送短信的公用方法

//调用阿里短信模板
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.dysmsapi.model.v20170525.SendSmsRequest;
import com.aliyuncs.dysmsapi.model.v20170525.SendSmsResponse;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.profile.DefaultProfile;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

@Service
public class SendMessage {

    public boolean senSms(String phoneNum,String code){
        //第一个参数:hangzhou
        //第二个参数:AccessKey ID
        //第三个参数:secret
        DefaultProfile profile = DefaultProfile.getProfile("cn-hangzhou", "", "");
        IAcsClient client = new DefaultAcsClient(profile);
        SendSmsRequest request = new SendSmsRequest();
        request.setSysRegionId("cn-hangzhou");
        //要发送的手机号
        request.setPhoneNumbers(phoneNum);
        //设置的签名(签名管理的签名名称))
        request.setSignName("");
        //设置的模板(模板管理中的模板code)
        request.setTemplateCode("");
        //设置模板的占位符,模板中变量的实际值
        request.setTemplateParam("{\"code\":\""+ code +"\"}");
        try{
            SendSmsResponse response = client.getAcsResponse(request);
        }catch (ClientException e){
            e.printStackTrace();
        }
        return true;
    }
}
  • 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

4、编写控制层,调用发送短信的方法

@ApiOperation("发送验证码")
@GetMapping("/sendSms")
public booleansendSms(@RequestParam(name = "phoneNum")String phoneNum,HttpSession session){
    Integer code = CodeUtils.generateValidateCode(4);
    //将生成的验证码保存到session中
    session.setAttribute(phoneNum,code);
    boolean b = sendMessage.senSms(phoneNum, code.toString());
    return b;
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9

5、测试

5.1可以在启动类中配置swagger,然后进行测试,可以参考swagger文档配置
5.2可以在Apifox中进行测试。
5.3可以编写对应的单元测试,养成好习惯

@SpringBootTest
class SpringbootdemoApplicationTests {

    @Test
    void contextLoads() {
    }

}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8

6、验证码及通知短信工具类

public class MessUtils {

    /**ACCESS_KEY_ID*/
    public static final String ACCESS_KEY_ID = "";
    /**SECRET*/
    public static final String SECRET = "";
    /**REGION_ID*/
    public static final String REGION_ID = "cn-hangzhou";
    /**验证码*/
    public static final String REGIS_CODE_TEMPLATE = "";
    /**通知*/
    public static final String CHECK_REMIND_TEMPLATE = "";
    /**签名*/
    public static final String SIGN_NAME = "";

    /**
     *  @author: 
     *  @Description: 短信验证码
     */
    public static boolean sendRegisCode(String phone, String code){
        DefaultProfile profile = DefaultProfile.getProfile(REGION_ID,ACCESS_KEY_ID, SECRET);
        IAcsClient client = new DefaultAcsClient(profile);
        CommonRequest request = new CommonRequest();
        request.setMethod(MethodType.POST);
        request.setDomain("dysmsapi.aliyuncs.com");
        request.setVersion("2017-05-25");
        request.setAction("SendSms");
        request.putQueryParameter("RegionId", REGION_ID);
        request.putQueryParameter("PhoneNumbers", phone);
        request.putQueryParameter("SignName", "");
        request.putQueryParameter("TemplateCode", "");
        request.putQueryParameter("TemplateParam", "{\"code\":" + code + "}");
        try {
            CommonResponse response = client.getCommonResponse(request);
            System.out.println(response.getData());
            return true;
        } catch (com.aliyuncs.exceptions.ClientException e) {
            e.printStackTrace();
            return false;
        } catch (ClientException e) {
            e.printStackTrace();
            return false;
        }
    }

    /**
     *  @author:
     *  @Description: 保单推送提醒短信
     */
    public static boolean sendCheckRemind(String phone, String taskId, BigDecimal amount){
        DefaultProfile profile = DefaultProfile.getProfile(REGION_ID, ACCESS_KEY_ID, SECRET);
        IAcsClient client = new DefaultAcsClient(profile);
        SendSmsRequest request = new SendSmsRequest();
        request.setPhoneNumbers(phone);
        request.setSignName(SIGN_NAME);
        request.setTemplateCode(CHECK_REMIND_TEMPLATE);
        request.setTemplateParam("{\"taskId\":\""+ taskId +"\",\"amount\":\""+ amount +"\"}");
        try {
            SendSmsResponse response = client.getAcsResponse(request);
            System.out.println(new Gson().toJson(response));
            return true;
        } catch (com.aliyuncs.exceptions.ClientException e) {
            e.printStackTrace();
            return false;
        } catch (ClientException e) {
            e.printStackTrace();
            return false;
        }
    }
}
  • 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

一个在学习的开发者,勿喷,欢迎交流

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/菜鸟追梦旅行/article/detail/340068?site
推荐阅读
相关标签
  

闽ICP备14008679号