参考项目: RuoYi-Vue-Plus
添加依赖配置相关 配置项com.aliyun dysmsapi20170525 2.0.9
#--- # sms 短信 sms: enabled: true endpoint: "dysmsapi.aliyuncs.com" accessKeyId: XXXXXX accessKeySecret: XXXXXX signName: 阿里云短信测试相关代码 配置文件 SmsProperties 映射类
@Data
@Component
@ConfigurationProperties(prefix = "sms")
public class SmsProperties {
private Boolean enabled;
private String endpoint;
private String accessKeyId;
private String accessKeySecret;
private String signName;
}
配置类 SmsConfig
@Configuration
@ConditionalOnProperty(value = "sms.enabled", havingValue = "true")
public class SmsConfig {
@Bean
public SmsTemplate aliyunSmsTemplate(SmsProperties smsProperties) {
return new AliyunSmsTemplate(smsProperties);
}
}
模板接口类 SmsTemplate
public interface SmsTemplate {
SmsResult send(String phones, String templateId, Map param);
}
模块实现类 AliyunSmsTemplate
public class AliyunSmsTemplate implements SmsTemplate {
private SmsProperties properties;
private Client client;
@SneakyThrows(Exception.class)
public AliyunSmsTemplate(SmsProperties smsProperties) {
this.properties = smsProperties;
Config config = new Config()
// 您的AccessKey ID
.setAccessKeyId(smsProperties.getAccessKeyId())
// 您的AccessKey Secret
.setAccessKeySecret(smsProperties.getAccessKeySecret())
// 访问的域名
.setEndpoint(smsProperties.getEndpoint());
this.client = new Client(config);
}
public SmsResult send(String phones, String templateId, Map param) {
if (StringUtils.isBlank(phones)) {
throw new SmsException("手机号不能为空");
}
if (StringUtils.isBlank(templateId)) {
throw new SmsException("模板ID不能为空");
}
SendSmsRequest req = new SendSmsRequest()
.setPhoneNumbers(phones)
.setSignName(properties.getSignName())
.setTemplateCode(templateId)
.setTemplateParam(JsonUtils.toJsonString(param));
try {
SendSmsResponse resp = client.sendSms(req);
return SmsResult.builder()
.isSuccess("OK".equals(resp.getBody().getCode()))
.message(resp.getBody().getMessage())
.response(resp)
.build();
} catch (Exception e) {
throw new SmsException(e.getMessage());
}
}
}
结果类 SmsResult
@Data
@Builder
public class SmsResult {
private boolean isSuccess;
private String message;
private Object response;
}



