<dependency>
<groupId>com.qiniu</groupId>
<artifactId>qiniu-java-sdk</artifactId>
<version>7.13.0</version>
<scope>compile</scope>
</dependency>
public class SmsClient {
public static Response sendFulltextMessage(List<String> phoneList, String templetId, String ak, String sk, Map<String, String> params) throws Exception {
String[] phones = phoneList.toArray(new String[0]);
Auth auth = Auth.create(ak, sk);
SmsManager smsManager = new SmsManager(auth);
Response resp = smsManager.sendMessage(templetId, phones, params);
return resp;
}
}
/**
* 发送注册验证码
*/
@PostMapping("/send")
public R send(@RequestParam String phone) {
String expiredFlag = redisService.getCacheObject(CacheConstants.SMS_REGISTERED_CODE + phone);
if (StringUtils.isNotEmpty(expiredFlag)) {
return R.fail("请五分钟后再次发送短信");
}
Integer sendCount = redisService.getCacheObject(CacheConstants.SMS_REGISTERED_COUNT + phone);
if (sendCount != null && sendCount >= maxRegisterSendCount) {
return R.fail("您今日注册验证码短信发送次数已达上限,请明日再试");
}
String captcha = new SecureRandom().nextInt(8999) + 1000 + "";
try {
Map<String, String> params = new HashMap<String, String>();
params.put("code", captcha);
Response resp = SmsClient.sendFulltextMessage(Arrays.asList(phone), registerTempleId, accessKey, secretKey, params);
String jobId = JSON.parseObject(resp.bodyString()).getString("job_id");
if (StringUtils.isNotEmpty(jobId)) {
redisService.setCacheObject(CacheConstants.SMS_REGISTERED_CODE + phone, captcha, 5L, TimeUnit.MINUTES);
//获取当天时间最大的秒数
long lastTime = LocalDateTime.parse(LocalDate.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd 23:59:59")), DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")).toEpochSecond(ZoneOffset.of("+8"));
//获取当前时间的秒数
long startTime = LocalDateTime.now().toEpochSecond(ZoneOffset.of("+8"));
if (sendCount == null) {
sendCount = 0;
}
redisService.setCacheObject(CacheConstants.SMS_REGISTERED_COUNT + phone, sendCount + 1, (lastTime - startTime), TimeUnit.SECONDS);
log.info("手机号:{}注册短信发送成功,验证码:{}", phone, captcha);
return R.ok("短信发送成功");
} else {
log.info("手机号:{}注册短信发送失败:{}", phone, JSON.toJSONString(resp));
return R.fail("短信发送失败");
}
} catch (Exception e) {
log.error("手机号:{}短信发送失败:{}", phone, e);
return R.fail("短信发送失败");
}
}
sms:
accessKey: XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
secretKey: XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
captchaTempletId: 12321XXXXXXXXXXXXX
maxSendCount: 10