Java implements Alibaba Cloud Yuntong SMS notification sending

development environment

idea + maven + jdk 1.8

Add SMS notification dependency to maven environment

<!--阿里短信服务相关jar包-->
<dependency>
    <groupId>com.aliyun</groupId>
    <artifactId>aliyun-java-sdk-core</artifactId>
    <version>4.1.0</version> <!-- 注:如提示报错,先升级基础包版,无法解决可联系技术支持 -->
</dependency>
<dependency>
    <groupId>com.aliyun</groupId>
    <artifactId>aliyun-java-sdk-dysmsapi</artifactId>
    <version>1.1.0</version>
</dependency>

Developer fixed parameters

/**
  * 产品名称: 云通信短信API产品,开发者无需替换
  */
static final String PRODUCT = "Dysmsapi";

/**
 * 产品域名,开发者无需更换
 */
static final String DOMAIN = "dysmsapi.aliyuncs.com";

/**
 * 开发者自己的AccessKeyID
 */
static final String ACCESS_KEYID = "********";

/**
 * 开发者自己的AccessKeySecret
 */
static final String ACCESSKEY_SECRET = "********";

/**
 * 短信签名--可在短信控制台中找到
 */
static final String SIGN = "****";

Parameters required to send SMS

// 接收短信的手机号
String mobile,
// 发送模板里所需的json数据
JSONObject jsonObject, 
// 短信模板,需要申请,后期根据业务务求,可将大量模板封装在一个封装类里
String templateCode

util tool class

The predecessors planted trees and later people enjoyed the shade. This tool class is based on the accumulation and summary of the predecessors (not completely copied), and you can move it down and use it directly after you understand it.

package com.maoni.ssmtest.utils.aliSmsUtil;

import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.dysmsapi.model.v20170525.SendSmsRequest;
import com.aliyuncs.dysmsapi.model.v20170525.SendSmsResponse;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.http.FormatType;
import com.aliyuncs.http.MethodType;
import com.aliyuncs.profile.DefaultProfile;
import com.aliyuncs.profile.IClientProfile;
import net.sf.json.JSONObject;

/**
 * @author ouj
 * 版本: 阿里云云通信
 * jar包: aliyun-java-sdk-core and aliyun-java-sdk-dysmsapi
 * 编码格式:UTF-8
 * 需要参数: 签名名称 / 模板code / RAM访问控制中的 AccessKeyID 和 AccessKeySecret
 */
public class aliSmsUtil {
    // 所有参数,可自定义根据需求,配置成application.properties 用@value()注入
    /**
     * 产品名称: 云通信短信API产品,开发者无需替换
     */
    static final String PRODUCT = "Dysmsapi";

    /**
     * 产品域名,开发者无需更换
     */
    static final String DOMAIN = "dysmsapi.aliyuncs.com";

    /**
     * 开发者自己的AccessKeyID
     */
    static final String ACCESS_KEYID = "********";

    /**
     * 开发者自己的AccessKeySecret
     */
    static final String ACCESSKEY_SECRET = "********";

    /**
     * 短信签名--可在短信控制台中找到
     */
    static final String SIGN = "*****";

    /**
     * IAcsClient是aliyun-java-sdk-green的Java客户端。使用aliyun-java-sdk-green Java SDK发起请求前,您需要初始化一个IAcsClient实例,并根据需要修改IClientProfile的配置项。
     */
    public IAcsClient acsClient;

    /**
     * 配置超时时间,初始化acsClient
     *
     * @return
     * @throws
     */
    public IAcsClient getInstant() throws ClientException {
        if (acsClient == null) {
            // 配置超时时间
            System.setProperty("sun.net.client.defaultConnectTimeout", "10000");
            System.setProperty("sun.net.client.defaultReadTimeout", "10000");
            //初始化acsClient,暂不支持region化
            IClientProfile profile = DefaultProfile.getProfile("cn-hangzhou", ACCESS_KEYID, ACCESSKEY_SECRET);
            DefaultProfile.addEndpoint("cn-hangzhou", "cn-hangzhou", PRODUCT, DOMAIN);
            return acsClient = new DefaultAcsClient(profile);
        }
        return acsClient;
    }

    /**
     *  创建短信发送请求
     * @param mobile        手机号
     * @param jsonObject    json数据
     * @param templateCode  短信模板
     * @return
     * @throws ClientException
     */
    public SendSmsResponse getSmsCodeClient(String mobile, JSONObject jsonObject, String templateCode) throws ClientException {
        //组装请求对象-具体描述见控制台-文档部分内容
        SendSmsRequest request = new SendSmsRequest();
        //修改数据提交方式
        request.setMethod(MethodType.POST);
        //修改数据交互格式
        request.setAcceptFormat(FormatType.JSON);
        //必填:待发送手机号
        request.setPhoneNumbers(mobile);
        //必填:短信签名-可在短信控制台中找到
        request.setSignName(SIGN);
        //必填:短信模板-可在短信控制台中找到
        request.setTemplateCode(templateCode);
        //可选:模板中的变量替换JSON串,如模板内容为"亲爱的${name},您的验证码为${code}"时,此处的值为
        request.setTemplateParam(jsonObject.toString());

        return getInstant().getAcsResponse(request);
    }

    /**
     * 发送短信
     *
     * @param mobile       手机号码
     * @param jsonObject   json数据
     * @param templateCode 短信模板
     * @return
     */
    public SendSmsResponse sendSms(String mobile, JSONObject jsonObject, String templateCode) {
        SendSmsResponse smsResponse = null;
        try{
            smsResponse = getSmsCodeClient(mobile,jsonObject,templateCode);
        } catch (ClientException e) {
            e.printStackTrace();
        }
        // 发生业务错误
        if ("isv.BUSINESS_LIMIT_CONTROL".equals(smsResponse.getCode())) {
            String message = smsResponse.getMessage();
            String limitNum = message.substring(message.length() - 1);
            if ("5".equals(limitNum)) {
                // 此处可自定义业务异常
                throw new RuntimeException("获取次数已达上线,请过一小时再试");
            } else if (limitNum.equals("0")) {
                throw new RuntimeException("获取次数已达上线,请明日再试");
            } else if (limitNum.equals("1")) {
                throw new RuntimeException("获取次数已达上线,请过一分钟再试");
            }
        }
        return smsResponse;
    }
}

test class test

package com.maoni.ssmtest.test;
import com.aliyuncs.dysmsapi.model.v20170525.SendSmsResponse;
import com.maoni.ssmtest.utils.aliSmsUtil.AliSmsUtil;
import net.sf.json.JSONObject;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

public class aliSmsTest {
    
    
    public static void main(String[] args) {
    
    

        SimpleDateFormat sdf = new SimpleDateFormat("YYYY-MM-dd");
        String sd = sdf.format(new Date());
        String phone = ""********";";
        String template = ""********";";
        String name = ""********";";
        Map map = new HashMap<>(4);
        map.put("transportNo",name);
        map.put("hour",sd);
        // 对象转json
        JSONObject jsonObject = JSONObject.fromObject(map);

        AliSmsUtil aliSmsUtil = new AliSmsUtil();
        // 发送短信
        SendSmsResponse sendSmsResponse = aliSmsUtil.sendSms(phone,jsonObject,template);
        if("OK".equals(sendSmsResponse.getCode())){
    
    
            System.out.println("发送成功");
        }else {
    
    
            System.out.println("发送失败");
        }
    }
}

DEBUG mode result

image-20211111094859022

Analyze the result of the sendSmsResponse request response and process the result according to the code status

success status:

image-20211111100925674

Guess you like

Origin blog.csdn.net/m0_49969111/article/details/121262807