Commit 2cfade2a by xinlaa

Merge branch 'master' of https://gitee.com/LinkWeChat/link-wechat into master

2 parents 194fdd80 2b6827f1
Showing 24 changed files with 825 additions and 99 deletions
package com.linkwechat.web.controller.wecom;
import com.alibaba.fastjson.JSONObject;
import com.linkwechat.common.utils.wecom.WxCryptUtil;
import com.linkwechat.web.controller.common.CommonController;
import com.linkwechat.wecom.domain.vo.WxCpXmlMessageVO;
import com.linkwechat.wecom.factory.WeCallBackEventFactory;
import com.linkwechat.wecom.factory.WeEventHandle;
import com.thoughtworks.xstream.XStream;
import com.thoughtworks.xstream.security.AnyTypePermission;
import lombok.extern.slf4j.Slf4j;
import me.chanjar.weixin.common.util.xml.XStreamInitializer;
import me.chanjar.weixin.cp.bean.WxCpXmlMessage;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import javax.servlet.http.HttpServletRequest;
/**
* @author sxw
* @description 企微回调通知接口
* @date 2020/11/6 17:31
**/
@Slf4j
@RestController
@RequestMapping("/wecom/callback")
public class WeCallBackController extends CommonController {
@Autowired
private WeEventHandle weEventHandle;
@Value("${wecome.callBack.appIdOrCorpId}")
private String appIdOrCorpId;
@Value("${wecome.callBack.token}")
private String token;
@Value("${wecome.callBack.encodingAesKey}")
private String encodingAesKey;
@PostMapping(value = "/recive", produces = {"application/xml;charset=UTF-8"})
public String recive(@RequestBody String msg, @RequestParam(name = "msg_signature") String signature,
String timestamp, String nonce) {
WxCryptUtil wxCryptUtil = new WxCryptUtil(token, encodingAesKey, appIdOrCorpId);
try {
String decrypt = wxCryptUtil.decrypt(signature, timestamp, nonce, msg);
WxCpXmlMessageVO wxCpXmlMessage = StrXmlToBean(decrypt);
log.info("企微回调通知接口 wxCpXmlMessage:{}", JSONObject.toJSONString(wxCpXmlMessage));
try {
WeCallBackEventFactory factory = weEventHandle.factory(wxCpXmlMessage.getEvent());
if (factory !=null){
factory.eventHandle(wxCpXmlMessage);
}
} catch (Exception e) {
e.printStackTrace();
}
return decrypt;
} catch (Exception e) {
e.printStackTrace();;
String sRespData = WxCryptUtil.getTextRespData("success");
return wxCryptUtil.encrypt(sRespData);
}
}
@GetMapping(value = "/recive", produces = {"application/xml;charset=UTF-8"})
public String recive(HttpServletRequest request) {
// 微信加密签名
String sVerifyMsgSig = request.getParameter("msg_signature");
// 时间戳
String sVerifyTimeStamp = request.getParameter("timestamp");
// 随机数
String sVerifyNonce = request.getParameter("nonce");
// 随机字符串
String sVerifyEchoStr = request.getParameter("echostr");
WxCryptUtil wxCryptUtil = new WxCryptUtil(token, encodingAesKey, appIdOrCorpId);
try {
return wxCryptUtil.verifyURL(sVerifyMsgSig, sVerifyTimeStamp, sVerifyNonce, sVerifyEchoStr);
} catch (Exception e) {
return "error";
}
}
private WxCpXmlMessageVO StrXmlToBean(String xmlStr){
XStream xstream = XStreamInitializer.getInstance();
xstream.addPermission(AnyTypePermission.ANY);
xstream.processAnnotations(WxCpXmlMessage.class);
xstream.processAnnotations(WxCpXmlMessageVO.class);
xstream.processAnnotations(WxCpXmlMessageVO.ScanCodeInfo.class);
xstream.processAnnotations(WxCpXmlMessageVO.SendPicsInfo.class);
xstream.processAnnotations(WxCpXmlMessageVO.SendPicsInfo.Item.class);
xstream.processAnnotations(WxCpXmlMessageVO.SendLocationInfo.class);
xstream.processAnnotations(WxCpXmlMessageVO.BatchJob.class);
WxCpXmlMessageVO wxCpXmlMessage = (WxCpXmlMessageVO)xstream.fromXML(xmlStr);
return wxCpXmlMessage;
}
}
...@@ -66,7 +66,8 @@ public class WeMessagePushController extends BaseController { ...@@ -66,7 +66,8 @@ public class WeMessagePushController extends BaseController {
@Log(title = "消息发送的", businessType = BusinessType.INSERT) @Log(title = "消息发送的", businessType = BusinessType.INSERT)
@PostMapping(value = "add") @PostMapping(value = "add")
public AjaxResult add(@RequestBody WeMessagePush weMessagePush) { public AjaxResult add(@RequestBody WeMessagePush weMessagePush) {
return toAjax(weMessagePushService.insertWeMessagePush(weMessagePush)); weMessagePushService.insertWeMessagePush(weMessagePush);
return AjaxResult.success();
} }
/** /**
......
...@@ -158,4 +158,8 @@ wecome: ...@@ -158,4 +158,8 @@ wecome:
fileUplodUrl: /media/upload,/media/uploadimg fileUplodUrl: /media/upload,/media/uploadimg
needProviderTokenUrl: needProviderTokenUrl:
- /service/get_login_info - /service/get_login_info
#企微回调通知配置
callBack:
appIdOrCorpId: ww24262ce93851488f
token: jtQ1aGHgSmH2UHNBIndUtUe6B6EwfR
encodingAesKey: Vga4HWv7nFbRDYK8iAaQbxmkuecpo2BAfmXAyWwcXMO
\ No newline at end of file \ No newline at end of file
...@@ -192,8 +192,23 @@ ...@@ -192,8 +192,23 @@
<artifactId>cglib-nodep</artifactId> <artifactId>cglib-nodep</artifactId>
<version>3.2.4</version> <version>3.2.4</version>
</dependency> </dependency>
<dependency>
<groupId>com.thoughtworks.xstream</groupId>
<artifactId>xstream</artifactId>
<version>1.4.11.1</version>
</dependency>
<dependency>
<groupId>org.dom4j</groupId>
<artifactId>dom4j</artifactId>
<version>2.1.3</version>
</dependency>
<!--动态添加属性和方法结束--> <!--动态添加属性和方法结束-->
<dependency>
<groupId>com.github.binarywang</groupId>
<artifactId>weixin-java-cp</artifactId>
<version>3.9.0</version>
</dependency>
</dependencies> </dependencies>
</project> </project>
\ No newline at end of file \ No newline at end of file
package com.linkwechat.common.constant; package com.linkwechat.common.constant;
import java.util.HashMap;
import java.util.Map;
/** /**
* @description: 企业微信相关常量 * @description: 企业微信相关常量
* @author: HaoN * @author: HaoN
...@@ -171,5 +174,70 @@ public class WeConstans { ...@@ -171,5 +174,70 @@ public class WeConstans {
public static final String COMMA = ","; public static final String COMMA = ",";
public static final String USER_ID = "userid"; public static final String USER_ID = "userid";
public static final String CURSOR = "cursor"; public static final String CURSOR = "cursor";
public static final String CORPID = "CORP_ID";
/**
* 企微回调事件类型路由
*/
public final static Map<String, String> eventRoute = new HashMap<String, String>() {
{
//成员事件
put("change_contact", "weEventChangeContactImpl");
//异步任务完成通知
put("batch_job_result", "weEventBatchJobResultImpl");
//外部联系人事件
put("change_external_contact", "weEventChangeExternalContactImpl");
}
};
//性别,1表示男性,2表示女性
//表示所在部门是否为上级,0-否,1-是,顺序与Department字段的部门逐一对应
//激活状态:1=已激活 2=已禁用 4=未激活 已激活代表已激活企业微信或已关注微工作台(原企业号) 5=成员退出
public static enum corpUserEnum {
User_SEX_TYPE_MAN(1, "男性"),
User_SEX_TYPE_WEMAN(2, "女性"),
IS_DEPARTMENT_SUPERIOR_YES(1, "是"),
IS_DEPARTMENT_SUPERIOR_NO(0, "否"),
ACTIVE_STATE_ONE(1, "已激活"),
ACTIVE_STATE_TWO(2, "已禁用"),
ACTIVE_STATE_FOUR(4, "未激活"),
ACTIVE_STATE_FIVE(5, "成员退出");
private int key;
private String value;
/**
* 构造方法
*
* @param key
* @param value
*/
corpUserEnum(int key, String value) {
this.setKey(key);
this.setValue(value);
}
public int getKey() {
return key;
}
public void setKey(int key) {
this.key = key;
}
public String getValue() {
return value;
}
public void setValue(String value) {
this.value = value;
}
}
} }
...@@ -152,4 +152,13 @@ public class DateUtils extends org.apache.commons.lang3.time.DateUtils ...@@ -152,4 +152,13 @@ public class DateUtils extends org.apache.commons.lang3.time.DateUtils
// long sec = diff % nd % nh % nm / ns; // long sec = diff % nd % nh % nm / ns;
return day + "天" + hour + "小时" + min + "分钟"; return day + "天" + hour + "小时" + min + "分钟";
} }
/**
* 计算两个时间差
*/
public static long diffTime(Date endDate, Date nowDate){
return endDate.getTime() - nowDate.getTime();
}
} }
package com.linkwechat.common.utils.wecom;
import java.util.ArrayList;
public class ByteGroup {
ArrayList<Byte> byteContainer = new ArrayList<>();
public byte[] toBytes() {
byte[] bytes = new byte[this.byteContainer.size()];
for (int i = 0; i < this.byteContainer.size(); i++) {
bytes[i] = this.byteContainer.get(i);
}
return bytes;
}
public ByteGroup addBytes(byte[] bytes) {
for (byte b : bytes) {
this.byteContainer.add(b);
}
return this;
}
public int size() {
return this.byteContainer.size();
}
}
/*
* 对公众平台发送给公众账号的消息加解密示例代码.
*
* @copyright Copyright (c) 1998-2014 Tencent Inc.
*/
package com.linkwechat.common.utils.wecom;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.util.Arrays;
/**
* 提供基于PKCS7算法的加解.
*
* @author tencent
*/
public class PKCS7Encoder {
private static final Charset CHARSET = StandardCharsets.UTF_8;
private static final int BLOCK_SIZE = 32;
/**
* 获得对明文进行补位填充的字节.
*
* @param count 需要进行填充补位操作的明文字节个数
* @return 补齐用的字节数组
*/
public static byte[] encode(int count) {
// 计算需要填充的位数
int amountToPad = BLOCK_SIZE - (count % BLOCK_SIZE);
// 获得补位所用的字符
char padChr = chr(amountToPad);
StringBuilder tmp = new StringBuilder();
for (int index = 0; index < amountToPad; index++) {
tmp.append(padChr);
}
return tmp.toString().getBytes(CHARSET);
}
/**
* 删除解密后明文的补位字符.
*
* @param decrypted 解密后的明文
* @return 删除补位字符后的明文
*/
public static byte[] decode(byte[] decrypted) {
int pad = decrypted[decrypted.length - 1];
if (pad < 1 || pad > 32) {
pad = 0;
}
return Arrays.copyOfRange(decrypted, 0, decrypted.length - pad);
}
/**
* 将数字转化成ASCII码对应的字符,用于对明文进行补码.
*
* @param a 需要转化的数字
* @return 转化得到的字符
*/
private static char chr(int a) {
byte target = (byte) (a & 0xFF);
return (char) target;
}
}
package com.linkwechat.common.utils.wecom;
import com.linkwechat.common.exception.wecom.WeComException;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.lang3.StringUtils;
import java.security.MessageDigest;
import java.util.Arrays;
/**
*
* @author Daniel Qian
* @date 14/10/19
*/
public class SHA1 {
/**
* 串接arr参数,生成sha1 digest.
*/
public static String gen(String... arr) {
if (StringUtils.isAnyEmpty(arr)) {
throw new IllegalArgumentException("非法请求参数,有部分参数为空 : " + Arrays.toString(arr));
}
Arrays.sort(arr);
StringBuilder sb = new StringBuilder();
for (String a : arr) {
sb.append(a);
}
return DigestUtils.sha1Hex(sb.toString());
}
/**
* 用&串接arr参数,生成sha1 digest.
*/
public static String genWithAmple(String... arr) {
if (StringUtils.isAnyEmpty(arr)) {
throw new IllegalArgumentException("非法请求参数,有部分参数为空 : " + Arrays.toString(arr));
}
Arrays.sort(arr);
StringBuilder sb = new StringBuilder();
for (int i = 0; i < arr.length; i++) {
String a = arr[i];
sb.append(a);
if (i != arr.length - 1) {
sb.append('&');
}
}
return DigestUtils.sha1Hex(sb.toString());
}
public static String getSHA1(String token, String timestamp, String nonce, String encrypt) throws WeComException {
try {
String[] array = new String[]{token, timestamp, nonce, encrypt};
StringBuffer sb = new StringBuffer();
Arrays.sort(array);
for(int i = 0; i < 4; ++i) {
sb.append(array[i]);
}
String str = sb.toString();
MessageDigest md = MessageDigest.getInstance("SHA-1");
md.update(str.getBytes());
byte[] digest = md.digest();
StringBuffer hexstr = new StringBuffer();
String shaHex = "";
for(int i = 0; i < digest.length; ++i) {
shaHex = Integer.toHexString(digest[i] & 255);
if (shaHex.length() < 2) {
hexstr.append(0);
}
hexstr.append(shaHex);
}
return hexstr.toString();
} catch (Exception var12) {
var12.printStackTrace();
throw new WeComException("sha加密生成签名失败");
}
}
}
...@@ -113,6 +113,7 @@ public class SecurityConfig extends WebSecurityConfigurerAdapter ...@@ -113,6 +113,7 @@ public class SecurityConfig extends WebSecurityConfigurerAdapter
.antMatchers("/webjars/**").anonymous() .antMatchers("/webjars/**").anonymous()
.antMatchers("/*/api-docs").anonymous() .antMatchers("/*/api-docs").anonymous()
.antMatchers("/druid/**").anonymous() .antMatchers("/druid/**").anonymous()
.antMatchers("/wecom/callback/**").anonymous()
// 除上面外的所有请求全部需要鉴权认证 // 除上面外的所有请求全部需要鉴权认证
.anyRequest().authenticated() .anyRequest().authenticated()
.and() .and()
......
...@@ -82,4 +82,9 @@ public class WeMessagePush extends BaseEntity { ...@@ -82,4 +82,9 @@ public class WeMessagePush extends BaseEntity {
*/ */
private String chatId; private String chatId;
/**
* 设置时间(格式为: 2020-11-17 09:00:00 ) 为空时立即发送
*/
private String settingTime;
} }
package com.linkwechat.wecom.domain.vo;
import com.thoughtworks.xstream.annotations.XStreamAlias;
import com.thoughtworks.xstream.annotations.XStreamConverter;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import me.chanjar.weixin.common.util.XmlUtils;
import me.chanjar.weixin.common.util.xml.XStreamCDataConverter;
import me.chanjar.weixin.cp.bean.WxCpXmlMessage;
import me.chanjar.weixin.cp.util.xml.XStreamTransformer;
import java.io.Serializable;
/**
* 微信推送过来的消息,也是同步回复给用户的消息,xml格式
*
* @author sxw
* @description
* @date 2020/11/10 10:29
**/
@Data
@Slf4j
@XStreamAlias("xml")
public class WxCpXmlMessageVO extends WxCpXmlMessage {
@XStreamAlias("Alias")
@XStreamConverter(value = XStreamCDataConverter.class)
private String alias;
@XStreamAlias("BatchJob")
private BatchJob batchJob = new BatchJob();
@Data
public static class BatchJob implements Serializable {
private static final long serialVersionUID = -3418685294606228837L;
@XStreamAlias("JobId")
@XStreamConverter(value = XStreamCDataConverter.class)
private String jobId;
@XStreamAlias("JobType")
@XStreamConverter(value = XStreamCDataConverter.class)
private String jobType;
@XStreamAlias("ErrCode")
private Integer errCode;
@XStreamAlias("ErrMsg")
@XStreamConverter(value = XStreamCDataConverter.class)
private String errMsg;
}
public static WxCpXmlMessageVO fromXml(String xml) {
//修改微信变态的消息内容格式,方便解析
//xml = xml.replace("</PicList><PicList>", "");
final WxCpXmlMessageVO xmlPackage = XStreamTransformer.fromXml(WxCpXmlMessageVO.class, xml);
xmlPackage.setAllFieldsMap(XmlUtils.xml2Map(xml));
return xmlPackage;
}
}
package com.linkwechat.wecom.factory;
import com.linkwechat.wecom.domain.vo.WxCpXmlMessageVO;
import org.springframework.stereotype.Service;
/**
* @author sxw
* @description 企微回调工厂接口
* @date 2020/11/9 17:12
**/
@Service
public interface WeCallBackEventFactory {
public void eventHandle(WxCpXmlMessageVO message);
}
package com.linkwechat.wecom.factory;
import com.linkwechat.common.constant.WeConstans;
import me.chanjar.weixin.cp.bean.WxCpXmlMessage;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.Map;
/**
* @author sxw
* @description 企微回调策略
* @date 2020/11/8 17:17
**/
@Service
public class WeEventHandle {
@Autowired
private Map<String, WeCallBackEventFactory> weCallBackEventFactoryMap;
public WeCallBackEventFactory factory(String eventType) {
if (!WeConstans.eventRoute.containsKey(eventType)) {
return null;
}
String resolveClass = WeConstans.eventRoute.get(eventType);
if (!weCallBackEventFactoryMap.containsKey(resolveClass)) {
return null;
}
return weCallBackEventFactoryMap.get(resolveClass);
}
}
package com.linkwechat.wecom.factory.impl;
import com.linkwechat.wecom.domain.vo.WxCpXmlMessageVO;
import com.linkwechat.wecom.factory.WeCallBackEventFactory;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
/**
* @author sxw
* @description 异步任务完成通知
* @date 2020/11/9 14:40
**/
@Service
@Slf4j
public class WeEventBatchJobResultImpl implements WeCallBackEventFactory {
@Override
public void eventHandle(WxCpXmlMessageVO message) {
String jobType = message.getBatchJob().getJobType();
switch (jobType){
case "sync_user"://增量更新成员)
break;
case "replace_user"://全量覆盖成员
break;
case "invite_user"://邀请成员关注
break;
case "replace_party"://全量覆盖部门
break;
}
}
}
package com.linkwechat.wecom.factory.impl;
import com.linkwechat.common.utils.StringUtils;
import com.linkwechat.wecom.domain.vo.WxCpXmlMessageVO;
import com.linkwechat.wecom.factory.WeCallBackEventFactory;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
/**
* @author sxw
* @description 外部联系人回调事件处理
* @date 2020/11/9 14:52
**/
@Service
@Slf4j
public class WeEventChangeExternalContactImpl implements WeCallBackEventFactory {
@Override
public void eventHandle(WxCpXmlMessageVO message) {
String changeType = message.getChangeType();
switch (changeType){
case "add_external_contact"://添加企业客户事件
addExternalContact(message);
break;
case "edit_external_contact"://编辑企业客户事件
editExternalContact(message);
break;
case "add_half_external_contact"://外部联系人免验证添加成员事件
addHalfExternalContact(message);
break;
case "del_external_contact"://删除企业客户事件
delExternalContact(message);
break;
case "del_follow_user"://删除跟进成员事件
delFollowUser(message);
break;
case "transfer_fail"://客户接替失败事件
transferFail(message);
break;
default:
break;
}
String chatId = message.getChatId();
if (StringUtils.isNotEmpty(chatId)){
//客户群变更事件
weChatChangeEvent(message);
}
}
private void weChatChangeEvent(WxCpXmlMessageVO message) {
}
private void transferFail(WxCpXmlMessageVO message) {
}
private void delFollowUser(WxCpXmlMessageVO message) {
}
private void delExternalContact(WxCpXmlMessageVO message) {
}
private void addHalfExternalContact(WxCpXmlMessageVO message) {
}
private void editExternalContact(WxCpXmlMessageVO message) {
}
private void addExternalContact(WxCpXmlMessageVO message) {
}
}
...@@ -33,7 +33,7 @@ public interface IWeMessagePushService { ...@@ -33,7 +33,7 @@ public interface IWeMessagePushService {
* @param weMessagePush 消息发送的 * @param weMessagePush 消息发送的
* @return 结果 * @return 结果
*/ */
public int insertWeMessagePush(WeMessagePush weMessagePush); public void insertWeMessagePush(WeMessagePush weMessagePush);
/** /**
* 批量删除消息发送的 * 批量删除消息发送的
......
package com.linkwechat.wecom.service.impl; package com.linkwechat.wecom.service.impl;
import cn.hutool.core.collection.CollectionUtil; import cn.hutool.core.date.DateUtil;
import cn.hutool.json.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper; import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.linkwechat.common.constant.WeConstans;
import com.linkwechat.common.enums.MessageType;
import com.linkwechat.common.enums.PushType; import com.linkwechat.common.enums.PushType;
import com.linkwechat.common.exception.wecom.WeComException;
import com.linkwechat.common.utils.DateUtils; import com.linkwechat.common.utils.DateUtils;
import com.linkwechat.common.utils.ReflectUtil;
import com.linkwechat.common.utils.SnowFlakeUtil;
import com.linkwechat.common.utils.StringUtils;
import com.linkwechat.wecom.client.WeMessagePushClient;
import com.linkwechat.wecom.domain.WeGroup;
import com.linkwechat.wecom.domain.WeMessagePush; import com.linkwechat.wecom.domain.WeMessagePush;
import com.linkwechat.wecom.domain.dto.WeMessagePushDto;
import com.linkwechat.wecom.domain.dto.WeMessagePushGroupDto;
import com.linkwechat.wecom.domain.dto.WeMessagePushResultDto;
import com.linkwechat.wecom.mapper.WeMessagePushMapper; import com.linkwechat.wecom.mapper.WeMessagePushMapper;
import com.linkwechat.wecom.service.IWeGroupService;
import com.linkwechat.wecom.service.IWeMessagePushService; import com.linkwechat.wecom.service.IWeMessagePushService;
import com.linkwechat.wecom.strategy.MessageContext;
import com.linkwechat.wecom.strategy.SendMessageToUserGroupStrategy;
import com.linkwechat.wecom.strategy.SendMessageToUserStrategy;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service; import org.springframework.stereotype.Service;
import java.util.Arrays; import java.util.*;
import java.util.HashMap;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;
/** /**
* 消息发送的Service接口 * 消息发送的Service接口
...@@ -44,10 +29,10 @@ public class WeMessagePushServiceImpl implements IWeMessagePushService { ...@@ -44,10 +29,10 @@ public class WeMessagePushServiceImpl implements IWeMessagePushService {
private WeMessagePushMapper weMessagePushMapper; private WeMessagePushMapper weMessagePushMapper;
@Autowired @Autowired
private WeMessagePushClient weMessagePushClient; private SendMessageToUserGroupStrategy sendMessageToUserGroupStrategy;
@Autowired @Autowired
private IWeGroupService weGroupService; private SendMessageToUserStrategy sendMessageToUserStrategy;
@Override @Override
public WeMessagePush selectWeMessagePushById(Long messagePushId) { public WeMessagePush selectWeMessagePushById(Long messagePushId) {
...@@ -60,88 +45,49 @@ public class WeMessagePushServiceImpl implements IWeMessagePushService { ...@@ -60,88 +45,49 @@ public class WeMessagePushServiceImpl implements IWeMessagePushService {
} }
@Override @Override
public int insertWeMessagePush(WeMessagePush weMessagePush) { public void insertWeMessagePush(WeMessagePush weMessagePush) {
//立即发送
HashMap<String, Object> map = Maps.newHashMap(); if (null == weMessagePush.getSettingTime()) {
JSONObject jsonObject = new JSONObject(weMessagePush.getMessageJson()); sendMessgae(weMessagePush);
Optional<MessageType> of = MessageType.of(weMessagePush.getMessageType()); } else {
of.ifPresent(messageType -> map.put(messageType.getMessageType(), jsonObject));
//发送时间不能小于当前时间
if (weMessagePush.getPushType() != null && weMessagePush.getPushType().equals(PushType.SEND_TO_USER.getType())) { //定时发送消息(异步执行)
//保存消息体到数据库,增加一个发送状态(0 已发送 1 未发送)
//发送消息 //定义一个任务执行队列
WeMessagePushDto weMessagePushDto = new WeMessagePushDto(); //把任务放入执行队列
weMessagePushDto.setTouser(weMessagePush.getToUser()); //任务执行 sendMessgae(WeMessagePush weMessagePush) 方法
weMessagePushDto.setToparty(weMessagePush.getToParty()); if (DateUtils.diffTime(new Date(), DateUtil.parse(weMessagePush.getSettingTime(), "yyyy-MM-dd HH:mm:ss")) < 0) {
weMessagePushDto.setTotag(weMessagePush.getToTag()); throw new WeComException("发送时间不能小于当前时间");
weMessagePushDto.setMsgtype(weMessagePush.getMessageType());
//这个先写在配置文件中
weMessagePushDto.setAgentid(1000003);
weMessagePushDto.setSafe(0);
weMessagePushDto.setEnable_id_trans(0);
weMessagePushDto.setEnable_duplicate_check(0);
weMessagePushDto.setDuplicate_check_interval(1800L);
//动态添加微信消息体属性和属性值信息
WeMessagePushDto target = (WeMessagePushDto) ReflectUtil.getTarget(weMessagePushDto, map);
WeMessagePushResultDto weMessagePushResultDto = weMessagePushClient.sendMessageToUser(target);
if (weMessagePushResultDto.getErrcode().equals(WeConstans.WE_SUCCESS_CODE)) {
weMessagePush.setCreateTime(DateUtils.getNowDate());
weMessagePush.setDelFlag(0);
weMessagePush.setMessagePushId(SnowFlakeUtil.nextId());
//存储返回结果信息
weMessagePush.setInvaliduser(weMessagePushResultDto.getInvaliduser());
weMessagePush.setInvalidparty(weMessagePushResultDto.getInvalidparty());
weMessagePush.setInvalidtag(weMessagePushResultDto.getInvalidtag());
} }
Timer timer = new Timer();
timer.schedule(new TimerTask() {
@Override
public void run() {
sendMessgae(weMessagePush);
} }
}, DateUtil.parse(weMessagePush.getSettingTime(), "yyyy-MM-dd HH:mm:ss"));
if (weMessagePush.getPushType() != null
&& weMessagePush.getPushType().equals(PushType.SENT_TO_USER_GROUP.getType())) {
//根据员工id列表查询所有的群信息
List<String> strings = Arrays.asList(StringUtils.splitByWholeSeparatorPreserveAllTokens(weMessagePush.getToUser(), WeConstans.COMMA));
List<String> chatIds = Lists.newArrayList();
strings.forEach(s -> {
List<WeGroup> groups = weGroupService
.list(new LambdaQueryWrapper<WeGroup>().eq(WeGroup::getOwner, s));
//发送消息到群聊
if (CollectionUtil.isNotEmpty(groups)) {
groups.forEach(d -> {
WeMessagePushGroupDto weMessagePushGroupDto = new WeMessagePushGroupDto();
weMessagePushGroupDto.setChatid(d.getChatId());
weMessagePushGroupDto.setMsgtype(weMessagePush.getMessageType());
weMessagePushGroupDto.setSafe(0);
//动态添加微信消息体属性和属性值信息
WeMessagePushGroupDto target = (WeMessagePushGroupDto) ReflectUtil.getTarget(weMessagePushGroupDto, map);
WeMessagePushResultDto weMessagePushResultDto = weMessagePushClient.sendMessageToUserGroup(target);
if (weMessagePushResultDto.getErrcode().equals(WeConstans.WE_SUCCESS_CODE)) {
//保存发送的群消息
chatIds.add(d.getChatId());
} }
});
} }
}); /**
* 发送消息
weMessagePush.setCreateTime(DateUtils.getNowDate()); *
weMessagePush.setDelFlag(0); * @param weMessagePush
weMessagePush.setMessagePushId(SnowFlakeUtil.nextId()); */
weMessagePush.setChatId(CollectionUtil.isNotEmpty(chatIds) ? String.join(",", chatIds) : null); public void sendMessgae(WeMessagePush weMessagePush) {
if (weMessagePush.getPushType() != null && weMessagePush.getPushType().equals(PushType.SEND_TO_USER.getType())) {
new MessageContext(sendMessageToUserStrategy).sendMessage(weMessagePush);
}
if (weMessagePush.getPushType() != null
&& weMessagePush.getPushType().equals(PushType.SENT_TO_USER_GROUP.getType())) {
new MessageContext(sendMessageToUserGroupStrategy).sendMessage(weMessagePush);
} }
return weMessagePushMapper.insert(weMessagePush);
} }
@Override @Override
public int deleteWeMessagePushByIds(Long[] messagePushIds) { public int deleteWeMessagePushByIds(Long[] messagePushIds) {
...@@ -153,5 +99,4 @@ public class WeMessagePushServiceImpl implements IWeMessagePushService { ...@@ -153,5 +99,4 @@ public class WeMessagePushServiceImpl implements IWeMessagePushService {
return weMessagePushMapper.deleteById(messagePushId); return weMessagePushMapper.deleteById(messagePushId);
} }
} }
package com.linkwechat.wecom.strategy;
import com.linkwechat.wecom.domain.WeMessagePush;
public class MessageContext {
private Strategy strategy;
public MessageContext(Strategy strategy) {
this.strategy = strategy;
}
/**
* 推送消息
*
* @param weMessagePush 消息发送的
*/
public void sendMessage(WeMessagePush weMessagePush) {
strategy.sendMessage(weMessagePush);
}
}
package com.linkwechat.wecom.strategy;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.json.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.linkwechat.common.constant.WeConstans;
import com.linkwechat.common.enums.MessageType;
import com.linkwechat.common.utils.DateUtils;
import com.linkwechat.common.utils.ReflectUtil;
import com.linkwechat.common.utils.SnowFlakeUtil;
import com.linkwechat.common.utils.StringUtils;
import com.linkwechat.wecom.client.WeMessagePushClient;
import com.linkwechat.wecom.domain.WeGroup;
import com.linkwechat.wecom.domain.WeMessagePush;
import com.linkwechat.wecom.domain.dto.WeMessagePushGroupDto;
import com.linkwechat.wecom.domain.dto.WeMessagePushResultDto;
import com.linkwechat.wecom.mapper.WeMessagePushMapper;
import com.linkwechat.wecom.service.IWeGroupService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Optional;
/**
* 应用推送消息
*/
@Service
public class SendMessageToUserGroupStrategy implements Strategy {
@Autowired
private WeMessagePushMapper weMessagePushMapper;
@Autowired
private WeMessagePushClient weMessagePushClient;
@Autowired
private IWeGroupService weGroupService;
@Override
public void sendMessage(WeMessagePush weMessagePush) {
HashMap<String, Object> map = Maps.newHashMap();
JSONObject jsonObject = new JSONObject(weMessagePush.getMessageJson());
Optional<MessageType> of = MessageType.of(weMessagePush.getMessageType());
of.ifPresent(messageType -> map.put(messageType.getMessageType(), jsonObject));
//根据员工id列表查询所有的群信息
List<String> strings = Arrays.asList(StringUtils.splitByWholeSeparatorPreserveAllTokens(weMessagePush.getToUser(), WeConstans.COMMA));
List<String> chatIds = Lists.newArrayList();
strings.forEach(s -> {
List<WeGroup> groups = weGroupService
.list(new LambdaQueryWrapper<WeGroup>().eq(WeGroup::getOwner, s));
//发送消息到群聊
if (CollectionUtil.isNotEmpty(groups)) {
groups.forEach(d -> {
WeMessagePushGroupDto weMessagePushGroupDto = new WeMessagePushGroupDto();
weMessagePushGroupDto.setChatid(d.getChatId());
weMessagePushGroupDto.setMsgtype(weMessagePush.getMessageType());
weMessagePushGroupDto.setSafe(0);
//动态添加微信消息体属性和属性值信息
WeMessagePushGroupDto target = (WeMessagePushGroupDto) ReflectUtil.getTarget(weMessagePushGroupDto, map);
WeMessagePushResultDto weMessagePushResultDto = weMessagePushClient.sendMessageToUserGroup(target);
if (weMessagePushResultDto.getErrcode().equals(WeConstans.WE_SUCCESS_CODE)) {
//保存发送的群消息
chatIds.add(d.getChatId());
}
});
}
});
weMessagePush.setCreateTime(DateUtils.getNowDate());
weMessagePush.setDelFlag(0);
weMessagePush.setMessagePushId(SnowFlakeUtil.nextId());
weMessagePush.setChatId(CollectionUtil.isNotEmpty(chatIds) ? String.join(",", chatIds) : null);
weMessagePushMapper.insert(weMessagePush);
}
}
package com.linkwechat.wecom.strategy;
import cn.hutool.json.JSONObject;
import com.google.common.collect.Maps;
import com.linkwechat.common.constant.WeConstans;
import com.linkwechat.common.enums.MessageType;
import com.linkwechat.common.utils.DateUtils;
import com.linkwechat.common.utils.ReflectUtil;
import com.linkwechat.common.utils.SnowFlakeUtil;
import com.linkwechat.wecom.client.WeMessagePushClient;
import com.linkwechat.wecom.domain.WeMessagePush;
import com.linkwechat.wecom.domain.dto.WeMessagePushDto;
import com.linkwechat.wecom.domain.dto.WeMessagePushResultDto;
import com.linkwechat.wecom.mapper.WeMessagePushMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.HashMap;
import java.util.Optional;
/**
* 发送应用消息
*/
@Service
public class SendMessageToUserStrategy implements Strategy {
@Autowired
private WeMessagePushMapper weMessagePushMapper;
@Autowired
private WeMessagePushClient weMessagePushClient;
@Override
public void sendMessage(WeMessagePush weMessagePush) {
HashMap<String, Object> map = Maps.newHashMap();
JSONObject jsonObject = new JSONObject(weMessagePush.getMessageJson());
Optional<MessageType> of = MessageType.of(weMessagePush.getMessageType());
of.ifPresent(messageType -> map.put(messageType.getMessageType(), jsonObject));
//发送消息
WeMessagePushDto weMessagePushDto = new WeMessagePushDto();
weMessagePushDto.setTouser(weMessagePush.getToUser());
weMessagePushDto.setToparty(weMessagePush.getToParty());
weMessagePushDto.setTotag(weMessagePush.getToTag());
weMessagePushDto.setMsgtype(weMessagePush.getMessageType());
//这个先写在配置文件中
weMessagePushDto.setAgentid(1000003);
weMessagePushDto.setSafe(0);
weMessagePushDto.setEnable_id_trans(0);
weMessagePushDto.setEnable_duplicate_check(0);
weMessagePushDto.setDuplicate_check_interval(1800L);
//动态添加微信消息体属性和属性值信息
WeMessagePushDto target = (WeMessagePushDto) ReflectUtil.getTarget(weMessagePushDto, map);
WeMessagePushResultDto weMessagePushResultDto = weMessagePushClient.sendMessageToUser(target);
if (weMessagePushResultDto.getErrcode().equals(WeConstans.WE_SUCCESS_CODE)) {
weMessagePush.setCreateTime(DateUtils.getNowDate());
weMessagePush.setDelFlag(0);
weMessagePush.setMessagePushId(SnowFlakeUtil.nextId());
//存储返回结果信息
weMessagePush.setInvaliduser(weMessagePushResultDto.getInvaliduser());
weMessagePush.setInvalidparty(weMessagePushResultDto.getInvalidparty());
weMessagePush.setInvalidtag(weMessagePushResultDto.getInvalidtag());
}
weMessagePushMapper.insert(weMessagePush);
}
}
package com.linkwechat.wecom.strategy;
import com.linkwechat.wecom.domain.WeMessagePush;
public interface Strategy {
/**
* 推送消息
*
* @param weMessagePush 消息发送的
*/
public void sendMessage(WeMessagePush weMessagePush);
}
Markdown is supported
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!