栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

Spring Boot 整合 阿里云短信(模板模式)

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

Spring Boot 整合 阿里云短信(模板模式)

参考项目: 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;
}
转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/930998.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号