/**
* 获取短信验证码
* @param phone - 手机号
* @return - 发送手机验证码结果
* @author LiuDeTian at 2021-08-30
*/
@GetMapping(value = "/getAuthCode")
@ApiOperation(value = "获取验证码")
public ResultVO getAuthCode(@RequestParam String phone) {
try {
//获取redis中是否有已发送结果
long keyExpire = RedisTool.getExpireSeconds(RedisConstant.AUTH_CODE + phone);
if (keyExpire > 0) {
return ResultVO.FAIL("验证码已发送,如果未收到,请【" + keyExpire + "】秒后重新获取!", null);
}
String authCode = AliYunSmsTool.generateAuthCode(6); // 生成6位结果码
SendSmsResponseBody smsRes = AliYunSmsTool.sendSMS(phone, authCode); //发送信息
if (!"OK".equals(smsRes.getCode())) {
log.error("验证码发送失败!" + smsRes.getMessage());
return ResultVO.FAIL("验证码发送失败!" + smsRes.getMessage(), null);
}
RedisTool.set(RedisConstant.AUTH_CODE + phone, authCode, 90);
applicationContext.publishEvent(new SmsEvent(SysAuthCode.builder()
.authCode(authCode)
.mobileNum(phone)
.smsCode(smsRes.getCode())
.smsMessage(smsRes.getMessage())
.createTime(LocalDateTime.now())
.build())
);
return ResultVO.SUCCESS();
} catch (Exception e) {
e.printStackTrace();
log.error("获取验证码异常!", e);
return ResultVO.ERROR("获取验证码异常!", null);
}
}
//------------------- 工具类-------------------------------------//
@Component
public class AliYunSmsTool {
// 阿里云短信客户端
private static Client client;
// 短息模板id
private static String templateCode;
// 短信签名
private static String signName;
private static final String[] CODE_EL_ARRAY = new String[] { /*"a","b","c","d","e","f","g","h","i","g","k","l","m","n","o","p","q","r",
"s","t","u","v","w","x","y","z",*/"0","1","2","3","4","5","6","7","8","9" };
@Value("${aliYunSMS.templateCode}")
public void setTemplateCode(String value) {
templateCode = value;
}
@Value("${aliYunSMS.signName}")
public void setSignName(String value) {
signName = value;
}
/**
* 注入静态变量的值
* @param client - 阿里云短信客户端实例
* @author liudetian at 2021-08-26
*/
@Autowired
private void setClient(Client client) {
AliYunSmsTool.client = client;
}
/**
* 发送短信
* @param mobile - 手机号
* @param message - 消息
* @return - 发送结果
* @author LiuDeTian at 2021-08-26
*/
public static SendSmsResponseBody sendSMS(String mobile, String message) throws Exception {
SendSmsRequest sendSmsRequest = new SendSmsRequest()
.setPhoneNumbers(mobile)
.setSignName(signName)
.setTemplateCode(templateCode) //短信模板Id
.setTemplateParam("{\"code\":\"" + message + "\"}");
// 复制代码运行请自行打印 API 的返回值
return client.sendSms(sendSmsRequest).getBody();
}
/**
* 生成给定位数的验证码
* @param digits - 位数
* @return - 给定位数的验证码
* @author LiuDeTian at 2021-08-30
*/
public static String generateAuthCode(int digits) {
StringBuilder codeBuilder = new StringBuilder();
for (int i = 0; i < digits;i++) {
codeBuilder.append(CODE_EL_ARRAY[(int)(Math.random() * CODE_EL_ARRAY.length)]);
}
return codeBuilder.toString();
}
}
获取手机验证码
于 2022-02-15 15:00:53 首次发布