@GetMapping("/sendSms")
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;
}
#AccessKey管理里面的账号
public static String accessKeyId = "";
#AccessKey管理里面的密码第一次保存的
public static String accessKeySecret = "";
#模板名称
public static String signName = "阿里云验证码";
#模板CODE
public static String templateCode = "";
public static AjaxResult sendSmsAli(String phoneNumber, RedisCache redisCache) throws Exception {
// 生成验证码
String code = getCode();
// 短信内容使用阿里云模板规范,短信参数应该是 JSON 格式
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);
// 将验证码存入 Redis,3 分钟过期
redisCache.setCacheObject(qcode + phoneNumber, code, 3, TimeUnit.MINUTES);
// 返回成功的 AjaxResult
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; // 最小值为100000
int max = 999999; // 最大值为999999
int randomNumber = random.nextInt(max - min + 1) + min;
return String.valueOf(randomNumber);
}