mitao
2025-02-28 1af0c41885a5b6fe8f566399e5d81afd24d361ca
短信发送工具类
1个文件已修改
2个文件已添加
195 ■■■■■ 已修改文件
springcloud_k8s_panzhihuazhihuishequ/service_sangeshenbian/pom.xml 6 ●●●●● 补丁 | 查看 | 原始文档 | blame | 历史
springcloud_k8s_panzhihuazhihuishequ/service_sangeshenbian/src/main/java/com/panzhihua/sangeshenbian/config/AliSmsConfig.java 46 ●●●●● 补丁 | 查看 | 原始文档 | blame | 历史
springcloud_k8s_panzhihuazhihuishequ/service_sangeshenbian/src/main/java/com/panzhihua/sangeshenbian/utils/AliSmsUtil.java 143 ●●●●● 补丁 | 查看 | 原始文档 | blame | 历史
springcloud_k8s_panzhihuazhihuishequ/service_sangeshenbian/pom.xml
@@ -123,6 +123,12 @@
            <artifactId>javase</artifactId>
            <version>3.3.3</version>
        </dependency>
        <!--sms-->
        <dependency>
            <groupId>com.aliyun</groupId>
            <artifactId>dysmsapi20170525</artifactId>
            <version>3.1.0</version>
        </dependency>
    </dependencies>
