Spring boot 集成 阿里云短信发送功能

创建一个Spring boot 项目 过程此处省略

1在pom.xml文件中加入依赖

  • 以下依赖包含项目测试用的到工具类
<dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>

        <!-- 阿里云短信包依赖 -->
        <dependency>
            <groupId>com.aliyun</groupId>
            <artifactId>aliyun-java-sdk-core</artifactId>
            <version>4.4.1</version>
        </dependency>
        <dependency>
            <groupId>com.aliyun</groupId>
            <artifactId>aliyun-java-sdk-dysmsapi</artifactId>
            <version>2.1.0</version>
        </dependency>

        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <version>1.16.20</version>
        </dependency>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <scope>test</scope>
        </dependency>

        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>fastjson</artifactId>
            <version>1.2.45</version>
        </dependency>

        <dependency>
            <groupId>cn.hutool</groupId>
            <artifactId>hutool-all</artifactId>
            <version>5.0.6</version>
        </dependency>

        <dependency>
            <groupId> org.springframework.boot </groupId>
            <artifactId> spring-boot-configuration-processor </artifactId>
            <optional> true </optional>
        </dependency>

    </dependencies>

2在application.yml 配置需要用到的账号信息

2.1accessKeyId和accessKeysecret在阿里云的—>用户信息管理—>安全信息管理 中创建

在这里插入图片描述

2.2singName和templateCode 需要在阿里云 短信服务中进行创建 并审核,具体规则官网有详解

在这里插入图片描述

sms:
  product: Dysmsapi #固定
  url: dysmsapi.aliyuncs.com #请求路径,固定
  accessKeyId: LTA**********JeKqFdL2 #阿里云账号验证id
  accessKeySecret: UUBkb***********NesozT6Ln # 阿里云验证密码
  signName: 黄淮学院软件工程 #短信签名
  templateCode: SMS_181850928 #短信模板

3 创建配置类AlySmsConfig

@Component
@PropertySource(value = {"classpath:application.yml"})
@ConfigurationProperties(prefix = "sms")
@Data
public class AlySmsConfig implements Serializable {

    private String product;

    private String url;

    private String accessKeyId;

    private String accessKeySecret;

    private String signName;

    private String templateCode;

}

4 创建发送信息的接口 AlySmsServcie

  • 两种实现方法,原理相同
public interface AlySmsServcie {

    /**
     * 方法1
     */
    void sendSms();

    /**
     * 方法2
     */
    void sendSmsTwo();

}

实现类

@Service
public class AlySmsServiceImpl implements  AlySmsServcie {

    @Autowired
    private AlySmsConfig config;

    private Logger logger = LoggerFactory.getLogger(getClass());

    public IAcsClient alySmsConfigInit() throws ClientException
    {
        //初始化acsClient
        IClientProfile profile = DefaultProfile.getProfile("cn-hangzhou",config.getAccessKeyId(),config.getAccessKeySecret());
        DefaultProfile.addEndpoint("cn-hangzhou","cn-hangzhou",config.getProduct(),config.getUrl());
        IAcsClient acsClient = new DefaultAcsClient(profile);
        return acsClient;
    }

    @Override
    public void sendSms() {
        try {
        IAcsClient acsClient = alySmsConfigInit();
        //组装请求对象
        SendSmsRequest request = new SendSmsRequest();
        //手机号,必填
        request.setPhoneNumbers("15239491151");
        //签名,必填
        request.setSignName(config.getSignName());
        //模板,必填
        request.setTemplateCode(config.getTemplateCode());
        //模板中参数,选填
        String params = "123456";
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("code",params);
        request.setTemplateParam(jsonObject.toJSONString());

        //可选:outId为提供给业务方扩展字段,最终在短信回执消息中将此值带回给调用者
        request.setOutId("thisOneId");

        //hint 此处可能会抛出异常,注意catch

            SendSmsResponse sendSmsResponse = acsClient.getAcsResponse(request);
            System.out.println(BeanUtil.beanToMap(sendSmsResponse));
            System.out.println(JSON.toJSON(sendSmsResponse));
        }catch (ClientException e)
        {
            System.out.println(e.getMessage());
        }
    }

    @Override
    public void sendSmsTwo() {

        IClientProfile profile = DefaultProfile.getProfile("cn-hangzhou",config.getAccessKeyId(),config.getAccessKeySecret());
        IAcsClient acsClient = new DefaultAcsClient(profile);

        //请求对象
        CommonRequest request =new CommonRequest();
        request.setSysMethod(MethodType.POST);
        request.setDomain(config.getUrl());
        request.setSysVersion("2017-05-25");

        //发送对象
        String phone ="15239491151";
        request.putQueryParameter("PhoneNumbers", phone);
        //  阿里云控制台签名

        request.putQueryParameter("SignName", config.getSignName());

        // 阿里云控制台模板编号

        request.putQueryParameter("TemplateCode", config.getTemplateCode());
        //系统规定参数
        request.setAction("SendSms");

        // 模板内需要填充参数信息
        //模板中参数,选填
        String params = "123456";
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("code",params);
        request.putQueryParameter("TemplateParam", jsonObject.toJSONString());
        try {
            CommonResponse response = acsClient.getCommonResponse(request);
            System.out.println(BeanUtil.beanToMap(response));
            System.out.println(JSON.toJSON(response));
        }catch (ServerException e) {
            logger.error("阿里云短信服务异常:{}", e);
        }catch (ClientException e) {
            logger.error("连接阿里云短信异常:{}", e);

        }catch (Exception e) {
            logger.error("json转换异常:{}", e);

        }
    }

}

5 测试类

@WebAppConfiguration
@RunWith(SpringJUnit4ClassRunner.class)
@SpringBootTest(classes = {AlysmsApplication.class})
public class smsTest {

    @Autowired
    private AlySmsServcie alySmsServcie;
    
    @Test
    public void alySmsTest()
    {
        alySmsServcie.sendSms();
    }

    @Test
    public void alySmsTestTwo()
    {
        alySmsServcie.sendSmsTwo();
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值