/* * Copyright 2019-2020 Zheng Jie * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package me.zhengjie.modules.temp.service.impl; import com.fasterxml.jackson.databind.ObjectMapper; import me.zhengjie.modules.temp.domain.WechatSendHistory; import me.zhengjie.modules.temp.event.ChangeApprovalStatusEvent; import me.zhengjie.utils.*; import lombok.RequiredArgsConstructor; import me.zhengjie.modules.temp.repository.WechatSendHistoryRepository; import me.zhengjie.modules.temp.service.WechatSendHistoryService; import me.zhengjie.modules.temp.service.dto.WechatSendHistoryDto; import me.zhengjie.modules.temp.service.dto.WechatSendHistoryQueryCriteria; import me.zhengjie.modules.temp.service.mapstruct.WechatSendHistoryMapper; import me.zhengjie.utils.weixin.WXBizJsonMsgCrypt; import org.json.JSONArray; import org.json.JSONObject; import org.json.XML; import org.springframework.context.ApplicationEventPublisher; import org.springframework.data.domain.Sort; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import org.springframework.data.domain.Page; import org.springframework.data.domain.Pageable; import java.io.BufferedReader; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.*; import java.io.IOException; import java.util.stream.Collectors; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; /** * @website https://eladmin.vip * @description 服务实现 * @author baolh * @date 2025-02-19 **/ @Service @RequiredArgsConstructor public class WechatSendHistoryServiceImpl implements WechatSendHistoryService { private final WechatSendHistoryRepository wechatSendHistoryRepository; private final WechatSendHistoryMapper wechatSendHistoryMapper; private final ApplicationEventPublisher applicationEventPublisher; private final String CORP_ID = "wwc0fd49735bfcf0ad"; private final String TOKEN = "KXUDtcVs1UdN7T"; private final String ENCODING_AES_KEY = "FnqE1jnu1LkqkfZzzsgU6WgIRvj1FTo8a7LgOmHqKgM"; private final String APPROVAL_AGENT_ID = "1000005"; @Override public Map queryAll(WechatSendHistoryQueryCriteria criteria, Pageable pageable){ Page page = wechatSendHistoryRepository.findAll((root, criteriaQuery, criteriaBuilder) -> QueryHelp.getPredicate(root,criteria,criteriaBuilder),pageable); return PageUtil.toPage(page.map(wechatSendHistoryMapper::toDto)); } @Override public List queryAll(WechatSendHistoryQueryCriteria criteria){ return wechatSendHistoryMapper.toDto(wechatSendHistoryRepository.findAll((root, criteriaQuery, criteriaBuilder) -> QueryHelp.getPredicate(root,criteria,criteriaBuilder))); } @Override @Transactional public WechatSendHistoryDto findById(Long id) { WechatSendHistory wechatSendHistory = wechatSendHistoryRepository.findById(id).orElseGet(WechatSendHistory::new); ValidationUtil.isNull(wechatSendHistory.getId(),"WechatSendHistory","id",id); return wechatSendHistoryMapper.toDto(wechatSendHistory); } @Override @Transactional(rollbackFor = Exception.class) public WechatSendHistoryDto create(WechatSendHistory resources) { return wechatSendHistoryMapper.toDto(wechatSendHistoryRepository.save(resources)); } @Override @Transactional(rollbackFor = Exception.class) public void update(WechatSendHistory resources) { WechatSendHistory wechatSendHistory = wechatSendHistoryRepository.findById(resources.getId()).orElseGet(WechatSendHistory::new); ValidationUtil.isNull( wechatSendHistory.getId(),"WechatSendHistory","id",resources.getId()); wechatSendHistory.copy(resources); wechatSendHistoryRepository.save(wechatSendHistory); } @Override public void deleteAll(Long[] ids) { for (Long id : ids) { wechatSendHistoryRepository.deleteById(id); } } @Override public void download(List all, HttpServletResponse response) throws IOException { List> list = new ArrayList<>(); for (WechatSendHistoryDto wechatSendHistory : all) { Map map = new LinkedHashMap<>(); map.put("下发内容", wechatSendHistory.getContent()); map.put("创建时间", wechatSendHistory.getCreateTime()); list.add(map); } FileUtil.downloadExcel(list, response); } @Override public void approvalBack(String msgSignature, String timestamp, String nonce, String echostr, HttpServletResponse response) { try { WXBizJsonMsgCrypt wxcpt = new WXBizJsonMsgCrypt(TOKEN, ENCODING_AES_KEY, CORP_ID); // 设置响应内容类型为纯文本 response.setContentType("text/plain; charset=UTF-8"); // 获取PrintWriter对象 PrintWriter out = response.getWriter(); // 直接返回 String message = wxcpt.VerifyURL(msgSignature, timestamp, nonce, echostr); out.print(message); // 刷新并关闭PrintWriter out.flush(); out.close(); } catch (Exception e) { e.printStackTrace(); } } @Override public void handleApprovalCallback(String msgSignature, String timestamp, String nonce, HttpServletRequest request, HttpServletResponse response) { try { WXBizJsonMsgCrypt wxcpt = new WXBizJsonMsgCrypt(TOKEN, ENCODING_AES_KEY, CORP_ID); // 读取回调数据 StringBuilder sb = new StringBuilder(); BufferedReader reader = new BufferedReader(new InputStreamReader(request.getInputStream())); String line; while ((line = reader.readLine()) != null) { sb.append(line); } String callbackData = sb.toString(); // 保存原始数据 WechatSendHistory beforeHistory = new WechatSendHistory(); beforeHistory.setContent(callbackData); wechatSendHistoryRepository.save(beforeHistory); // 解密前处理 JSONObject dataJson; if (isJson(callbackData)) { dataJson = new JSONObject(callbackData); } else { JSONObject xmlJson = XML.toJSONObject(callbackData); // 修复 JSON 结构 fixJsonStructure(xmlJson); // 保存解密前XML数据 WechatSendHistory afterHistory1 = new WechatSendHistory(); afterHistory1.setContent(xmlJson.toString()); wechatSendHistoryRepository.save(afterHistory1); dataJson = xmlJson.getJSONObject("xml"); } // 进行解密处理前将键值修改为小写 JSONObject finalDataJson = new JSONObject(dataJson.keySet().stream().collect(Collectors.toMap(key -> key.toLowerCase(), val -> dataJson.get(val)))); String decryptedMessage = wxcpt.DecryptMsg(msgSignature, timestamp, nonce, finalDataJson.toString()); // 保存解密后原始数据 WechatSendHistory afterHistory2 = new WechatSendHistory(); afterHistory2.setContent(decryptedMessage); wechatSendHistoryRepository.save(afterHistory2); // 解密后处理 JSONObject decryptDataJson; if (isJson(decryptedMessage)) { decryptDataJson = new JSONObject(decryptedMessage); } else { JSONObject xmlJson = XML.toJSONObject(decryptedMessage); // 修复 JSON 结构 fixJsonStructure(xmlJson); // 保存解密后XML数据 WechatSendHistory afterHistory3 = new WechatSendHistory(); afterHistory3.setContent(xmlJson.toString()); wechatSendHistoryRepository.save(afterHistory3); decryptDataJson = xmlJson.getJSONObject("xml"); } // 保存最终数据 WechatSendHistory afterHistory4 = new WechatSendHistory(); afterHistory4.setContent(decryptDataJson.toString()); WechatSendHistory afterHistorySaved = wechatSendHistoryRepository.save(afterHistory4); ChangeApprovalStatusEvent event = new ChangeApprovalStatusEvent(new Object(), afterHistorySaved.getId()); applicationEventPublisher.publishEvent(event); } catch (Exception e) { e.printStackTrace(); } } @Override public void handleWechatSendHistoryBySpNo(String spNo) { if (StringUtils.isNotBlank(spNo)) { WechatSendHistoryQueryCriteria criteria = new WechatSendHistoryQueryCriteria(); criteria.setContentInnerLike(spNo); List historyList = wechatSendHistoryRepository.findAll((root, criteriaQuery, criteriaBuilder) -> QueryHelp.getPredicate(root, criteria, criteriaBuilder), Sort.by(Sort.Direction.DESC, "id")); if (historyList.size() > 0) { WechatSendHistory filterData = historyList.stream().filter(h -> h.getContent().startsWith("{\"ApprovalInfo\"")).findFirst().orElseGet(WechatSendHistory::new); if (StringUtils.isNotBlank(filterData.getContent())) { ChangeApprovalStatusEvent event = new ChangeApprovalStatusEvent(new Object(), filterData.getId()); applicationEventPublisher.publishEvent(event); } } } } /** * 判断字符串是不是Json格式 * * @param str 字符串对象 */ private static Boolean isJson(String str) { try { ObjectMapper mapper = new ObjectMapper(); mapper.readTree(str); return true; } catch (Exception e) { return false; } } /** * 修复 JSON 结构,确保指定字段始终是列表 * * @param jsonObject JSON 对象 */ private static void fixJsonStructure(JSONObject jsonObject) { // 定义需要确保为列表的字段名 String[] listFields = {"ProcessList", "NodeList", "Details", "Notifyer", "SubNodeList", "SpRecord", "Comments" }; for (String fieldName : listFields) { if (jsonObject.has(fieldName)) { Object value = jsonObject.get(fieldName); if (!(value instanceof JSONArray)) { // 如果不是列表,将其包装为列表 JSONArray array = new JSONArray(); array.put(value); jsonObject.put(fieldName, array); } } } // 递归处理嵌套对象 for (String key : jsonObject.keySet()) { Object value = jsonObject.get(key); if (value instanceof JSONObject) { fixJsonStructure((JSONObject) value); } else if (value instanceof JSONArray) { JSONArray array = (JSONArray) value; for (int i = 0; i < array.length(); i++) { Object item = array.get(i); if (item instanceof JSONObject) { fixJsonStructure((JSONObject) item); } } } } } }