阿里云发送短信
0.阿里云文档地址
可以设置测试手机号
1.引入依赖
<dependency>
<groupId>com.aliyun</groupId>
<artifactId>aliyun-java-sdk-core</artifactId>
</dependency>
<dependency>
<groupId>com.aliyun</groupId>
<artifactId>aliyun-java-sdk-dysmsapi</artifactId>
<version>1.1.0</version>
</dependency>
2.controller层代码
// 发送短信,访问接口就向手机号发送短信,不处理任何业务
@GetMapping("/send/{phone}")
public R sendMail(@PathVariable("phone") String phoneId) {
String code = RandomUtil.getFourBitRandom();
Map<String, Object> param = new HashMap<>();
param.put("code", code);
boolean ifSuccess = msmService.sendMail(code, phoneId);
if (ifSuccess) {
return R.ok();
} else {
return R.error();
}
}
3.service层代码
@Override
public boolean sendMail(String code, String phoneId) {
String securityCode;
try {
// 查询redis中是否已经有这个手机号对应的验证码了,避免重复发送验证码
if (StringUtils.isNotEmpty(redisTemplate.opsForValue().get(phoneId))) {
return true;
}
// 发送短信
Map<String, String> map = new HashMap<>();
map.put("accessKeyId", "");//填写自己的accessKeyId
map.put("accessKeySecret", "");// 和secret
// 手机号
map.put("phoneNumbers", phoneId);
// 签名名称
map.put("signName", "阿里云短信测试");
// 模板code
map.put("templateCode", "SMS_154950909");
securityCode = RandomUtil.getFourBitRandom();
// 验证码
map.put("templateParam", "{code:" + securityCode + "}");
SendEmailUtil.sendMsg(map);
} catch (Exception e) {
e.printStackTrace();
return false;
}
redisTemplate.opsForValue().set(phoneId, securityCode, 5, TimeUnit.MINUTES);
return true;
}