阿里云发送验证码
1.工具类生成验证码
public class VerificationCodeUtil{
/**
* 六位随机数验证码
*/
public static String getVerificationCode() {
StringBuilder result = new StringBuilder();
Random random = new Random();
String[] str = {"0", "1", "2", "3", "4", "5", "6", "7", "8", "9"};
for (int i = 0; i < 6; i++) {
result.append(str[random.nextInt(10)]);
}
return result.toString();
}
}
2.短信验证码发送工具类
public class SmsUtil {
//阿里云服务KEYID
private static final String KEYID = "******************";
//阿里云服务SECRET
private static final String SECRET = "*******************";
/**
* 使用AK&SK初始化账号Client
*/
public static Client createClient(String accessKeyId, String accessKeySecret) throws Exception {
Config config = new Config()
// 必填,您的 AccessKey ID
.setAccessKeyId(accessKeyId)
// 必填,您的 AccessKey Secret
.setAccessKeySecret(accessKeySecret);
// 访问的域名
config.endpoint = "dysmsapi.aliyuncs.com";
return new Client(config);
}
/**
* 短信验证码
*
* @param phone 手机号
* @param template_code 短信模板
* @param params 模板参数
*/
public static void sendMessage(String phone, String template_code, String params) {
try {
// 创建一个短信服务客户端实例,使用预设的KEYID和SECRET进行身份认证
Client client = SmsUtil.createClient(KEYID, SECRET);
// 创建SendSmsRequest对象,设置发送短信所需参数
SendSmsRequest sendSmsRequest = new SendSmsRequest()
// 设置接收短信的手机号码
.setPhoneNumbers(phone)
// 设置模板参数,根据实际业务场景替换为动态内容
.setTemplateParam(params)
// 设置短信模板CODE
.setTemplateCode(template_code)
// 设置短信签名名称
.setSignName("短信验证码");
// 调用客户端的sendSmsWithOptions方法发送短信,并传入RuntimeOptions以配置额外的运行时选项
// 这段代码执行后会发送短信验证码到指定的手机号码上,但此处为了简洁没有打印API返回的结果
client.sendSmsWithOptions(sendSmsRequest, new RuntimeOptions());
} catch (Exception ignored) {
}
}
}
3.功能实现
@RestController
@RequestMapping(value = "/api/member")
public class VerificationCodeController {
@Resource
private RedisUtil util;
@PostMapping(value = "/sendRegisterCode")
public RespResult sendRegisterCode(@RequestParam("phone") String phone) {
//判断手机号是否注册
boolean isRegister = service.checkPhoneIsRegister(phone);
if (isRegister) {
return RespResult.builder().code(500).msg("手机号已被注册").build();
}
//获取6位随机验证码
String code = VerificationCodeUtil.getVerificationCode();
//创建一个HashMap用于存储短信验证码及其对应信息
Map<String, Object> map = new HashMap<>();
// 将生成的验证码存入map中
map.put("code", code);
// 使用SmsUtil类发送短信,其中phone参数为目标手机号,"短信模板"为短信内容模板, JSONObject.toJSONString(map)将map转为JSON字符串作为模板中的变量数据
SmsUtil.sendMessage(phone, "短信模板", JSONObject.toJSONString(map));
// 使用Redis工具类(@Resource注解注入的RedisUtil实例)将验证码和手机号作为键值对存入 Redis,并设置300秒的有效期
util.set("test:user:register:code:" + phone, code, 300);
// 返回一个包含成功信息的RespResult对象,msg字段为"发送验证码成功"
return RespResult.builder().msg("发送验证码成功").build();
}
}