SpringBoot发送短信验证码
一、申请短信模板等信息
此处我申请的是阿里云的短信服务,登录阿里云账号号,搜索短信服务,进入控控制台,即可按自己的需求申请
二、java代码部分
1.添加依赖
com.aliyun
aliyun-java-sdk-core
3.0.0
com.aliyun
aliyun-java-sdk-dysmsapi
2.1.0
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;
}
}
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;
}
}
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;
}
5、测试
5.1可以在启动类中配置swagger,然后进行测试,可以参考swagger文档配置。 5.2可以在Apifox中进行测试。 5.3可以编写对应的单元测试,养成好习惯
@SpringBootTest
class SpringbootdemoApplicationTests {
@Test
void contextLoads() {
}
}
一个在学习的开发者,勿喷,欢迎交流
|