springboot使用阿里云短信

        阿里云给咱们提供了短信的功能,首先如果咱们要发送短信是要有短信的一个模板的,还有一个签名,以及咱们账号的accessKeyId,和accessKeySecret,知道这些参数咱们才好去做一个发送短信的功能,当然啦,咱们开通了阿里云的短信服务,这些参数都会有的窝~

        我已经提前封装好工具类啦,直接调用就好啦~为了代码更加的简洁,所以我还创建了一个entity用来作为咱们工具类方法的一个参数,让咱们的方法更加的简洁。

当然啦第一步还是导入咱们的依赖:

        <!--阿里云短信-->
        <dependency>
            <groupId>com.aliyun</groupId>
            <artifactId>aliyun-java-sdk-core</artifactId>
            <version>4.0.6</version>
        </dependency>
        <dependency>
            <groupId>com.aliyun</groupId>
            <artifactId>aliyun-java-sdk-dysmsapi</artifactId>
            <version>1.1.0</version>
        </dependency>
        <!--fast json-->
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>fastjson</artifactId>
            <version>1.2.75</version>
        </dependency>

entity:

import lombok.Data;

import java.io.Serializable;

/**
 * 阿里云短信信息
 * @author shenwang
 * version 1.0
 */
@Data
public class AliyunMessageInfo implements Serializable {
    /**
     * 签名
     */
    private String signName;
    /**
     * 模板编号
     */
    private String templateCode;
    /**
     * 接收短信的手机号码
     */
    private String phone;

}

后来是咱们工具类的一个代码,实现了,发送信息和批量发送。

/**
 * 阿里云短信服务,工具类
 * @author shenwang
 * @version 1.0
 */
@Component
public class AliyunTextMessageUtils {
    //accessKeyId,accessKeySecret
    static final String accessKeyId = "自己的accessKeyId";
    static final String accessKeySecret = "自己的accessKeySecret";
    static IAcsClient acsClient=null;
    static {
        //设置超时时间-可自行调整
        System.setProperty("sun.net.client.defaultConnectTimeout", "10000");
        System.setProperty("sun.net.client.defaultReadTimeout", "10000");

        //初始化ascClient需要的几个参数 短信API产品名称(短信产品名固定,无需修改)
        final String product = "Dysmsapi";
        //短信API产品域名(接口地址固定,无需修改)
        final String domain = "dysmsapi.aliyuncs.com";


        //初始化ascClient,暂时不支持多region(请勿修改)
        IClientProfile profile = DefaultProfile.getProfile("cn-hangzhou", accessKeyId,
                accessKeySecret);
        try {
            DefaultProfile.addEndpoint("cn-hangzhou", "cn-hangzhou", product, domain);
        } catch (ClientException e) {
            e.printStackTrace();
        }
        acsClient = new DefaultAcsClient(profile);
    }

    /**
     * 向某电话号码发送验证码
     * @param aliyunMessageInfo 短信基本信息
     * @param code 验证码
     * @return
     * @throws ClientException
     */
    public boolean sendMessageCode(AliyunMessageInfo aliyunMessageInfo, String code) throws ClientException {
       Map<String,Object> map=new HashMap<>();
       map.put("code",code);
       return sendMessage(aliyunMessageInfo, map);
    }

    /**
     * 发送短信
     * @param info 本条短信的信息,签名,模板编号,手机号
     * @param parameters 该短信模板对应的参数
     */
    public boolean sendMessage(AliyunMessageInfo info, Map<String,Object> parameters) throws ClientException {
        if (StringUtils.isEmpty(info.getPhone())||StringUtils.isEmpty(info.getSignName())||StringUtils.isEmpty(info.getTemplateCode())){
            return false;
        }
        //组装请求对象
        SendSmsRequest request = new SendSmsRequest();
        //使用post提交
        request.setMethod(MethodType.POST);
        //必填:待发送手机号。支持以逗号分隔的形式进行批量调用,批量上限为1000个手机号码,批量调用相对于单条调用及时性稍有延迟,验证码类型的短信推荐使用单条调用的方式;发送国际/港澳台消息时,接收号码格式为国际区号+号码,如“85200000000”
        request.setPhoneNumbers(info.getPhone());
        //必填:短信签名-可在短信控制台中找到
        request.setSignName(info.getSignName());
        //必填:短信模板-可在短信控制台中找到,发送国际/港澳台消息时,请使用国际/港澳台短信模版
        request.setTemplateCode(info.getTemplateCode());
        //可选:模板中的变量替换JSON串,如模板内容为"亲爱的${name},您的验证码为${code}"时,此处的值为
        //友情提示:如果JSON中需要带换行符,请参照标准的JSON协议对换行符的要求,比如短信内容中包含\r\n的情况在JSON中需要表示成\\r\\n,否则会导致JSON在服务端解析失败
        //参考:request.setTemplateParam("{\"变量1\":\"值1\",\"变量2\":\"值2\",\"变量3\":\"值3\"}")
        String jsonStr = JSON.toJSONString(parameters);
        System.out.println("------------------jsonStr:"+jsonStr+"-----------------------------");
        request.setTemplateParam(jsonStr);

        //请求失败这里会抛ClientException异常
        SendSmsResponse sendSmsResponse = acsClient.getAcsResponse(request);
        if(sendSmsResponse.getCode() != null && sendSmsResponse.getCode().equals("OK")) {
            //请求成功
            return true;
        }
        return false;
    }

    /**
     * 批量发送短信
     * @param phoneList
     * @param info
     * @param map
     * @return
     * @throws ClientException
     */
    public boolean batchSend(List<String> phoneList,AliyunMessageInfo info,Map<String,Object> map) throws ClientException {
            if (phoneList!=null&&phoneList.size()>0){
                StringBuffer phones=new StringBuffer();
                for (String phone:phoneList){
                    phones.append(phone+",");
                }
                info.setPhone(phones.toString().substring(0, phones.length() - 1));
                return sendMessage(info, map);
            }
            else{
                return false;
            }
    }

紧接着咱们就可以去测试啦!!!

import com.aliyuncs.exceptions.ClientException;

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.ArrayList;
import java.util.List;

/**
 * 测试阿里云短信
 * @author shenwang
 */
@RunWith(SpringRunner.class)
@SpringBootTest(classes = Application.class)
public class AliyunMessageTest {
    @Autowired
    private AliyunTextMessageUtils aliyunTextMessageUtils;
    @Test
    public void test01() throws ClientException {
        AliyunMessageInfo info=new AliyunMessageInfo();
        //发送给那个手机号
        info.setPhone("1008611");
        info.setSignName("自己的签名");
        info.setTemplateCode("模板编号");
        boolean flag = aliyunTextMessageUtils.sendMessageCode(info,"13212");
        System.out.println(flag?"发送成功":"发送失败");
    }
    @Test
    public void test02() throws ClientException {
        AliyunMessageInfo info=new AliyunMessageInfo();
        info.setSignName("自己的签名");
        info.setTemplateCode("模板编号");
        //要批量发送号码的集合
        List<String> phoneList=new ArrayList<>();
        phoneList.add("1008611");
        phoneList.add("10086");
        System.out.println(aliyunTextMessageUtils.batchSend(phoneList,info,null));
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值