【代码模板】阿里云接口实现短信发送
Kiml Lv5
  • 前言
    阿里云接口实现短信发送。

  • 更新

1
24.05.24 初始记录

依赖

1
2
3
4
5
6
<!--sms验证服务-->  
<dependency>
<groupId>com.alibaba.cloud</groupId>
<artifactId>spring-cloud-alicloud-sms</artifactId>
<version>2.2.0.RELEASE</version>
</dependency>

代码

  1. Service 中要添加的代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
@Override  
public Boolean sendCode(String phone) {
//非空校验
if (Strings.isNullOrEmpty(phone)) {
throw new LogicException("手机号为空");
}

StringBuilder sbCode = new StringBuilder();
// 6位随机密码
Stream.generate(() -> new Random().nextInt(10))
.limit(6)
.forEach(sbCode::append);
//将验证码放入redis, 5分钟过期
redisTemplate.opsForValue().set(phone, sbCode.toString(), Duration.ofMinutes(5));
log.info("短信验证码:" + sbCode.toString());
return smsSender.sendMsg(phone, sbCode.toString());
}
  1. SmsConfig.java

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
@Configuration  
@RefreshScope
public class SmsConfig {
@Value("${sms.operator.signName}")
private String signName;
@Value("${sms.operator.templateCode}")
private String templateCode;

public String getSignName() {
return signName;
}

public String getTemplateCode() {
return templateCode;
}
}
  1. 配置文件中添加

1
2
3
4
sms:
operator:
signName: 你的signName
templateCode: 你的templateCode
  1. SmsSender.java

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
@Component  
@Slf4j
public class SmsSender {
@Autowired
private SmsConfig smsConfig;
@Autowired
private ISmsService smsService;

/**
* 发送验证码短信
*
* @param telephone 手机号
* @param code 手机验证码
*/
public boolean sendMsg(String telephone, String code) {
SendSmsRequest request = new SendSmsRequest();

request.setPhoneNumbers(telephone);
request.setSignName(smsConfig.getSignName());
request.setTemplateCode(smsConfig.getTemplateCode());
ObjectMapper mapper = new ObjectMapper();
JsonNode rootNode = mapper.createObjectNode();
// 存入验证码
((ObjectNode) rootNode).put("code", code);

try {
request.setTemplateParam(mapper.writeValueAsString(rootNode));
val sendSmsResponse = smsService.sendSmsRequest(request);
log.info("短信发送接收:" + JSONUtil.toJsonPrettyStr(sendSmsResponse));
if (sendSmsResponse.getCode() != null && "OK".equals(sendSmsResponse.getCode())) {
return true;
} else {
throw new LogicException("验证码发送失败:" + sendSmsResponse.getMessage());
}
} catch (Exception e) {
log.error("send sms error." + e.getMessage());
val operLog = OperLog.builder().title("发送验证码")
.businessType(BusinessType.OTHER.ordinal())
.operParam(JSONUtil.toJsonPrettyStr(request))
.status(BusinessStatus.FAIL.ordinal())
.errorMsg(e.getMessage())
.build();
AsyncManager.me().execute(AsyncFactory.recordOper(operLog));
throw new LogicException("验证码发送失败");
}
}
}
 评论
评论插件加载失败
正在加载评论插件
由 Hexo 驱动 & 主题 Keep
访客数 访问量