<!--阿里云短信验证码-->
<dependency>
<groupId>com.aliyun</groupId>
<artifactId>dysmsapi20170525</artifactId>
<version>3.0.0</version>
</dependency>
@ApiOperation("发送信息")
@GetMapping("/sendSmssendSmsAli")
public AjaxResult sendSmsAli(String phoneNum) {
AjaxResult ajaxResult = new AjaxResult();
try {
ajaxResult = SmsSendUtils.sendSmsAli(phoneNum, redisCache);
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (Exception e) {
throw new RuntimeException(e);
}
if (ajaxResult.isSuccess()) {
return AjaxResult.success();
}
return ajaxResult;
}
public static String accessKeyId = "";
public static String accessKeySecret = "";
public static String signName = "阿里云短信测试";
public static String templateCode = "SMS_154950909";
public static AjaxResult sendSmsAli(String phoneNumber, RedisCache redisCache) throws Exception {
String code = getCode();
String templateParam = String.format("{\"code\":\"%s\"}", code);
Config config = new Config()
.setAccessKeyId(accessKeyId)
.setAccessKeySecret(accessKeySecret);
config.endpoint = "dysmsapi.aliyuncs.com";
Client client = new Client(config);
SendSmsRequest sendSmsRequest = new SendSmsRequest()
.setSignName(signName)
.setTemplateCode(templateCode)
.setPhoneNumbers(phoneNumber)
.setTemplateParam(templateParam);
RuntimeOptions runtime = new RuntimeOptions();
try {
client.sendSmsWithOptions(sendSmsRequest, runtime);
System.out.println("短信发送成功"+code);
redisCache.setCacheObject(qcode + phoneNumber, code, 3, TimeUnit.MINUTES);
return AjaxResult.success(code);
} catch (Exception error) {
System.err.println("短信发送失败:" + error.getMessage());
return AjaxResult.error("短信发送失败:" + error.getMessage());
}
}
public static String getCode() {
Random random = new Random();
int min = 100000;
int max = 999999;
int randomNumber = random.nextInt(max - min + 1) + min;
return String.valueOf(randomNumber);
}