Commit 5069723d by levphon

通知服务-新增发短信接口

1 parent 76e40a50
package cn.com.glsx.notify.modules.api;
import cn.com.glsx.notify.api.NotifyCenterFeignClient;
import cn.com.glsx.notify.dto.MailTemplateMessageDTO;
import cn.com.glsx.notify.dto.request.MailMessageRequest;
import cn.com.glsx.notify.dto.request.SmsMessageRequest;
import cn.com.glsx.notify.modules.service.MailService;
import cn.com.glsx.notify.modules.service.SmsService;
import com.glsx.plat.core.web.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
......@@ -19,8 +21,8 @@ import java.util.Map;
@RequestMapping(value = "/api/notify")
public class NotifyApiController implements NotifyCenterFeignClient {
/* @Autowired
private SmsService smsService;*/
@Autowired
private SmsService smsService;
@Autowired
private MailService mailService;
......@@ -31,18 +33,18 @@ public class NotifyApiController implements NotifyCenterFeignClient {
// @Autowired
// private WeixinService weixinService;
/* @Override
@Override
@PostMapping(value = "/sendSms")
@ResponseBody
public R sendSms(@RequestBody SmsTemplateMessageDTO messageDTO) {
smsService.sendSms(messageDTO.getPhone(), messageDTO.getTemplate(), messageDTO.getArgs().values());
public R sendSms(@RequestBody SmsMessageRequest messageRequest) {
smsService.sendSms(messageRequest.getPhone(), messageRequest.getTemplate(), messageRequest.getArgs().values());
return R.ok();
}*/
}
@Override
@PostMapping(value = "/sendMail")
@ResponseBody
public R sendMail(@RequestBody MailTemplateMessageDTO messageDTO) {
public R sendMail(@RequestBody MailMessageRequest messageRequest) {
Map<String, Object> args = new HashMap<>();
args.put("arg1", "刘宇峰");
args.put("arg2", "B73493098765");
......@@ -73,14 +75,14 @@ public class NotifyApiController implements NotifyCenterFeignClient {
/**
* 邮件内容自己拼接而成发送邮件
*
* @param messageDTO 邮件接受实体类
* @param messageRequest 邮件接受实体类
* @return R
*/
@Override
@PostMapping(value = "/sendMailOnlyContent")
@ResponseBody
public R sendMailOnlyContent(@RequestBody MailTemplateMessageDTO messageDTO) {
mailService.sendSimpleMailOnlyContent(messageDTO.getTo(), messageDTO.getTitle(), messageDTO.getContent());
public R sendMailOnlyContent(@RequestBody MailMessageRequest messageRequest) {
mailService.sendSimpleMailOnlyContent(messageRequest.getTo(), messageRequest.getTitle(), messageRequest.getContent());
return R.ok();
}
}
......@@ -24,6 +24,7 @@ public class MessageLog extends BaseEntity {
private String attachment;
private String type;
@Column(name = "send_type")
private String sendType;
}
\ No newline at end of file
......@@ -3,6 +3,7 @@ package cn.com.glsx.notify.modules.entity;
import com.glsx.plat.mybatis.base.BaseEntity;
import lombok.Data;
import javax.persistence.Column;
import javax.persistence.Table;
@Data
......@@ -15,6 +16,9 @@ public class MessageTemplate extends BaseEntity {
private String content;
private String type;
@Column(name = "send_type")
private String sendType;
private Integer type;
}
\ No newline at end of file
......@@ -10,6 +10,4 @@ public interface MessageTemplateMapper extends CommonBaseMapper<MessageTemplate>
MessageTemplate findByTemplate(@Param("template") String template);
MessageTemplate findByTemplateAndType(@Param("template") String template, @Param("type") String type);
}
\ No newline at end of file
/*
package cn.com.glsx.notify.modules.service;
import cn.com.glsx.notify.modules.entity.MessageLog;
import cn.com.glsx.notify.modules.entity.MessageTemplate;
import cn.com.glsx.notify.modules.mapper.MessageLogMapper;
import cn.com.glsx.notify.modules.mapper.MessageTemplateMapper;
import cn.com.glsx.notify.modules.utils.SmsUtils;
import cn.com.glsx.notify.modules.utils.RopHttpUtil;
import com.glsx.plat.sms.properties.SMSProperties;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import javax.annotation.Resource;
import java.text.MessageFormat;
import java.util.Arrays;
import java.util.Date;
*/
/**
* 短信发送服务
*
* @author payu
*//*
*/
@Slf4j
@Service
@RefreshScope
public class SmsService {
@Autowired
private SmsUtils smsUtils;
@Resource
private SMSProperties properties;
@Autowired
private MessageLogMapper messageLogMapper;
......@@ -28,22 +40,54 @@ public class SmsService {
@Autowired
private MessageTemplateMapper messageTemplateMapper;
@Async
public void sendSms(String phone, String template, Object... arg) {
MessageTemplate mt = messageTemplateMapper.findByTemplate(template);
if (mt == null) {
log.warn("短信模板{}不存在", template);
return;
}
String content = MessageFormat.format(mt.getContent(), arg);
smsUtils.send(phone, content);
MessageLog log = new MessageLog();
log.setToUser(phone);
log.setContent(content);
log.setTemplate(template);
log.setType(mt.getType());
messageLogMapper.insert(log);
String[] phones = phone.split(";");
Arrays.asList(phones).forEach(pno -> {
sendMessage(pno, String.valueOf(mt.getType()), content);
MessageLog log = new MessageLog();
log.setToUser(pno);
log.setContent(content);
log.setTemplate(template);
log.setSendType(mt.getSendType());
log.setCreatedDate(new Date());
messageLogMapper.insert(log);
});
}
/**
* 发送短信
*
* @param phone 电话号码,批量用逗号隔开
* @param type 类型
* @param context 发送内容
*/
public void sendMessage(String phone, String type, String context) {
MultiValueMap<String, String> params = new LinkedMultiValueMap<>(5);
try {
params.add("phone", phone);
params.add("source", properties.getSource());
params.add("messageSource", properties.getSource());
params.add("type", type);
params.add("context", context);
String sendMessageMethod = "glsx.accounts.send.message";
String post = RopHttpUtil.postE(params, String.class, properties.getUrl() + "?method=" + sendMessageMethod, sendMessageMethod);
log.info("发送短信结果{}", post);
} catch (Exception e) {
log.error("发送短信到{}异常,{}", phone, e.getMessage());
}
}
}
*/
package cn.com.glsx.notify.modules.utils;
import org.apache.commons.lang.StringUtils;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.util.DefaultUriBuilderFactory;
import org.springframework.web.util.UriBuilder;
import java.net.URI;
import java.util.Map;
import java.util.Map.Entry;
/**
* @author zhouhaibao
* @version 1.0
* @description: http调用rop端服务
* @date 2021/7/30 11:26
*/
public class RopHttpUtil {
private final static String appKey = "48e5e13229b82c1b4e6e8c96151f0637";
private final static String secret = "c24619ed7fef02a0ae16328146bca5f97cc6493957a2137b";
private static void addBaseParam(MultiValueMap<String, String> paramsMap, String method) {
paramsMap.add("v", "1.0.0");
paramsMap.add("method", method);
paramsMap.add("name", "zhouhb");
}
private static void addBaseParamE(MultiValueMap<String, String> paramsMap, String method) {
paramsMap.add("v", "1.0.0");
paramsMap.add("method", method);
}
public static <T> T get(MultiValueMap<String, String> paramsMap, Class<T> responseType, String baseurl, String method) throws Exception {
addBaseParam(paramsMap, method);
MultiValueMap<String, String> params = getSysParams();
params.putAll(paramsMap);
for (Entry<String, String> entry : params.toSingleValueMap().entrySet()) {
if (StringUtils.isEmpty(entry.getValue())) {
params.remove(entry.getKey());
}
}
String sign = RopUtils.sign(params.toSingleValueMap(), secret);
params.add("sign", sign);
RestTemplate rest = new RestTemplate();
RopUriTemplateHandler uriTemplateHandler = new RopUriTemplateHandler(baseurl);
uriTemplateHandler.setDefaultUriVariables(params.toSingleValueMap());
rest.setUriTemplateHandler(uriTemplateHandler);
T forObject = rest.getForObject(baseurl, responseType, params.toSingleValueMap());
return forObject;
}
public static <T> T post(MultiValueMap<String, String> paramsMap, Class<T> responseType, String baseurl, String method) throws Exception {
addBaseParam(paramsMap, method);
MultiValueMap<String, String> params = getSysParams();
params.putAll(paramsMap);
for (Entry<String, String> entry : params.toSingleValueMap().entrySet()) {
if (StringUtils.isEmpty(entry.getValue())) {
params.remove(entry.getKey());
}
}
String sign = RopUtils.sign(params.toSingleValueMap(), secret);
params.add("sign", sign);
return new RestTemplate().postForObject(baseurl, params, responseType);
}
public static <T> T postE(MultiValueMap<String, String> paramsMap, Class<T> responseType, String baseurl, String method) throws Exception {
addBaseParamE(paramsMap, method);
MultiValueMap<String, String> params = getSysParamsE();
params.putAll(paramsMap);
for (Entry<String, String> entry : params.toSingleValueMap().entrySet()) {
if (StringUtils.isEmpty(entry.getValue())) {
params.remove(entry.getKey());
}
}
String sign = RopUtils.signByMd5(params.toSingleValueMap(), secret);
params.add("sign", sign);
return new RestTemplate().postForObject(baseurl, params, responseType);
}
public static MultiValueMap<String, String> getSysParams() {
MultiValueMap<String, String> params = new LinkedMultiValueMap<String, String>(16);
params.add("appKey", appKey);
params.add("format", "json");
return params;
}
public static MultiValueMap<String, String> getSysParamsE() {
MultiValueMap<String, String> params = new LinkedMultiValueMap<String, String>(16);
params.add("app_key", appKey);
params.add("format", "json");
params.add("timestamp", System.currentTimeMillis() + "");
return params;
}
static class RopUriTemplateHandler extends DefaultUriBuilderFactory {
public RopUriTemplateHandler(String baseUriTemplate) {
super(baseUriTemplate);
}
@Override
public URI expand(String uriTemplate, Map<String, ?> uriVars) {
UriBuilder builder = uriString(uriTemplate);
if (uriVars != null && !uriVars.isEmpty()) {
MultiValueMap<String, String> params = new LinkedMultiValueMap<String, String>();
for (Entry<String, ?> entry : uriVars.entrySet()) {
params.add(entry.getKey(), entry.getValue().toString());
}
builder.queryParams(params);
}
return builder.build(uriVars);
}
}
}
package cn.com.glsx.notify.modules.utils;
import com.glsx.plat.common.utils.MD5Util;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.security.GeneralSecurityException;
import java.security.MessageDigest;
import java.util.*;
public class RopUtils {
private static final Logger logger = LoggerFactory.getLogger(RopUtils.class);
public RopUtils() {
}
/**
* 使用<code>secret</code>对paramValues按以下算法进行签名: <br/>
* uppercase(hex(sha1(secretkey1value1key2value2...secret))
* <p>
* 需要签名的参数名
*
* @param paramValues 参数列表
* @param secret
* @return
*/
public static String signByMd5(Map<String, String> paramValues, String secret) {
return sign(paramValues, null, secret);
}
/**
* 对paramValues进行签名,其中ignoreParamNames这些参数不参与签名
*
* @param paramValues
* @param ignoreParamNames
* @param secret
* @return
*/
public static String signByMd5(Map<String, String> paramValues, List<String> ignoreParamNames, String secret) {
StringBuilder sb = new StringBuilder();
List<String> paramNames = new ArrayList<String>(paramValues.size());
paramNames.addAll(paramValues.keySet());
if (ignoreParamNames != null && ignoreParamNames.size() > 0) {
for (String ignoreParamName : ignoreParamNames) {
paramNames.remove(ignoreParamName);
}
}
Collections.sort(paramNames);
sb.append(secret);
for (String paramName : paramNames) {
sb.append(paramName).append(paramValues.get(paramName));
}
sb.append(secret);
return MD5Util.convert32(sb.toString());
}
public static String sign(Map<String, String> paramValues, String secret) {
return sign(paramValues, null, secret);
}
public static String sign(Map<String, String> paramValues, List<String> ignoreParamNames, String secret) {
try {
StringBuilder sb = new StringBuilder();
List<String> paramNames = new ArrayList(paramValues.size());
paramNames.addAll(paramValues.keySet());
Iterator var5;
String paramName;
if (ignoreParamNames != null && ignoreParamNames.size() > 0) {
var5 = ignoreParamNames.iterator();
while (var5.hasNext()) {
paramName = (String) var5.next();
paramNames.remove(paramName);
}
}
Collections.sort(paramNames);
sb.append(secret);
var5 = paramNames.iterator();
while (var5.hasNext()) {
paramName = (String) var5.next();
sb.append(paramName).append((String) paramValues.get(paramName));
}
sb.append(secret);
byte[] sha1Digest = getSHA1Digest(sb.toString());
return byte2hex(sha1Digest);
} catch (IOException var7) {
logger.info("异常信息", var7);
return null;
}
}
public static String utf8Encoding(String value, String sourceCharsetName) {
try {
return new String(value.getBytes(sourceCharsetName), "UTF-8");
} catch (UnsupportedEncodingException var3) {
throw new IllegalArgumentException(var3);
}
}
private static byte[] getSHA1Digest(String data) throws IOException {
Object var1 = null;
try {
MessageDigest md = MessageDigest.getInstance("SHA-1");
byte[] bytes = md.digest(data.getBytes("UTF-8"));
return bytes;
} catch (GeneralSecurityException var3) {
throw new IOException(var3);
}
}
private static byte[] getMD5Digest(String data) throws IOException {
Object var1 = null;
try {
MessageDigest md = MessageDigest.getInstance("MD5");
byte[] bytes = md.digest(data.getBytes("UTF-8"));
return bytes;
} catch (GeneralSecurityException var3) {
throw new IOException(var3);
}
}
private static String byte2hex(byte[] bytes) {
StringBuilder sign = new StringBuilder();
for (int i = 0; i < bytes.length; ++i) {
String hex = Integer.toHexString(bytes[i] & 255);
if (hex.length() == 1) {
sign.append("0");
}
sign.append(hex.toUpperCase());
}
return sign.toString();
}
public static String getUUID() {
UUID uuid = UUID.randomUUID();
return uuid.toString().toUpperCase();
}
}
/*
package cn.com.glsx.notify.modules.utils;
import com.alibaba.fastjson.JSONObject;
import com.glsx.plat.common.utils.HttpUtils;
import com.glsx.plat.sms.properties.SMSProperties;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Component;
import javax.annotation.Resource;
import java.util.TreeMap;
*/
/**
* @author payu
*//*
@Slf4j
@Component("smsUtils")
public class SmsUtils {
@Resource
private SMSProperties properties;
*/
/**
* 短信
*
* @param phone
* @param content
*//*
// @Async
public void send(String phone, String content) {
send(phone, content, properties.getSource());
}
*/
/**
* 短信派单
*
* @param phone
* @param content
* @param source
*//*
// @Async
public void send(String phone, String content, String source) {
TreeMap<String, Object> treeMap = new TreeMap<>();
treeMap.put("method", "glsx.message.sendmessage");
treeMap.put("format", "json");
treeMap.put("akey", properties.getAccessKeyId());
treeMap.put("v", "1.0.0");
treeMap.put("channel", "1001");
treeMap.put("lock", "2AC16F3AB37C129E273A4979FD0A46B0");
treeMap.put("source", source);
treeMap.put("type", "1");
treeMap.put("phone", phone);
treeMap.put("content", content);
treeMap.put("subcode", "");
log.info("Send Sms:" + treeMap.toString());
String url = properties.getUrl();
log.info("短信接口:" + url);
try {
String res = HttpUtils.get(url, treeMap);
log.info("Result:" + res);
if (StringUtils.isNotEmpty(res)) {
if (res.contains("<html>")) {
log.error("短信服务不可用,返回html...");
}
if (res.contains("{")) {
JSONObject jsonObject = JSONObject.parseObject(res);
String code = jsonObject.getString("code");
if (!"0".equals(code)) {
res = HttpUtils.get(url, treeMap);
log.info("Failure resend result:" + res);
}
}
} else {
log.error("短信服务不可用,返回为空");
}
} catch (IllegalStateException ex) {
if (StringUtils.isNotEmpty(url)) {
log.error("IllegalStateException", ex);
}
} catch (Exception ex) {
log.error("SendSmsException", ex);
try {
String res1 = HttpUtils.get(url, treeMap);
log.info("Exception resend result:" + res1);
} catch (Exception e) {
log.error("ReSendSmsException", ex);
}
}
}
// public static void main(String[] args) {
// SmsUtils util = new SmsUtils();
// util.send("18682185876", "您本次操作验证码为:{0},五分钟内有效。", "frms_sms_assign");
// }
}
*/
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="cn.com.glsx.notify.modules.mapper.MessageLogMapper">
<resultMap id="BaseResultMap" type="cn.com.glsx.notify.modules.entity.MessageLog">
<!--
WARNING - @mbg.generated
-->
<id column="id" jdbcType="BIGINT" property="id" />
<result column="from_user" jdbcType="VARCHAR" property="fromUser" />
<result column="to_user" jdbcType="VARCHAR" property="toUser" />
<result column="template" jdbcType="VARCHAR" property="template" />
<result column="subject" jdbcType="VARCHAR" property="subject" />
<result column="content" jdbcType="VARCHAR" property="content" />
<result column="attachment" jdbcType="VARCHAR" property="attachment" />
<result column="type" jdbcType="VARCHAR" property="type" />
<result column="del_flag" jdbcType="INTEGER" property="delFlag" />
<result column="created_date" jdbcType="TIMESTAMP" property="createdDate" />
<result column="created_by" jdbcType="INTEGER" property="createdBy" />
<result column="updated_date" jdbcType="TIMESTAMP" property="updatedDate" />
<result column="updated_by" jdbcType="INTEGER" property="updatedBy" />
</resultMap>
<sql id="Base_Column_List">
<!--
WARNING - @mbg.generated
-->
id, from_user, to_user, `template`, subject, content, attachment, `type`,
del_flag, created_date, created_by, updated_date, updated_by
</sql>
<resultMap id="BaseResultMap" type="cn.com.glsx.notify.modules.entity.MessageLog">
<!--
WARNING - @mbg.generated
-->
<id column="id" jdbcType="BIGINT" property="id"/>
<result column="from_user" jdbcType="VARCHAR" property="fromUser"/>
<result column="to_user" jdbcType="VARCHAR" property="toUser"/>
<result column="template" jdbcType="VARCHAR" property="template"/>
<result column="subject" jdbcType="VARCHAR" property="subject"/>
<result column="content" jdbcType="VARCHAR" property="content"/>
<result column="attachment" jdbcType="VARCHAR" property="attachment"/>
<result column="send_type" jdbcType="VARCHAR" property="sendType"/>
<result column="del_flag" jdbcType="INTEGER" property="delFlag"/>
<result column="created_date" jdbcType="TIMESTAMP" property="createdDate"/>
<result column="created_by" jdbcType="INTEGER" property="createdBy"/>
<result column="updated_date" jdbcType="TIMESTAMP" property="updatedDate"/>
<result column="updated_by" jdbcType="INTEGER" property="updatedBy"/>
</resultMap>
<sql id="Base_Column_List">
<!--
WARNING - @mbg.generated
-->
id, from_user, to_user, `template`, subject, content, attachment, send_type,
del_flag, created_date, created_by, updated_date, updated_by
</sql>
</mapper>
\ No newline at end of file
......@@ -9,7 +9,8 @@
<result column="template" jdbcType="VARCHAR" property="template"/>
<result column="subject" jdbcType="VARCHAR" property="subject"/>
<result column="content" jdbcType="VARCHAR" property="content"/>
<result column="type" jdbcType="VARCHAR" property="type"/>
<result column="send_type" jdbcType="VARCHAR" property="sendType"/>
<result column="type" jdbcType="INTEGER" property="type"/>
<result column="del_flag" jdbcType="INTEGER" property="delFlag"/>
<result column="created_date" jdbcType="TIMESTAMP" property="createdDate"/>
<result column="created_by" jdbcType="INTEGER" property="createdBy"/>
......@@ -20,7 +21,7 @@
<!--
WARNING - @mbg.generated
-->
id, `template`, subject, content, `type`, del_flag, created_date,
id, `template`, subject, content, send_type, `type`, del_flag, created_date,
created_by, updated_date, updated_by
</sql>
<select id="findByTemplate" resultMap="BaseResultMap">
......@@ -29,12 +30,4 @@
from t_message_template
where template = #{template}
</select>
<select id="findByTemplateAndType" resultMap="BaseResultMap">
select
<include refid="Base_Column_List"/>
from t_message_template
where template = #{template}
and type = #{type}
</select>
</mapper>
\ No newline at end of file
Markdown is supported
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!