springcloud_k8s_panzhihuazhihuishequ/service_sangeshenbian/src/main/java/com/panzhihua/sangeshenbian/config/AliSmsConfig.java
New file
@@ -0,0 +1,46 @@
package com.panzhihua.sangeshenbian.config;
import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;
@Component
@ConfigurationProperties(prefix = "sms")
@Data
public class AliSmsConfig {
    private String accessKeyId;
    private String accessKeySecret;
    /**
     * 签名
     */
    private String signName;
    /**
     * 诉求超时提醒模板编码
     */
    private String timeoutTemplateCode;
    /**
     * 诉求临期提醒模板代码
     */
    private String expireTemplateCode;
    /**
     * 连接超时ms
     */
    private String connectTimeout = "30000";
    /**
     * 读超时ms
     */
    private String readTimeout = "30000";
    /**
     * 调试状态
     */
    private boolean debug = false;
}
springcloud_k8s_panzhihuazhihuishequ/service_sangeshenbian/src/main/java/com/panzhihua/sangeshenbian/utils/AliSmsUtil.java
New file
@@ -0,0 +1,143 @@
package com.panzhihua.sangeshenbian.utils;
import cn.hutool.core.date.DateUtil;
import com.alibaba.fastjson.JSON;
import com.aliyun.dysmsapi20170525.Client;
import com.aliyun.dysmsapi20170525.models.SendBatchSmsRequest;
import com.aliyun.dysmsapi20170525.models.SendBatchSmsResponse;
import com.aliyun.dysmsapi20170525.models.SendSmsRequest;
import com.aliyun.dysmsapi20170525.models.SendSmsResponse;
import com.aliyun.teaopenapi.models.Config;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
@Slf4j
public class AliSmsUtil {
    private static final String ACCESS_KEY_ID = "LTAI5t8EwfjWRWs7tJGimAQG";
    private static final String ACCESS_KEY_SECRET = "UjuTDcXO14dSQ7STg8Pf3idjLqwx1M";
    private static final String SIGN_NAME = "花城e十";
    private static final String TIME_OUT_TEMPLATE_CODE = "SMS_479120493";
    private static final String EXPIRE_TEMPLATE_CODE = "SMS_479510160";
    /**
     * 发送诉求超时提醒短信
     * @param phoneList
     * @param title
     */
    public static void  sendTimeoutMessage(List<String> phoneList, String title) {
        Map<String, String> param = new HashMap<>(3);
        param.put("title", title);
        sendBatchSms(phoneList, SIGN_NAME, TIME_OUT_TEMPLATE_CODE, param);
    }
    /**
     * 发送诉求临期短信
     * @param phoneList
     * @param title
     * @param closingTime
     * @param days
     */
    public static void sendExpireMessage(List<String> phoneList, String title, Date closingTime, Integer days) {
        Map<String, String> param = new HashMap<>(3);
        param.put("title", title);
        param.put("time", DateUtil.format(closingTime, "yyyy-MM-dd HH:mm:ss"));
        param.put("times", String.valueOf(days));
        sendBatchSms(phoneList, SIGN_NAME, EXPIRE_TEMPLATE_CODE, param);
    }
    /**
     * 阿里发送短信
     *
     * @param phone
     * @param signName
     * @param templateCode
     * @param param
     * @return
     */
    private boolean sendSms(String phone, String signName, String templateCode, Map<String, String> param) {
        // 可自助调整超时时间
        System.setProperty("sun.net.client.defaultConnectTimeout", "30000");
        System.setProperty("sun.net.client.defaultReadTimeout", "30000");
        try {
            // 初始化请求客户端
            Client client = createClient();
            // 构造请求对象,请填入请求参数值
            SendSmsRequest sendSmsRequest = new SendSmsRequest()
                    .setPhoneNumbers(phone)
                    .setSignName(signName)
                    .setTemplateCode(templateCode)
                    .setTemplateParam(JSON.toJSONString(param));
            //if (aliSmsConfig.isDebug()) {
            //    log.info("短信 DEBUG code= {}", param);
            //    return true;
            //}
            // 获取响应对象
            SendSmsResponse sendSmsResponse = client.sendSms(sendSmsRequest);
            // hint 此处可能会抛出异常,注意catch
            if (StringUtils.equalsIgnoreCase("ok", sendSmsResponse.getBody().getCode())) {
                return true;
            } else {
                log.error("{}短信发送失败:{}", phone, sendSmsResponse.getBody().getMessage());
            }
        } catch (Exception e) {
            log.error("{}短信发送失败:{}", phone, e.getMessage(),e);
            throw new RuntimeException("短信发送失败", e);
        }
        return false;
    }
    private static boolean sendBatchSms(List<String> phones, String signName, String templateCode, Map<String, String> param) {
        // 可自助调整超时时间
        System.setProperty("sun.net.client.defaultConnectTimeout", "30000");
        System.setProperty("sun.net.client.defaultReadTimeout", "30000");
        try {
            // 初始化请求客户端
            Client client = createClient();
            // 构造请求对象,请填入请求参数值
            SendBatchSmsRequest request = new SendBatchSmsRequest()
                    .setPhoneNumberJson(JSON.toJSONString(phones)) // 手机号数组JSON
                    .setSignNameJson(JSON.toJSONString(Collections.nCopies(phones.size(), SIGN_NAME)))
                    .setTemplateCode(templateCode)
                    .setTemplateParamJson(JSON.toJSONString(Collections.nCopies(phones.size(), param))); // 参数数组JSON
            //if (aliSmsConfig.isDebug()) {
            //    log.info("短信 DEBUG code= {}", param);
            //    return true;
            //}
            // 获取响应对象
            SendBatchSmsResponse sendBatchSmsResponse = client.sendBatchSms(request);
            // hint 此处可能会抛出异常,注意catch
            if (StringUtils.equalsIgnoreCase("ok", sendBatchSmsResponse.getBody().getCode())) {
                return true;
            } else {
                log.error("{}短信发送失败:{}", JSON.toJSONString(phones), sendBatchSmsResponse.getBody().getMessage());
            }
        } catch (Exception e) {
            log.error("{}短信发送失败:{}", JSON.toJSONString(phones), e.getMessage(),e);
            throw new RuntimeException("短信发送失败", e);
        }
        return false;
    }
    public static Client createClient() throws Exception {
        Config config = new Config()
                // 配置 AccessKey ID
                .setAccessKeyId(ACCESS_KEY_ID)
                // 配置 AccessKey Secret
                .setAccessKeySecret(ACCESS_KEY_SECRET);
        // 配置 Endpoint
        config.endpoint = "dysmsapi.aliyuncs.com";
        return new Client(config);
    }
}