springboot 整合阿里云短信服务

官方sdk示例地址

  1. 依赖引入
        <!-- https://mvnrepository.com/artifact/com.aliyun/dysmsapi20170525 -->
        <dependency>
            <groupId>com.aliyun</groupId>
            <artifactId>dysmsapi20170525</artifactId>
            <version>2.0.23</version>
        </dependency>
  1. 配置
aliyun:
  sms:
    endpoint: dysmsapi.aliyuncs.com
    access-key-id: LTAI5t9WVhxxxx
    access-key-secret: z6OCV3hMfxxxx
    sign-name: 短信
    # 买家报价短信模板
    quote_template-code: SMS_465896xxx
    # 买家报价短信模板 -有车牌号
    quote_template-code-plate: SMS_465911xxx
    # 卖家报价确认短信模板
    quote_confirm_template-code: SMS_465956xxx
    # 卖家报价确认短信模板
    quote_confirm_template-code-plate: SMS_465971xxx
  1. AliyunSmsService

注意sendCode方法发送不同的短信,需要修改setTemplateCode(this.quoteTemplateCode)中的TemplateCode,建议不同方法发送不同的短信

package com.vehicle.manager.core.service;

import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson.JSON;
import com.aliyun.tea.TeaException;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Service;
import com.aliyun.teaopenapi.models.Config;
import com.aliyun.dysmsapi20170525.Client;
import com.aliyun.dysmsapi20170525.models.SendSmsRequest;
import com.aliyun.dysmsapi20170525.models.SendSmsResponse;

import java.util.Map;
import java.util.Objects;


/**
 * @author zr 2024/5/13
 */
@Slf4j
@Data
@Service
@ConfigurationProperties("aliyun.sms")
public class AliyunSmsService {
    private String accessKeyId;
    private String accessKeySecret;
    private String endpoint;
    private String signName;
    private String quoteTemplateCode;
    private String quoteTemplateCodePlate;
    private String quoteConfirmTemplateCode;
    private String quoteConfirmTemplateCodePlate;

    public static Client createClient(String accessKeyId, String accessKeySecret, String endpoint)
            throws Exception {
        Config config =
                new Config()
                        // 必填,您的 AccessKey ID
                        .setAccessKeyId(accessKeyId)
                        // 必填,您的 AccessKey Secret
                        .setAccessKeySecret(accessKeySecret);
        // 访问的域名
        config.endpoint = endpoint;
        return new com.aliyun.dysmsapi20170525.Client(config);
    }

    /**
     * 发送短信验证码
     *
     * @param phone 电话号码
     * @throws Exception 短信推送异常
     */
    public boolean sendCode(String phone, Map<String,Object> param) throws Exception {
        Client client = createClient(this.accessKeyId, this.accessKeySecret, this.endpoint);
        SendSmsRequest sendSmsRequest =
                new SendSmsRequest()
                        .setSignName(this.signName)
                        // 发送不同的短信选择不同的TemplateCode
                        .setTemplateCode(this.quoteTemplateCode)
                        .setPhoneNumbers(phone)
                        .setTemplateParam(JSON.toJSONString(param));
        try {
            log.info("发送短信入参: " + JSONUtil.toJsonStr(sendSmsRequest));
            // 复制代码运行请自行打印 API 的返回值
            SendSmsResponse sendSmsResponse = client.sendSms(sendSmsRequest);
            log.info("发送短信结果: " + JSONUtil.toJsonStr(sendSmsResponse.getBody()));
            if (Objects.nonNull(sendSmsResponse) && sendSmsResponse.getBody().code.equals("OK")) {
                return Boolean.TRUE;
            }
        } catch (TeaException error) {
            // 如有需要,请打印 error
            log.error("短信推送异常结果: " + error.message);
            return Boolean.FALSE;
        } catch (Exception e) {
            TeaException error = new TeaException(e.getMessage(), e);
            // 如有需要,请打印 error
            com.aliyun.teautil.Common.assertAsString(error.message);
            log.error("短信推送异常结果: " + error.message);
            return Boolean.FALSE;
        }
        return Boolean.FALSE;
    }
}
  1. 测试

param的参数名称要与模板中的一致
image.png

package com.vehicle.manager.core;

import com.vehicle.manager.api.StartApplication;
import com.vehicle.manager.core.service.AliyunSmsService;
import lombok.extern.slf4j.Slf4j;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;

import java.util.HashMap;

/**
 * @author zr 2024/5/13
 */
@RunWith(SpringRunner.class)
@SpringBootTest(classes = StartApplication.class)
@Slf4j
public class AliyunSmsTest {
    @Autowired
    private AliyunSmsService aliyunSmsService;
    @Test
    public void name() {
        try {

            HashMap<String, Object> param = new HashMap<>();
            param.put("carModel","测试车型");
            param.put("amounts",11);
            param.put("hours",2);
            boolean b = aliyunSmsService.sendCode("1774878xxxx", param);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }

    }
}

image.png
image.png

  • 10
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值