From ba17866a389cca739c56bef16c341e9ea59eda0c Mon Sep 17 00:00:00 2001 From: wangpengfei <1928057482@qq.com> Date: Fri, 31 Mar 2023 16:49:57 +0800 Subject: [PATCH] =?UTF-8?q?=E5=BE=AE=E4=BF=A1=E5=85=AC=E4=BC=97=E5=8F=B7?= =?UTF-8?q?=E6=8E=A8=E9=80=81?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../supervise-customer-biz/pom.xml | 6 + .../supervise/customer/biz/util/CharUtil.java | 80 ++++ .../customer/biz/util/JedisLock.java | 171 +++++++ .../customer/biz/util/JsonUtils.java | 418 ++++++++++++++++++ .../biz/util/JsonValueProcessorImpl.java | 49 ++ .../supervise/customer/biz/util/MapUtils.java | 302 +++++++++++++ .../supervise/customer/biz/util/MyModule.java | 10 + .../customer/biz/util/MyX509TrustManager.java | 22 + .../biz/util/PropertyFilterMixIn.java | 8 + .../customer/biz/util/ValidatorUtils.java | 201 +++++++++ .../customer/biz/util/WeixinCheckoutUtil.java | 89 ++++ .../supervise/customer/biz/util/XmlUtil.java | 201 +++++++++ .../customer/biz/util/applet/MD5.java | 29 ++ .../biz/util/applet/TemplateData.java | 47 ++ .../biz/util/applet/WX_HttpsUtil.java | 80 ++++ .../biz/util/applet/WX_TemplateMsgUtil.java | 112 +++++ .../biz/util/applet/WechatConfig.java | 39 ++ .../util/applet/WechatRefundApiResult.java | 214 +++++++++ .../customer/biz/util/applet/WechatUtil.java | 296 +++++++++++++ .../customer/biz/wechat/WechatApiService.java | 271 ++++++++++++ .../customer/biz/wechat/WechatRest.java | 48 ++ .../customer/biz/wechat/WechatService.java | 67 +++ 22 files changed, 2760 insertions(+) create mode 100644 yxt_supervise/supervise-customer/supervise-customer-biz/src/main/java/com/yxt/supervise/customer/biz/util/CharUtil.java create mode 100644 yxt_supervise/supervise-customer/supervise-customer-biz/src/main/java/com/yxt/supervise/customer/biz/util/JedisLock.java create mode 100644 yxt_supervise/supervise-customer/supervise-customer-biz/src/main/java/com/yxt/supervise/customer/biz/util/JsonUtils.java create mode 100644 yxt_supervise/supervise-customer/supervise-customer-biz/src/main/java/com/yxt/supervise/customer/biz/util/JsonValueProcessorImpl.java create mode 100644 yxt_supervise/supervise-customer/supervise-customer-biz/src/main/java/com/yxt/supervise/customer/biz/util/MapUtils.java create mode 100644 yxt_supervise/supervise-customer/supervise-customer-biz/src/main/java/com/yxt/supervise/customer/biz/util/MyModule.java create mode 100644 yxt_supervise/supervise-customer/supervise-customer-biz/src/main/java/com/yxt/supervise/customer/biz/util/MyX509TrustManager.java create mode 100644 yxt_supervise/supervise-customer/supervise-customer-biz/src/main/java/com/yxt/supervise/customer/biz/util/PropertyFilterMixIn.java create mode 100644 yxt_supervise/supervise-customer/supervise-customer-biz/src/main/java/com/yxt/supervise/customer/biz/util/ValidatorUtils.java create mode 100644 yxt_supervise/supervise-customer/supervise-customer-biz/src/main/java/com/yxt/supervise/customer/biz/util/WeixinCheckoutUtil.java create mode 100644 yxt_supervise/supervise-customer/supervise-customer-biz/src/main/java/com/yxt/supervise/customer/biz/util/XmlUtil.java create mode 100644 yxt_supervise/supervise-customer/supervise-customer-biz/src/main/java/com/yxt/supervise/customer/biz/util/applet/MD5.java create mode 100644 yxt_supervise/supervise-customer/supervise-customer-biz/src/main/java/com/yxt/supervise/customer/biz/util/applet/TemplateData.java create mode 100644 yxt_supervise/supervise-customer/supervise-customer-biz/src/main/java/com/yxt/supervise/customer/biz/util/applet/WX_HttpsUtil.java create mode 100644 yxt_supervise/supervise-customer/supervise-customer-biz/src/main/java/com/yxt/supervise/customer/biz/util/applet/WX_TemplateMsgUtil.java create mode 100644 yxt_supervise/supervise-customer/supervise-customer-biz/src/main/java/com/yxt/supervise/customer/biz/util/applet/WechatConfig.java create mode 100644 yxt_supervise/supervise-customer/supervise-customer-biz/src/main/java/com/yxt/supervise/customer/biz/util/applet/WechatRefundApiResult.java create mode 100644 yxt_supervise/supervise-customer/supervise-customer-biz/src/main/java/com/yxt/supervise/customer/biz/util/applet/WechatUtil.java create mode 100644 yxt_supervise/supervise-customer/supervise-customer-biz/src/main/java/com/yxt/supervise/customer/biz/wechat/WechatApiService.java create mode 100644 yxt_supervise/supervise-customer/supervise-customer-biz/src/main/java/com/yxt/supervise/customer/biz/wechat/WechatRest.java create mode 100644 yxt_supervise/supervise-customer/supervise-customer-biz/src/main/java/com/yxt/supervise/customer/biz/wechat/WechatService.java diff --git a/yxt_supervise/supervise-customer/supervise-customer-biz/pom.xml b/yxt_supervise/supervise-customer/supervise-customer-biz/pom.xml index 15f895be..9e6d517c 100644 --- a/yxt_supervise/supervise-customer/supervise-customer-biz/pom.xml +++ b/yxt_supervise/supervise-customer/supervise-customer-biz/pom.xml @@ -117,6 +117,12 @@ easyexcel 3.2.1 + + net.sf.json-lib + json-lib + jdk15 + 2.4 + diff --git a/yxt_supervise/supervise-customer/supervise-customer-biz/src/main/java/com/yxt/supervise/customer/biz/util/CharUtil.java b/yxt_supervise/supervise-customer/supervise-customer-biz/src/main/java/com/yxt/supervise/customer/biz/util/CharUtil.java new file mode 100644 index 00000000..dbd0da33 --- /dev/null +++ b/yxt_supervise/supervise-customer/supervise-customer-biz/src/main/java/com/yxt/supervise/customer/biz/util/CharUtil.java @@ -0,0 +1,80 @@ +package com.yxt.supervise.customer.biz.util; + +import java.util.Random; + +public class CharUtil { + + /** + * 获取随机字符串 + * + * @param num + * @return + */ + public static String getRandomString(Integer num) { + String base = "abcdefghijklmnopqrstuvwxyz0123456789"; + Random random = new Random(); + StringBuffer sb = new StringBuffer(); + for (int i = 0; i < num; i++) { + int number = random.nextInt(base.length()); + sb.append(base.charAt(number)); + } + return sb.toString(); + } + + /** + * 获取随机字符串 + * + * @param num + * @return + */ + public static String getRandomNum(Integer num) { + String base = "0123456789"; + Random random = new Random(); + StringBuffer sb = new StringBuffer(); + for (int i = 0; i < num; i++) { + int number = random.nextInt(base.length()); + sb.append(base.charAt(number)); + } + return sb.toString(); + } + + /** + * 右补位,左对齐 + * + * @param oriStr 原字符串 + * @param len 目标字符串长度 + * @param fillChar 补位字符 + * @return 目标字符串 + */ + public static String padRight(String oriStr, int len, char fillChar) { + String str = ""; + int strlen = oriStr.length(); + if (strlen < len) { + for (int i = 0; i < len - strlen; i++) { + str = str + fillChar; + } + } + str = str + oriStr; + return str; + } + + /** + * 左补位,右对齐 + * + * @param oriStr 原字符串 + * @param len 目标字符串长度 + * @param fillChar 补位字符 + * @return 目标字符串 + */ + public static String padLeft(String oriStr, int len, char fillChar) { + int strlen = oriStr.length(); + String str = ""; + if (strlen < len) { + for (int i = 0; i < len - strlen; i++) { + str = str + fillChar; + } + } + str = oriStr + str; + return str; + } +} diff --git a/yxt_supervise/supervise-customer/supervise-customer-biz/src/main/java/com/yxt/supervise/customer/biz/util/JedisLock.java b/yxt_supervise/supervise-customer/supervise-customer-biz/src/main/java/com/yxt/supervise/customer/biz/util/JedisLock.java new file mode 100644 index 00000000..ac1200a1 --- /dev/null +++ b/yxt_supervise/supervise-customer/supervise-customer-biz/src/main/java/com/yxt/supervise/customer/biz/util/JedisLock.java @@ -0,0 +1,171 @@ +package com.yxt.supervise.customer.biz.util; + +import redis.clients.jedis.Jedis; + +import java.util.Arrays; +import java.util.UUID; + +/** + * Redis distributed lock implementation. + * + * @author Alois Belaska + */ +public class JedisLock { + + /** + * Lua script which allows for an atomic delete on the lock only + * if it is owned by the lock. This prevents locks stealing from others. + */ + private final static String DELETE_IF_OWNED = + "if redis.call('get', KEYS[1]) == ARGV[1] then " + + "return redis.call('del', KEYS[1]) " + + "else " + + "return 0 " + + "end"; + + private Jedis jedis; + + /** + * Lock key path. + */ + private String lockKey; + private String token; + + /** + * Lock expiration in milliseconds. + */ + private int expireMsecs = 60 * 1000; + + /** + * Acquire timeout in milliseconds. + */ + private int timeoutMsecs = 10 * 1000; + + private boolean locked = false; + + /** + * Detailed constructor with default acquire timeout 10000 msecs and lock expiration of 60000 msecs. + * + * @param jedis + * @param lockKey lock key (ex. account:1, ...) + */ + public JedisLock(Jedis jedis, String lockKey) { + this.jedis = jedis; + this.lockKey = lockKey; + this.token = UUID.randomUUID().toString(); + } + + /** + * Detailed constructor with default lock expiration of 60000 msecs. + * + * @param jedis + * @param lockKey lock key (ex. account:1, ...) + * @param timeoutMsecs acquire timeout in milliseconds (default: 10000 msecs) + */ + public JedisLock(Jedis jedis, String lockKey, int timeoutMsecs) { + this(jedis, lockKey); + this.timeoutMsecs = timeoutMsecs; + } + + /** + * Detailed constructor. + * + * @param jedis + * @param lockKey lock key (ex. account:1, ...) + * @param timeoutMsecs acquire timeout in milliseconds (default: 10000 msecs) + * @param expireMsecs lock expiration in milliseconds (default: 60000 msecs) + */ + public JedisLock(Jedis jedis, String lockKey, int timeoutMsecs, int expireMsecs) { + this(jedis, lockKey, timeoutMsecs); + this.expireMsecs = expireMsecs; + } + + /** + * Detailed constructor with default acquire timeout 10000 msecs and lock expiration of 60000 msecs. + * + * @param lockKey lock key (ex. account:1, ...) + */ + public JedisLock(String lockKey) { + this(null, lockKey); + } + + /** + * Detailed constructor with default lock expiration of 60000 msecs. + * + * @param lockKey lock key (ex. account:1, ...) + * @param timeoutMsecs acquire timeout in miliseconds (default: 10000 msecs) + */ + public JedisLock(String lockKey, int timeoutMsecs) { + this(null, lockKey, timeoutMsecs); + } + + /** + * Detailed constructor. + * + * @param lockKey lock key (ex. account:1, ...) + * @param timeoutMsecs acquire timeout in miliseconds (default: 10000 msecs) + * @param expireMsecs lock expiration in miliseconds (default: 60000 msecs) + */ + public JedisLock(String lockKey, int timeoutMsecs, int expireMsecs) { + this(null, lockKey, timeoutMsecs, expireMsecs); + } + + /** + * @return lock key + */ + public String getLockKey() { + return lockKey; + } + + /** + * Acquire lock. + * + * @return true if lock is acquired, false acquire timeouted + * @throws InterruptedException in case of thread interruption + */ + public synchronized boolean acquire() throws InterruptedException { + return acquire(jedis); + } + + /** + * Acquire lock. + * + * @param jedis + * @return true if lock is acquired, false acquire timed out + * @throws InterruptedException in case of thread interruption + */ + public synchronized boolean acquire(Jedis jedis) throws InterruptedException { + int timeout = timeoutMsecs; + while (timeout >= 0) { + + if ("OK".equals(jedis.set(lockKey, token))) { + // lock acquired + locked = true; + return true; + } + + timeout -= 100; + Thread.sleep(100); + } + + return false; + } + + /** + * Acquired lock release. + */ + public synchronized void release() { + release(jedis); + } + + /** + * Acquired lock release. + */ + public synchronized void release(Jedis jedis) { + if (locked) { + // prevent threads from releasing locks which they don't own + jedis.eval(DELETE_IF_OWNED, Arrays.asList(lockKey), Arrays.asList(token)); + locked = false; + } + } +} diff --git a/yxt_supervise/supervise-customer/supervise-customer-biz/src/main/java/com/yxt/supervise/customer/biz/util/JsonUtils.java b/yxt_supervise/supervise-customer/supervise-customer-biz/src/main/java/com/yxt/supervise/customer/biz/util/JsonUtils.java new file mode 100644 index 00000000..e5949ed0 --- /dev/null +++ b/yxt_supervise/supervise-customer/supervise-customer-biz/src/main/java/com/yxt/supervise/customer/biz/util/JsonUtils.java @@ -0,0 +1,418 @@ +package com.yxt.supervise.customer.biz.util; + +import com.fasterxml.jackson.annotation.JsonFilter; +import com.fasterxml.jackson.core.JsonParseException; +import com.fasterxml.jackson.core.JsonProcessingException; +import com.fasterxml.jackson.core.type.TypeReference; +import com.fasterxml.jackson.databind.*; +import com.fasterxml.jackson.databind.ser.FilterProvider; +import com.fasterxml.jackson.databind.ser.impl.SimpleBeanPropertyFilter; +import com.fasterxml.jackson.databind.ser.impl.SimpleFilterProvider; +import com.google.common.collect.Lists; +import com.google.common.collect.Maps; +import lombok.extern.slf4j.Slf4j; +import net.sf.json.JsonConfig; +import net.sf.json.util.PropertyFilter; +import org.springframework.core.annotation.AnnotationUtils; +import org.springframework.util.StringUtils; + +import java.io.IOException; +import java.io.OutputStream; +import java.text.SimpleDateFormat; +import java.util.*; + +/** + * json对象映射工具类之jackson封装 + */ +@Slf4j +public class JsonUtils { + + private static ObjectMapper objectMapper = null; + + static { + objectMapper = new ObjectMapper(); + // 设置默认日期格式 + objectMapper.setDateFormat(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss")); + // 提供其它默认设置 + objectMapper.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES); + objectMapper.configure(SerializationFeature.FAIL_ON_EMPTY_BEANS, false); + objectMapper.setFilters(new SimpleFilterProvider() + .setFailOnUnknownId(false)); + objectMapper.registerModule(new MyModule()); + } + + /** + * 将对象转换成json字符串格式(默认将转换所有的属性) + * + * @param value + * @return + */ + public static String toJsonStr(Object value) { + try { + return objectMapper.writeValueAsString(value); + } catch (JsonProcessingException e) { + log.error("Json转换失败", e); + throw new RuntimeException(e); + } + } + + /** + * 将对象转换成json字符串格式 + * + * @param value 需要转换的对象 + * @param properties 需要转换的属性 + */ + public static String toJsonStr(Object value, String[] properties) { + try { + SimpleBeanPropertyFilter sbp = SimpleBeanPropertyFilter + .filterOutAllExcept(properties); + FilterProvider filterProvider = new SimpleFilterProvider() + .addFilter("propertyFilterMixIn", sbp); + return objectMapper.writer(filterProvider) + .writeValueAsString(value); + } catch (Exception e) { + log.error("Json转换失败", e); + throw new RuntimeException(e); + } + + } + + /** + * 将对象转换成json字符串格式 + * + * @param value 需要转换的对象 + * @param properties2Exclude 需要排除的属性 + */ + public static String toJsonStrWithExcludeProperties(Object value, + String[] properties2Exclude) { + try { + SimpleBeanPropertyFilter sbp = SimpleBeanPropertyFilter + .serializeAllExcept(properties2Exclude); + FilterProvider filterProvider = new SimpleFilterProvider() + .addFilter("propertyFilterMixIn", sbp); + return objectMapper.writer(filterProvider) + .writeValueAsString(value); + } catch (Exception e) { + log.error("Json转换失败", e); + throw new RuntimeException(e); + } + + } + + /** + * 将对象json格式直接写出到流对象中(默认将转换所有的属性) + * + * @param out + * @return + */ + public static void writeJsonStr(OutputStream out, Object value) { + try { + objectMapper.writeValue(out, value); + } catch (Exception e) { + log.error("Json转换失败", e); + throw new RuntimeException(e); + } + } + + /** + * 将对象json格式直接写出到流对象中 + * + * @param value 需要转换的对象(注意,需要在要转换的对象中定义JsonFilter注解) + * @param properties 需要转换的属性 + */ + public static void writeJsonStr(OutputStream out, Object value, + String[] properties) { + + try { + objectMapper.writer( + new SimpleFilterProvider().addFilter( + AnnotationUtils + .getValue( + AnnotationUtils.findAnnotation( + value.getClass(), + JsonFilter.class)) + .toString(), SimpleBeanPropertyFilter + .filterOutAllExcept(properties))) + .writeValue(out, value); + } catch (Exception e) { + log.error("Json转换失败", e); + throw new RuntimeException(e); + } + + } + + /** + * 将对象转换成json字符串格式 + * + * @param value 需要转换的对象 + * @param properties2Exclude 需要排除的属性(注意,需要在要转换的对象中定义JsonFilter注解) + */ + public static void writeJsonStrWithExcludeProperties(OutputStream out, + Object value, String[] properties2Exclude) { + try { + objectMapper.writer( + new SimpleFilterProvider().addFilter( + AnnotationUtils + .getValue( + AnnotationUtils.findAnnotation( + value.getClass(), + JsonFilter.class)) + .toString(), SimpleBeanPropertyFilter + .serializeAllExcept(properties2Exclude))) + .writeValue(out, value); + } catch (Exception e) { + log.error("Json转换失败", e); + throw new RuntimeException(e); + } + + } + + /** + * 反序列化POJO或简单Collection如List. + *

+ * 如果JSON字符串为Null或"null"字符串, 返回Null. 如果JSON字符串为"[]", 返回空集合. + *

+ * 如需反序列化复杂Collection如List, 请使用fromJson(String, JavaType) + */ + public static T fromJson(String jsonString, Class clazz) { + if (StringUtils.isEmpty(jsonString)) { + return null; + } + + try { + return objectMapper.readValue(jsonString, clazz); + } catch (IOException e) { + log.warn("parse json string error:" + jsonString, e); + return null; + } + } + + @SuppressWarnings({"unchecked", "unused"}) + public static List readJsonList(String jsondata, Object object) { + try { + List> list = objectMapper.readValue( + jsondata, List.class); + + List objects = Lists.newArrayList(); + System.out.println(list.size()); + for (int i = 0; i < list.size(); i++) { + Map map = list.get(i); + Set set = map.keySet(); + for (Iterator it = set.iterator(); it.hasNext(); ) { + String key = it.next(); + System.out.println(key + ":" + map.get(key)); + } + } + } catch (JsonParseException e) { + e.printStackTrace(); + } catch (JsonMappingException e) { + e.printStackTrace(); + } catch (IOException e) { + e.printStackTrace(); + } + return null; + } + + + /** + * 单独解析某一个json的key值 + * + * @param @param jsonText + * @param @param key + * @param @return 设定文件 + * @return JsonNode 返回类型 + * @throws + * @Title: getjsonvalue + * @Description: TODO(这里用一句话描述这个方法的作用) + */ + public static JsonNode getjsonvalue(String jsonText, String key) { + + try { + ObjectMapper mapper = new ObjectMapper(); + JsonNode rootNode = mapper.readTree(jsonText); // 读取Json + + return rootNode.path(key); + } catch (Exception e) { + e.printStackTrace(); + } + return null; + } + + + public static JavaType getCollectionType(Class collectionClass, Class... elementClasses) { + ObjectMapper mapper = new ObjectMapper(); + return mapper.getTypeFactory().constructParametricType(collectionClass, elementClasses); + } + + public static List json2list(String jsonArrayStr, Class clazz) throws Exception { + List> list = (List) objectMapper.readValue(jsonArrayStr, new TypeReference>() { + }); + List result = new ArrayList(); + Iterator var4 = list.iterator(); + + while (var4.hasNext()) { + Map map = (Map) var4.next(); + result.add(map2pojo(map, clazz)); + } + + return result; + } + + public static T map2pojo(Map map, Class clazz) { + return objectMapper.convertValue(map, clazz); + } + + /** + * 解析json属性,放到实体里面去 + * + * @param @param jsondata + * @param @param collectionClass + * @param @return 设定文件 + * @return List 返回类型 + * @throws + * @Title: readJsonList + * @Description: TODO(这里用一句话描述这个方法的作用) + */ + @SuppressWarnings("unchecked") + public static List readJsonList(String jsondata, Class collectionClass) { + try { + ObjectMapper mapper = new ObjectMapper(); + JavaType javaType = getCollectionType(ArrayList.class, collectionClass); + List lst = (List) mapper.readValue(jsondata, javaType); + + return lst; + } catch (Exception e) { + e.printStackTrace(); + } + return null; + } + + + /** + * json 转map + * + * @param @param jsondata + * @param @return 设定文件 + * @return Map> 返回类型 + * @throws + * @Title: readJsonMap + * @Description: TODO(这里用一句话描述这个方法的作用) + */ + @SuppressWarnings("unchecked") + public static Map readJsonToMap(String jsondata) { + try { + Map maps = objectMapper.readValue(jsondata, Map.class); + //System.out.println(maps); + return maps; + } catch (Exception e) { + e.printStackTrace(); + } + return null; + } + + @SuppressWarnings("unchecked") + public static Map readJsonToMap1(String jsondata) { + try { + Map maps = objectMapper.readValue(jsondata, Map.class); + //System.out.println(maps); + return maps; + } catch (Exception e) { + e.printStackTrace(); + } + return null; + } + + + /** + * 设置过滤值为空的属性,使得生成的 json 字符串只包含非空的值 + * + * @return + */ + public static JsonConfig getJsonConfig() { + JsonConfig jsonConfig = new JsonConfig(); + jsonConfig.registerJsonValueProcessor(java.sql.Timestamp.class, new JsonValueProcessorImpl()); + jsonConfig.setJsonPropertyFilter(new PropertyFilter() { + @Override + public boolean apply(Object source, String name, Object value) { + return value == null; + } + }); + + jsonConfig.setIgnoreDefaultExcludes(false); // 设置默认忽略 + jsonConfig.setExcludes(new String[]{"dbName", "isDel"}); // 此处是亮点,只要将所需忽略字段加到数组中即可,在实际测试中,我发现在所返回数组中,存在大量无用属性, + + return jsonConfig; + } + + /** + * 将对象转换成json字符串。 + */ + public static String objectToJson(Object data) { + try { + String string = objectMapper.writeValueAsString(data); + return string; + } catch (JsonProcessingException e) { + e.printStackTrace(); + } + return null; + } + + /** + * 将json结果集转化为对象 + * + * @param jsonData json数据 + * @param beanType 对象中的object类型 + */ + public static T jsonToPojo(String jsonData, Class beanType) { + try { + if (ValidatorUtils.notEmpty(jsonData)) { + T t = objectMapper.readValue(jsonData, beanType); + return t; + } + } catch (Exception e) { + e.printStackTrace(); + } + return null; + } + + /** + * 将json数据转换成pojo对象list + */ + public static List jsonToList(String jsonData, Class beanType) { + JavaType javaType = objectMapper.getTypeFactory().constructParametricType(List.class, beanType); + try { + List list = objectMapper.readValue(jsonData, javaType); + return list; + } catch (Exception e) { + e.printStackTrace(); + } + + return null; + } + + public static void main(String[] args) { + Map userData = Maps.newHashMap(); + Map nameStruct = Maps.newHashMap(); + nameStruct.put("firstName", "张三"); + nameStruct.put("lastName", "你大爷"); + + System.out.println(JsonUtils.toJsonStr(nameStruct)); + userData.put("name", nameStruct); + userData.put("age", 20); + List stringList = Lists.newArrayList("A", "B", "C"); + System.out.println(JsonUtils.toJsonStr(userData)); + System.out.println(JsonUtils.toJsonStr(stringList)); +// String[] arr = {"37","38","41","42","43","44","45","1693","1694","1695","1696"}; +// System.out.println(toJsonStr(arr)); + + String ss = "{\"address\": \"address2\",\"name\":\"haha2\"}"; + + Map map = readJsonToMap(ss); + + if (map != null) { + System.out.println(map.get("address")); + } + } + + +} diff --git a/yxt_supervise/supervise-customer/supervise-customer-biz/src/main/java/com/yxt/supervise/customer/biz/util/JsonValueProcessorImpl.java b/yxt_supervise/supervise-customer/supervise-customer-biz/src/main/java/com/yxt/supervise/customer/biz/util/JsonValueProcessorImpl.java new file mode 100644 index 00000000..154b8341 --- /dev/null +++ b/yxt_supervise/supervise-customer/supervise-customer-biz/src/main/java/com/yxt/supervise/customer/biz/util/JsonValueProcessorImpl.java @@ -0,0 +1,49 @@ +/** + * + */ +package com.yxt.supervise.customer.biz.util; + + +import net.sf.json.JsonConfig; +import net.sf.json.processors.JsonValueProcessor; + +import java.text.SimpleDateFormat; +import java.util.Date; + +/** + *

Title: JsonValueProcessorImpl.java

+ *

Description: net.js.json 特殊值处理

+ *

Copyright: Copyright (c) 2014-2018

+ *

Company: leimingtech.com

+ * + * @author linjm + * @version 1.0 + * @date 2015年7月17日 + */ +public class JsonValueProcessorImpl implements JsonValueProcessor { + + private String format = "yyyy-MM-dd HH:mm:ss"; + + @Override + public Object processArrayValue(Object value, JsonConfig jsonConfig) { + String[] obj = {}; + if (value instanceof Date[]) { + SimpleDateFormat sdf = new SimpleDateFormat(format); + Date[] date = (Date[]) value; + for (int i = 0; i < date.length; i++) { + obj[i] = sdf.format(date[i]); + } + } + return obj; + } + + @Override + public Object processObjectValue(String key, Object value, JsonConfig jsonConfig) { + if (value instanceof Date) { + String str = new SimpleDateFormat(format).format(value); + return str; + } + return value.toString(); + } + +} diff --git a/yxt_supervise/supervise-customer/supervise-customer-biz/src/main/java/com/yxt/supervise/customer/biz/util/MapUtils.java b/yxt_supervise/supervise-customer/supervise-customer-biz/src/main/java/com/yxt/supervise/customer/biz/util/MapUtils.java new file mode 100644 index 00000000..2b1c8886 --- /dev/null +++ b/yxt_supervise/supervise-customer/supervise-customer-biz/src/main/java/com/yxt/supervise/customer/biz/util/MapUtils.java @@ -0,0 +1,302 @@ +package com.yxt.supervise.customer.biz.util;//package com.supervise.rms.biz.util; +// +// +//import com.mysql.cj.util.StringUtils; +//import org.apache.commons.beanutils.PropertyUtilsBean; +//import org.apache.commons.lang.ArrayUtils; +//import org.springframework.util.Assert; +// +//import java.beans.PropertyDescriptor; +//import java.math.BigDecimal; +//import java.sql.Date; +//import java.sql.Timestamp; +//import java.util.HashMap; +//import java.util.Iterator; +//import java.util.Map; +//import java.util.Set; +// +///** +// * 获取map中值的工具类,自动进行类型转换 +// * +// * @author DT_panda +// */ +//public class MapUtils { +// +// public static String getString(String key, Map map) { +// if (map == null || key == null) +// throw new IllegalArgumentException(); +// if (!map.containsKey(key)) +// return null; +// Object value = map.get(key); +// if (value == null) +// return null; +// return value.toString(); +// } +// +// public static Integer getInteger(String key, Map map) { +// if (map == null || key == null) +// throw new IllegalArgumentException(); +// if (!map.containsKey(key)) +// return null; +// Object value = map.get(key); +// if (value == null) +// return null; +// if (value instanceof Integer) +// return (Integer) value; +// if (value instanceof String) +// return Integer.valueOf((String) value); +// //Date 不支持变成为date类型 +// if (value instanceof Date) +// throw new ClassCastException(); +// if (value instanceof Number) +// return ((Number) value).intValue(); +// throw new ClassCastException(); +// } +// +// public static Long getLong(String key, Map map) { +// if (map == null || key == null) +// throw new IllegalArgumentException(); +// if (!map.containsKey(key)) +// return null; +// Object value = map.get(key); +// if (value == null) +// return null; +// if (value instanceof Long) +// return (Long) value; +// if (value instanceof Number) +// return ((Number) value).longValue(); +// if (value instanceof String) +// return Long.valueOf((String) value); +// if (value instanceof Date) { +// return (((Date) value).getTime()); +// } +// if (value instanceof java.sql.Time) { +// return ((java.sql.Time) value).getTime(); +// } +// if (value instanceof Timestamp) { +// return ((Timestamp) value).getTime(); +// } +// +// throw new ClassCastException(); +// } +// +// public static Double getDouble(String key, Map map) { +// if (map == null || key == null) +// throw new IllegalArgumentException(); +// if (!map.containsKey(key)) +// return null; +// Object value = map.get(key); +// if (value == null) +// return null; +// if (value instanceof Double) +// return (Double) value; +// if (value instanceof Number) +// return ((Number) value).doubleValue(); +// if (value instanceof String) +// return Double.valueOf((String) value); +// throw new ClassCastException(); +// } +// +// public static BigDecimal getBigDecimal(String key, Map map) { +// if (map == null || key == null) +// throw new IllegalArgumentException(); +// if (!map.containsKey(key)) +// return null; +// Object value = map.get(key); +// if (value == null) +// return null; +// if (value instanceof BigDecimal) +// return (BigDecimal) value; +// if (value instanceof Integer) +// return new BigDecimal((Integer) value); +// if (value instanceof Short) +// return new BigDecimal((Short) value); +// if (value instanceof Byte) +// return new BigDecimal((Byte) value); +// if (value instanceof Long) +// return new BigDecimal((Long) value); +// if (value instanceof Float) +// return new BigDecimal((Float) value); +// if (value instanceof Double) +// return new BigDecimal((Double) value); +// if (value instanceof Date) { +// return new BigDecimal(((Date) value).getTime()); +// } +// if (value instanceof java.sql.Time) { +// return new BigDecimal(((java.sql.Time) value).getTime()); +// } +// if (value instanceof Timestamp) { +// return new BigDecimal(((Timestamp) value).getTime()); +// } +// if (value instanceof String) { +// if (!StringUtils.isNullOrEmpty((String) value)) +// return new BigDecimal((String) value); +// else +// return null; +// } +// throw new ClassCastException(); +// } +// +// /** +// * 将bean转化为map +// * +// * @param bean +// * @return +// */ +// public static Map getMap(Object bean) { +// return beanToMap(bean); +// } +// +// /** +// * 将map中key为likeKey的value前后加上字符'%',用于like查询 +// * +// * @param map +// * @param likeKey +// */ +// public static void toLikeValue(Map map, String... likeKey) { +// if (ArrayUtils.isEmpty(likeKey)) +// return; +// for (String key : likeKey) { +// if (map.containsKey(key)) +// map.put(key, "%" + map.get(key) + "%"); +// } +// } +// +// /** +// * 获取日期 +// * +// * @param key +// * @param map +// * @return +// */ +// public static Date getDate(String key, Map map) { +// if (map == null || key == null) +// throw new IllegalArgumentException(); +// if (!map.containsKey(key)) +// return null; +// Object value = map.get(key); +// if (value == null) +// return null; +// else { +// if (value instanceof Date) { +// return (Date) value; +// } else if (value instanceof Timestamp) { +// return new Date(((Timestamp) value).getTime()); +// } +// } +// return null; +// } +// +// /** +// * 获取日期 +// * +// * @param key +// * @param map +// * @return +// */ +// public static java.util.Date getTimestamp(String key, Map map) { +// if (map == null || key == null) +// throw new IllegalArgumentException(); +// if (!map.containsKey(key)) +// return null; +// Object value = map.get(key); +// if (value == null) +// return null; +// else { +// if (value instanceof Date) { +// return (Date) value; +// } else if (value instanceof Timestamp) { +// Timestamp ts = (Timestamp) value; +// return ts; +// } +// } +// return null; +// } +// +// /** +// * 如果value不为空 ,则放到map中 +// * +// * @param map +// * @param key +// * @param value +// */ +// public static void putIfValueNotNull(Map map, String key, Object value) { +// Assert.notNull(map); +// Assert.hasText(key); +// if (value != null) +// map.put(key, value); +// } +// +// /** +// * 如果value不为空 ,则放到map中 +// * +// * @param map +// * @param key +// * @param value +// */ +// public static void putIfValueNotEmpty(Map map, String key, String value) { +// Assert.notNull(map); +// Assert.hasText(key); +// if (!StringUtils.isNullOrEmpty(value)) +// map.put(key, value); +// } +// +// /** +// * 将map中指定的key的value值进行处理 +// * +// * @param key +// * @param map +// * @param helper +// */ +// public static void convertMapValuePattern(String key, Map map, DealMapValueHelper helper) { +// Assert.hasText(key); +// Assert.notNull(map); +// Assert.notNull(helper); +// helper.dealValue(key, map); +// } +// +// /** +// * 将javabean实体类转为map类型,然后返回一个map类型的值 +// * +// * @return +// */ +// public static Map beanToMap(Object beanObj) { +// Map params = new HashMap(0); +// try { +// PropertyUtilsBean propertyUtilsBean = new PropertyUtilsBean(); +// PropertyDescriptor[] descriptors = propertyUtilsBean.getPropertyDescriptors(beanObj); +// for (int i = 0; i < descriptors.length; i++) { +// String name = descriptors[i].getName(); +// if (!"class".equals(name)) { +// params.put(name, propertyUtilsBean.getNestedProperty(beanObj, name)); +// } +// } +// } catch (Exception e) { +// e.printStackTrace(); +// } +// return params; +// } +// +// public static String convertMap2Xml(Map paraMap) { +// StringBuffer xmlStr = new StringBuffer(); +// if (paraMap != null) { +// xmlStr.append(""); +// Set keySet = paraMap.keySet(); +// Iterator keyIte = keySet.iterator(); +// while (keyIte.hasNext()) { +// String key = (String) keyIte.next(); +// String val = String.valueOf(paraMap.get(key)); +// xmlStr.append("<"); +// xmlStr.append(key); +// xmlStr.append(">"); +// xmlStr.append(val); +// xmlStr.append(""); +// } +// xmlStr.append(""); +// } +// return xmlStr.toString(); +// } +//} +// diff --git a/yxt_supervise/supervise-customer/supervise-customer-biz/src/main/java/com/yxt/supervise/customer/biz/util/MyModule.java b/yxt_supervise/supervise-customer/supervise-customer-biz/src/main/java/com/yxt/supervise/customer/biz/util/MyModule.java new file mode 100644 index 00000000..12f8b845 --- /dev/null +++ b/yxt_supervise/supervise-customer/supervise-customer-biz/src/main/java/com/yxt/supervise/customer/biz/util/MyModule.java @@ -0,0 +1,10 @@ +package com.yxt.supervise.customer.biz.util; + +import com.fasterxml.jackson.databind.module.SimpleModule; + +public class MyModule extends SimpleModule { + @Override + public void setupModule(SetupContext context) { + context.setMixInAnnotations(Object.class, PropertyFilterMixIn.class); + } +} diff --git a/yxt_supervise/supervise-customer/supervise-customer-biz/src/main/java/com/yxt/supervise/customer/biz/util/MyX509TrustManager.java b/yxt_supervise/supervise-customer/supervise-customer-biz/src/main/java/com/yxt/supervise/customer/biz/util/MyX509TrustManager.java new file mode 100644 index 00000000..43142c34 --- /dev/null +++ b/yxt_supervise/supervise-customer/supervise-customer-biz/src/main/java/com/yxt/supervise/customer/biz/util/MyX509TrustManager.java @@ -0,0 +1,22 @@ +package com.yxt.supervise.customer.biz.util; + +import javax.net.ssl.X509TrustManager; +import java.security.cert.CertificateException; +import java.security.cert.X509Certificate; + +public class MyX509TrustManager implements X509TrustManager { + @Override + public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException { + + } + + @Override + public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException { + + } + + @Override + public X509Certificate[] getAcceptedIssuers() { + return null; + } +} diff --git a/yxt_supervise/supervise-customer/supervise-customer-biz/src/main/java/com/yxt/supervise/customer/biz/util/PropertyFilterMixIn.java b/yxt_supervise/supervise-customer/supervise-customer-biz/src/main/java/com/yxt/supervise/customer/biz/util/PropertyFilterMixIn.java new file mode 100644 index 00000000..657eae00 --- /dev/null +++ b/yxt_supervise/supervise-customer/supervise-customer-biz/src/main/java/com/yxt/supervise/customer/biz/util/PropertyFilterMixIn.java @@ -0,0 +1,8 @@ +package com.yxt.supervise.customer.biz.util; + +import com.fasterxml.jackson.annotation.JsonFilter; + +@JsonFilter("propertyFilterMixIn") +public class PropertyFilterMixIn { + +} diff --git a/yxt_supervise/supervise-customer/supervise-customer-biz/src/main/java/com/yxt/supervise/customer/biz/util/ValidatorUtils.java b/yxt_supervise/supervise-customer/supervise-customer-biz/src/main/java/com/yxt/supervise/customer/biz/util/ValidatorUtils.java new file mode 100644 index 00000000..3fee0364 --- /dev/null +++ b/yxt_supervise/supervise-customer/supervise-customer-biz/src/main/java/com/yxt/supervise/customer/biz/util/ValidatorUtils.java @@ -0,0 +1,201 @@ +package com.yxt.supervise.customer.biz.util; + +//import com.zscat.mallplus.vo.timeline.TimeSecound; + +import java.math.BigDecimal; +import java.util.Collection; +import java.util.Date; +import java.util.List; +import java.util.Map; +import java.util.regex.Matcher; +import java.util.regex.Pattern; + +public class ValidatorUtils { + + /** + * 判断内容不为空 + * + * @param str + * @return + */ + public static boolean notEmpty(Object str) { + if (str != null && str.toString().trim().length() > 0) { + return true; + } else { + return false; + } + } + + /** + * 判断内容不为空(包含数组) + * + * @param str + * @return + */ + @SuppressWarnings("unchecked") + public static boolean notEmptyIncludeArray(Object str) { + if (str != null && String.valueOf(str).trim().length() > 0) { + if (str instanceof Object[]) {// 增加了数组长度判断 + Object[] array = (Object[]) str; + if (array.length > 0) + return true; + + return false; + } else if (str instanceof List) {// 增加了数组长度判断 + List list = (List) str; + if (list.size() > 0) + return true; + + return false; + } + + return true; + } else { + return false; + } + } + + /** + * 判断内容是空 + * + * @param str + * @return + */ + public static boolean isEmpty(Object str) { + if (str == null || str.toString().trim().length() == 0) { + return true; + } else { + return false; + } + } + + /** + * 检查对象是否为空 + * + * @param obj 要检查的数据(数据类型: String、Number、Boolean、Collection、Map、Object[]) + * @return true: 为空; false: 不为空
  • String:值为 null、""、"0" 时返回 true
  • + * Number:值为 null、0 时返回 true
  • Boolean:值为 null、false 时返回 true
  • + * Collection:值为 null、size=0 时返回 true
  • Map:值为 null、size=0 时返回 + * true
  • Object[]:值为 null、length=0 时返回 true + */ + @SuppressWarnings("unchecked") + public static boolean empty(Object obj) { + if (obj == null) { + return true; + } else if (obj instanceof String && (obj.equals(""))) { + return true; + } else if (obj instanceof Number && ((Number) obj).doubleValue() == 0) { + return true; + } else if (obj instanceof Boolean && !((Boolean) obj)) { + return true; + } else if (obj instanceof Collection && ((Collection) obj).isEmpty()) { + return true; + } else if (obj instanceof Map && ((Map) obj).isEmpty()) { + return true; + } else if (obj instanceof Object[] && ((Object[]) obj).length == 0) { + return true; + } + return false; + } + + /** + * 判断是否是合法邮箱地址 + * + * @param email + * @return + */ + public static boolean isEmail(String email) { + Pattern p = Pattern + .compile("^\\w+([\\-+.]\\w+)*@\\w+([-.]\\w+)*\\.[a-z]{2,3}"); + Matcher m = p.matcher(email); + return m.matches(); + } + + /** + * 只包含英文字母和数字、下划线 + * + * @param str + * @return + */ + public static boolean onlyNumAndChar(String str) { + String regex = "^[a-zA-Z0-9_]+$"; + Pattern pattern = Pattern.compile(regex); + return pattern.matcher(str).matches(); + } + + /** + * 必须包含字母 + * + * @param str + * @return + */ + public static boolean hasLetterAndNum(String str) { + Pattern pattern = Pattern.compile("^(?=.*[a-zA-Z].*).{6,}$"); + return pattern.matcher(str).matches(); + } + + /** + * 是否长度符合 + * + * @param str + * @param min 最小 + * @param max 最大 + * @return + */ + public static boolean lengthBetween(String str, int min, int max) { + return str.length() >= min && str.length() <= max; + } + + /** + * 判断字符串是否是数字 + * + * @param str + * @return + */ + public static boolean isNumeric(String str) { + Pattern pattern = Pattern.compile("[0-9]*"); + Matcher isNum = pattern.matcher(str); + if (!isNum.matches()) { + return false; + } + return true; + } + + public static Double rountTwo(Double num) { + if (num != null) { + BigDecimal b = new BigDecimal(num); + Double d = b.setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue(); + return d; + } else { + return null; + } + } + + public static String doubleTrans(double d) { + if (Math.round(d) - d == 0) { + return String.valueOf((long) d); + } + return String.valueOf(d); + } + + /** + * 获取结束时间与当前的时间差 + * + * @param endTime + * @return + */ +// public static TimeSecound getTimeSecound(Date endTime) { +// +// long diff = endTime.getTime() - System.currentTimeMillis();// 这样得到的差值是微秒级别 +// +// long days = diff / (1000 * 60 * 60 * 24);//天 +// +// long hours = (diff - days * (1000 * 60 * 60 * 24)) +// / (1000 * 60 * 60); //小时 +// long mins = (diff - days * (1000 * 60 * 60 * 24) - hours * (1000 * 60 * 60)) / (1000 * 60); //小时 +// long sc = (diff - days * (1000 * 60 * 60 * 24) - hours +// * (1000 * 60 * 60) - mins * (1000 * 60)) / (1000); // 秒 +// +// return new TimeSecound(days, hours, mins, sc); +// } +} diff --git a/yxt_supervise/supervise-customer/supervise-customer-biz/src/main/java/com/yxt/supervise/customer/biz/util/WeixinCheckoutUtil.java b/yxt_supervise/supervise-customer/supervise-customer-biz/src/main/java/com/yxt/supervise/customer/biz/util/WeixinCheckoutUtil.java new file mode 100644 index 00000000..4fdb1dea --- /dev/null +++ b/yxt_supervise/supervise-customer/supervise-customer-biz/src/main/java/com/yxt/supervise/customer/biz/util/WeixinCheckoutUtil.java @@ -0,0 +1,89 @@ +package com.yxt.supervise.customer.biz.util; + +import java.security.MessageDigest; +import java.security.NoSuchAlgorithmException; + +/** + * @author wangpengfei + * @date 2023/3/31 15:52 + */ +public class WeixinCheckoutUtil { + + + // 与接口配置信息中的Token要一致 + private static String token = "yxthryy"; + + /** + * 验证签名 + * + * @param signature + * @param timestamp + * @param nonce + * @return + */ + public static boolean checkSignature(String signature, String timestamp, String nonce) { + String[] arr = new String[] { token, timestamp, nonce }; + // 将token、timestamp、nonce三个参数进行字典序排序 + // Arrays.sort(arr); + sort(arr); + StringBuilder content = new StringBuilder(); + for (int i = 0; i < arr.length; i++) { + content.append(arr[i]); + } + MessageDigest md = null; + String tmpStr = null; + + try { + md = MessageDigest.getInstance("SHA-1"); + // 将三个参数字符串拼接成一个字符串进行sha1加密 + byte[] digest = md.digest(content.toString().getBytes()); + tmpStr = byteToStr(digest); + } catch (NoSuchAlgorithmException e) { + e.printStackTrace(); + } + content = null; + // 将sha1加密后的字符串可与signature对比,标识该请求来源于微信 + + return tmpStr != null ? tmpStr.equals(signature.toUpperCase()) : false; + } + + /** + * 将字节数组转换为十六进制字符串 + * + * @param byteArray + * @return + */ + private static String byteToStr(byte[] byteArray) { + String strDigest = ""; + for (int i = 0; i < byteArray.length; i++) { + strDigest += byteToHexStr(byteArray[i]); + } + return strDigest; + } + + /** + * 将字节转换为十六进制字符串 + * + * @param mByte + * @return + */ + private static String byteToHexStr(byte mByte) { + char[] Digit = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F' }; + char[] tempArr = new char[2]; + tempArr[0] = Digit[(mByte >>> 4) & 0X0F]; + tempArr[1] = Digit[mByte & 0X0F]; + String s = new String(tempArr); + return s; + } + public static void sort(String a[]) { + for (int i = 0; i < a.length - 1; i++) { + for (int j = i + 1; j < a.length; j++) { + if (a[j].compareTo(a[i]) < 0) { + String temp = a[i]; + a[i] = a[j]; + a[j] = temp; + } + } + } + } +} diff --git a/yxt_supervise/supervise-customer/supervise-customer-biz/src/main/java/com/yxt/supervise/customer/biz/util/XmlUtil.java b/yxt_supervise/supervise-customer/supervise-customer-biz/src/main/java/com/yxt/supervise/customer/biz/util/XmlUtil.java new file mode 100644 index 00000000..90effbb7 --- /dev/null +++ b/yxt_supervise/supervise-customer/supervise-customer-biz/src/main/java/com/yxt/supervise/customer/biz/util/XmlUtil.java @@ -0,0 +1,201 @@ +package com.yxt.supervise.customer.biz.util;//package com.supervise.rms.biz.util; +// +// +//import com.mysql.cj.util.StringUtils; +//import org.dom4j.Document; +//import org.dom4j.DocumentHelper; +//import org.dom4j.Element; +// +//import java.lang.reflect.Field; +//import java.util.HashMap; +//import java.util.List; +//import java.util.Map; +// +///** +// * xml相关的工具类 +// * +// * @author yang.y +// */ +//@SuppressWarnings("unchecked") +//public class XmlUtil { +// +// /** +// * xml字符串转换成bean对象 +// * +// * @param xmlStr xml字符串 +// * @param clazz 待转换的class +// * @return 转换后的对象 +// */ +// public static Object xmlStrToBean(String xmlStr, Class clazz) { +// Object obj = null; +// try { +// // 将xml格式的数据转换成Map对象 +// Map map = xmlStrToMap(xmlStr); +// // 将map对象的数据转换成Bean对象 +// obj = mapToBean(map, clazz); +// } catch (Exception e) { +// e.printStackTrace(); +// } +// return obj; +// } +// +// /** +// * 将xml格式的字符串转换成Map对象 +// * +// * @param xmlStr xml格式的字符串 +// * @return Map对象 +// * @throws Exception 异常 +// */ +// public static Map xmlStrToMap(String xmlStr) throws Exception { +// if (StringUtils.isNullOrEmpty(xmlStr)) { +// return null; +// } +// Map map = new HashMap(); +// // 将xml格式的字符串转换成Document对象 +// Document doc = DocumentHelper.parseText(xmlStr); +// // 获取根节点 +// Element root = doc.getRootElement(); +// // 获取根节点下的所有元素 +// List children = root.elements(); +// // 循环所有子元素 +// if (children != null && children.size() > 0) { +// for (int i = 0; i < children.size(); i++) { +// Element child = (Element) children.get(i); +// map.put(child.getName(), child.getTextTrim()); +// } +// } +// return map; +// } +// +// /** +// * 将xml格式字符串转换成Bean对象 +// * 多级子节点递归遍历 +// * +// * @param xmlStr +// * @param clazz +// * @return +// * @throws Exception +// */ +// public static Object xmlStrToJavaBean(String xmlStr, Class clazz) { +// if (StringUtils.isNullOrEmpty(xmlStr)) { +// return null; +// } +// Object obj = null; +// Map map = new HashMap(); +// // 将xml格式的字符串转换成Document对象 +// Document doc; +// try { +// doc = DocumentHelper.parseText(xmlStr); +// +// // 获取根节点 +// Element root = doc.getRootElement(); +// map = elementToMap(root, map); +// // 将map对象的数据转换成Bean对象 +// obj = mapToBean(map, clazz); +// } catch (Exception e) { +// e.printStackTrace(); +// } +// return obj; +// } +// +// /** +// * 递归遍历xml子节点,转换Map +// * +// * @param element +// * @param map +// * @return +// */ +// public static Map elementToMap(Element element, Map map) { +// if (element == null || map == null) +// return null; +// List children = element.elements(); +// if (children != null && children.size() > 0) { +// for (int i = 0; i < children.size(); i++) { +// Element child = (Element) children.get(i); +// if (child.elements() != null && child.elements().size() > 0) +// elementToMap(child, map); +// else +// map.put(child.getName(), child.getTextTrim()); +// } +// } +// return map; +// } +// +// /** +// * 将Map对象通过反射机制转换成Bean对象 +// * +// * @param map 存放数据的map对象 +// * @param clazz 待转换的class +// * @return 转换后的Bean对象 +// * @throws Exception 异常 +// */ +// public static Object mapToBean(Map map, Class clazz) throws Exception { +// Object obj = clazz.newInstance(); +// if (map != null && map.size() > 0) { +// for (Map.Entry entry : map.entrySet()) { +// String propertyName = entry.getKey(); +// Object value = entry.getValue(); +// String setMethodName = "set" + propertyName.substring(0, 1).toUpperCase() + propertyName.substring(1); +// Field field = getClassField(clazz, propertyName); +// if (field != null) { +// Class fieldTypeClass = field.getType(); +// value = convertValType(value, fieldTypeClass); +// clazz.getMethod(setMethodName, field.getType()).invoke(obj, value); +// } +// } +// } +// return obj; +// } +// +// /** +// * 将Object类型的值,转换成bean对象属性里对应的类型值 +// * +// * @param value Object对象值 +// * @param fieldTypeClass 属性的类型 +// * @return 转换后的值 +// */ +// private static Object convertValType(Object value, Class fieldTypeClass) { +// Object retVal = null; +// if (Long.class.getName().equals(fieldTypeClass.getName()) +// || long.class.getName().equals(fieldTypeClass.getName())) { +// retVal = Long.parseLong(value.toString()); +// } else if (Integer.class.getName().equals(fieldTypeClass.getName()) +// || int.class.getName().equals(fieldTypeClass.getName())) { +// retVal = Integer.parseInt(value.toString()); +// } else if (Float.class.getName().equals(fieldTypeClass.getName()) +// || float.class.getName().equals(fieldTypeClass.getName())) { +// retVal = Float.parseFloat(value.toString()); +// } else if (Double.class.getName().equals(fieldTypeClass.getName()) +// || double.class.getName().equals(fieldTypeClass.getName())) { +// retVal = Double.parseDouble(value.toString()); +// } else { +// retVal = value; +// } +// return retVal; +// } +// +// /** +// * 获取指定字段名称查找在class中的对应的Field对象(包括查找父类) +// * +// * @param clazz 指定的class +// * @param fieldName 字段名称 +// * @return Field对象 +// */ +// private static Field getClassField(Class clazz, String fieldName) { +// if (Object.class.getName().equals(clazz.getName())) { +// return null; +// } +// Field[] declaredFields = clazz.getDeclaredFields(); +// for (Field field : declaredFields) { +// if (field.getName().equals(fieldName)) { +// return field; +// } +// } +// +// Class superClass = clazz.getSuperclass(); +// if (superClass != null) {// 简单的递归一下 +// return getClassField(superClass, fieldName); +// } +// return null; +// } +//} diff --git a/yxt_supervise/supervise-customer/supervise-customer-biz/src/main/java/com/yxt/supervise/customer/biz/util/applet/MD5.java b/yxt_supervise/supervise-customer/supervise-customer-biz/src/main/java/com/yxt/supervise/customer/biz/util/applet/MD5.java new file mode 100644 index 00000000..4ccb91a8 --- /dev/null +++ b/yxt_supervise/supervise-customer/supervise-customer-biz/src/main/java/com/yxt/supervise/customer/biz/util/applet/MD5.java @@ -0,0 +1,29 @@ +package com.yxt.supervise.customer.biz.util.applet; + +import java.security.MessageDigest; + +public class MD5 { + private MD5() { + } + + /* * 生成 MD5 + * + * @param data 待处理数据 + * @return MD5结果 + */ + public static String getMessageDigest(String data) { + StringBuilder sb = new StringBuilder(); + try { + MessageDigest md = MessageDigest.getInstance("MD5"); + byte[] array = md.digest(data.getBytes("UTF-8")); + + for (byte item : array) { + sb.append(Integer.toHexString((item & 0xFF) | 0x100).substring(1, 3)); + } + } catch (Exception e) { + return null; + } + return sb.toString().toUpperCase(); + } + +} diff --git a/yxt_supervise/supervise-customer/supervise-customer-biz/src/main/java/com/yxt/supervise/customer/biz/util/applet/TemplateData.java b/yxt_supervise/supervise-customer/supervise-customer-biz/src/main/java/com/yxt/supervise/customer/biz/util/applet/TemplateData.java new file mode 100644 index 00000000..a1e3449a --- /dev/null +++ b/yxt_supervise/supervise-customer/supervise-customer-biz/src/main/java/com/yxt/supervise/customer/biz/util/applet/TemplateData.java @@ -0,0 +1,47 @@ +package com.yxt.supervise.customer.biz.util.applet; + +/** + * 模板详细信息 + * 根据需求自己更改 + */ +public class TemplateData { + private String value; + private String color; + + public TemplateData() { + } + + public TemplateData(String value, String color) { + this.value = value; + this.color = color; + } + + /** + * @return the value + */ + public String getValue() { + return value; + } + + /** + * @param value the value to set + */ + public void setValue(String value) { + this.value = value; + } + + /** + * @return the color + */ + public String getColor() { + return color; + } + + /** + * @param color the color to set + */ + public void setColor(String color) { + this.color = color; + } + +} diff --git a/yxt_supervise/supervise-customer/supervise-customer-biz/src/main/java/com/yxt/supervise/customer/biz/util/applet/WX_HttpsUtil.java b/yxt_supervise/supervise-customer/supervise-customer-biz/src/main/java/com/yxt/supervise/customer/biz/util/applet/WX_HttpsUtil.java new file mode 100644 index 00000000..822cf999 --- /dev/null +++ b/yxt_supervise/supervise-customer/supervise-customer-biz/src/main/java/com/yxt/supervise/customer/biz/util/applet/WX_HttpsUtil.java @@ -0,0 +1,80 @@ +package com.yxt.supervise.customer.biz.util.applet; + + +import com.yxt.supervise.customer.biz.util.MyX509TrustManager; +import net.sf.json.JSONObject; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import javax.net.ssl.HttpsURLConnection; +import javax.net.ssl.SSLContext; +import javax.net.ssl.SSLSocketFactory; +import javax.net.ssl.TrustManager; +import java.io.BufferedReader; +import java.io.InputStream; +import java.io.InputStreamReader; +import java.io.OutputStream; +import java.net.ConnectException; +import java.net.URL; + +public class WX_HttpsUtil { + + private static Logger log = LoggerFactory.getLogger(WX_HttpsUtil.class); + + /** + * 发送https请求 + * + * @param requestUrl 请求地址 + * @param requestMethod 请求方式(GET、POST) + * @param outputStr 提交的数据 + * @return JSONObject(通过JSONObject.get ( key)的方式获取json对象的属性值) + */ + public static JSONObject httpsRequest(String requestUrl, String requestMethod, String outputStr) { + JSONObject jsonObject = null; + try { + // 创建SSLContext对象,并使用我们指定的信任管理器初始化 + TrustManager[] tm = {new MyX509TrustManager()}; + SSLContext sslContext = SSLContext.getInstance("SSL", "SunJSSE"); + sslContext.init(null, tm, new java.security.SecureRandom()); + // 从上述SSLContext对象中得到SSLSocketFactory对象 + SSLSocketFactory ssf = sslContext.getSocketFactory(); + URL url = new URL(requestUrl); + HttpsURLConnection conn = (HttpsURLConnection) url.openConnection(); + conn.setSSLSocketFactory(ssf); + conn.setDoOutput(true); + conn.setDoInput(true); + conn.setUseCaches(false); + // 设置请求方式(GET/POST) + conn.setRequestMethod(requestMethod); + // 当outputStr不为null时向输出流写数据 + if (null != outputStr) { + OutputStream outputStream = conn.getOutputStream(); + // 注意编码格式 + outputStream.write(outputStr.getBytes("UTF-8")); + outputStream.close(); + } + // 从输入流读取返回内容 + InputStream inputStream = conn.getInputStream(); + InputStreamReader inputStreamReader = new InputStreamReader(inputStream, "utf-8"); + BufferedReader bufferedReader = new BufferedReader(inputStreamReader); + String str = null; + StringBuffer buffer = new StringBuffer(); + while ((str = bufferedReader.readLine()) != null) { + buffer.append(str); + } + // 释放资源 + bufferedReader.close(); + inputStreamReader.close(); + inputStream.close(); + inputStream = null; + conn.disconnect(); + jsonObject = JSONObject.fromObject(buffer.toString()); + } catch (ConnectException ce) { + log.error("连接超时:{}", ce); + } catch (Exception e) { + log.error("https请求异常:{}", e); + } + return jsonObject; + } + +} diff --git a/yxt_supervise/supervise-customer/supervise-customer-biz/src/main/java/com/yxt/supervise/customer/biz/util/applet/WX_TemplateMsgUtil.java b/yxt_supervise/supervise-customer/supervise-customer-biz/src/main/java/com/yxt/supervise/customer/biz/util/applet/WX_TemplateMsgUtil.java new file mode 100644 index 00000000..3985a66c --- /dev/null +++ b/yxt_supervise/supervise-customer/supervise-customer-biz/src/main/java/com/yxt/supervise/customer/biz/util/applet/WX_TemplateMsgUtil.java @@ -0,0 +1,112 @@ +package com.yxt.supervise.customer.biz.util.applet; + + +import net.sf.json.JSONObject; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import java.util.Map; + +public class WX_TemplateMsgUtil { + + private static Logger log = LoggerFactory.getLogger(WX_TemplateMsgUtil.class); + + /** + * 封装模板详细信息 + * + * @return + */ + public static JSONObject packJsonmsg(Map param) { + JSONObject json = new JSONObject(); + for (Map.Entry entry : param.entrySet()) { + JSONObject keyJson = new JSONObject(); + TemplateData dta = entry.getValue(); + keyJson.put("value", dta.getValue()); + keyJson.put("color", dta.getColor()); + json.put(entry.getKey(), keyJson); + } + return json; + } + + /** + * 根据模板的编号 新增并获取模板ID + * + * @param templateSerialNumber 模板库中模板的 "编号" + * @return 模板ID + */ + public static String getWXTemplateMsgId(String templateSerialNumber, String token) { + String tmpurl = "https://api.weixin.qq.com/cgi-bin/template/api_add_template?access_token=" + token; + JSONObject json = new JSONObject(); + json.put("template_id_short", templateSerialNumber); + JSONObject resultJson = WX_HttpsUtil.httpsRequest(tmpurl, "POST", json.toString()); + // JSONObject resultJson = JSONObject.fromObject(result); + String errmsg = (String) resultJson.get("errmsg"); + log.info("获取模板编号返回信息:" + errmsg); + if (!"ok".equals(errmsg)) { + return "error"; + } + String templateId = (String) resultJson.get("template_id"); + return templateId; + } + + /** + * 根据模板ID 删除模板消息 + * + * @param templateId 模板ID + * @return + */ + public static String deleteWXTemplateMsgById(String templateId, String token) { + String tmpurl = "https://api.weixin.qq.com/cgi-bin/template/del_private_template?access_token=" + token; + JSONObject json = new JSONObject(); + json.put("template_id", templateId); + try { + JSONObject resultJson = WX_HttpsUtil.httpsRequest(tmpurl, "POST", json.toString()); + // JSONObject resultJson = new JSONObject(result); + log.info("删除" + templateId + "模板消息,返回CODE:" + resultJson.get("errcode")); + String errmsg = (String) resultJson.get("errmsg"); + if (!"ok".equals(errmsg)) { + return "error"; + } + } catch (Exception e) { + e.printStackTrace(); + } + return "success"; + } + + + /** + * 发送微信消息(模板消息) + * + * @param touser 用户 OpenID + * @param templatId 模板消息ID + * @param page URL置空,则在发送后,点击模板消息会进入一个空白页面(ios),或无法点击(android)。 + * @param formId + * @param data 详细内容 + * @return + */ + public static String sendWechatMsgToUser(String touser, String templatId, String page, String formId, JSONObject data, String token) { + String tmpurl = "https://api.weixin.qq.com/cgi-bin/message/wxopen/template/send?access_token=" + token; + + JSONObject json = new JSONObject(); + json.put("touser", touser); + json.put("form_id", formId); + json.put("page", page); + json.put("template_id", templatId); + json.put("data", data); + try { + JSONObject resultJson = WX_HttpsUtil.httpsRequest(tmpurl, "POST", json.toString()); + // JSONObject resultJson = new JSONObject(result); + log.info("发送微信消息返回信息:" + resultJson.get("errcode")); + String errmsg = (String) resultJson.get("errmsg"); + if (!"ok".equals(errmsg)) { //如果为errmsg为ok,则代表发送成功,公众号推送信息给用户了。 + return "error"; + } + } catch (Exception e) { + e.printStackTrace(); + return "error"; + } + + return "success"; + } + +} diff --git a/yxt_supervise/supervise-customer/supervise-customer-biz/src/main/java/com/yxt/supervise/customer/biz/util/applet/WechatConfig.java b/yxt_supervise/supervise-customer/supervise-customer-biz/src/main/java/com/yxt/supervise/customer/biz/util/applet/WechatConfig.java new file mode 100644 index 00000000..50c47682 --- /dev/null +++ b/yxt_supervise/supervise-customer/supervise-customer-biz/src/main/java/com/yxt/supervise/customer/biz/util/applet/WechatConfig.java @@ -0,0 +1,39 @@ +package com.yxt.supervise.customer.biz.util.applet; + +import org.apache.http.conn.ssl.SSLConnectionSocketFactory; +import org.apache.http.conn.ssl.SSLContexts; + +import javax.net.ssl.SSLContext; +import java.io.InputStream; +import java.security.KeyStore; + +@SuppressWarnings("deprecation") +public class WechatConfig { + + private static SSLConnectionSocketFactory sslcsf; + + public static SSLConnectionSocketFactory getSslcsf() { + if (null == sslcsf) { + setSsslcsf(); + } + return sslcsf; + } + + private static void setSsslcsf() { + try { + KeyStore keyStore = KeyStore.getInstance("PKCS12"); + Thread.currentThread().getContextClassLoader(); + InputStream instream = new WechatRefundApiResult().getClass().getResourceAsStream("certName"); + try { + keyStore.load(instream, "mchId".toCharArray()); + } finally { + instream.close(); + } + SSLContext sslcontext = SSLContexts.custom().loadKeyMaterial(keyStore, "mchId".toCharArray()).build(); + sslcsf = new SSLConnectionSocketFactory(sslcontext, new String[]{"TLSv1"}, null, SSLConnectionSocketFactory.BROWSER_COMPATIBLE_HOSTNAME_VERIFIER); + } catch (Exception e) { + e.printStackTrace(); + } + } + +} diff --git a/yxt_supervise/supervise-customer/supervise-customer-biz/src/main/java/com/yxt/supervise/customer/biz/util/applet/WechatRefundApiResult.java b/yxt_supervise/supervise-customer/supervise-customer-biz/src/main/java/com/yxt/supervise/customer/biz/util/applet/WechatRefundApiResult.java new file mode 100644 index 00000000..76990b8c --- /dev/null +++ b/yxt_supervise/supervise-customer/supervise-customer-biz/src/main/java/com/yxt/supervise/customer/biz/util/applet/WechatRefundApiResult.java @@ -0,0 +1,214 @@ +package com.yxt.supervise.customer.biz.util.applet; + +public class WechatRefundApiResult { + private String return_code; + private String return_msg; + + private String result_code; + private String err_code; + private String err_code_des; + private String appid; + private String mch_id; + private String device_info; + private String nonce_str; + private String sign; + private String transaction_id; + private String out_trade_no; + private String out_refund_no; + private String refund_id; + private String refund_channel; + private String refund_fee; + private String settlement_refund_fee; + private String total_fee; + private String settlement_total_fee; + private String fee_type; + private String cash_fee; + private String cash_refund_fee; + private String refund_status; + + public String getRefund_status() { + return refund_status; + } + + public void setRefund_status(String refund_status) { + this.refund_status = refund_status; + } + + public String getReturn_code() { + return return_code; + } + + public void setReturn_code(String return_code) { + this.return_code = return_code; + } + + public String getReturn_msg() { + return return_msg; + } + + public void setReturn_msg(String return_msg) { + this.return_msg = return_msg; + } + + public String getResult_code() { + return result_code; + } + + public void setResult_code(String result_code) { + this.result_code = result_code; + } + + public String getErr_code() { + return err_code; + } + + public void setErr_code(String err_code) { + this.err_code = err_code; + } + + public String getErr_code_des() { + return err_code_des; + } + + public void setErr_code_des(String err_code_des) { + this.err_code_des = err_code_des; + } + + public String getAppid() { + return appid; + } + + public void setAppid(String appid) { + this.appid = appid; + } + + public String getMch_id() { + return mch_id; + } + + public void setMch_id(String mch_id) { + this.mch_id = mch_id; + } + + public String getDevice_info() { + return device_info; + } + + public void setDevice_info(String device_info) { + this.device_info = device_info; + } + + public String getNonce_str() { + return nonce_str; + } + + public void setNonce_str(String nonce_str) { + this.nonce_str = nonce_str; + } + + public String getSign() { + return sign; + } + + public void setSign(String sign) { + this.sign = sign; + } + + public String getTransaction_id() { + return transaction_id; + } + + public void setTransaction_id(String transaction_id) { + this.transaction_id = transaction_id; + } + + public String getOut_trade_no() { + return out_trade_no; + } + + public void setOut_trade_no(String out_trade_no) { + this.out_trade_no = out_trade_no; + } + + public String getOut_refund_no() { + return out_refund_no; + } + + public void setOut_refund_no(String out_refund_no) { + this.out_refund_no = out_refund_no; + } + + public String getRefund_id() { + return refund_id; + } + + public void setRefund_id(String refund_id) { + this.refund_id = refund_id; + } + + public String getRefund_channel() { + return refund_channel; + } + + public void setRefund_channel(String refund_channel) { + this.refund_channel = refund_channel; + } + + public String getRefund_fee() { + return refund_fee; + } + + public void setRefund_fee(String refund_fee) { + this.refund_fee = refund_fee; + } + + public String getSettlement_refund_fee() { + return settlement_refund_fee; + } + + public void setSettlement_refund_fee(String settlement_refund_fee) { + this.settlement_refund_fee = settlement_refund_fee; + } + + public String getTotal_fee() { + return total_fee; + } + + public void setTotal_fee(String total_fee) { + this.total_fee = total_fee; + } + + public String getSettlement_total_fee() { + return settlement_total_fee; + } + + public void setSettlement_total_fee(String settlement_total_fee) { + this.settlement_total_fee = settlement_total_fee; + } + + public String getFee_type() { + return fee_type; + } + + public void setFee_type(String fee_type) { + this.fee_type = fee_type; + } + + public String getCash_fee() { + return cash_fee; + } + + public void setCash_fee(String cash_fee) { + this.cash_fee = cash_fee; + } + + public String getCash_refund_fee() { + return cash_refund_fee; + } + + public void setCash_refund_fee(String cash_refund_fee) { + this.cash_refund_fee = cash_refund_fee; + } + + +} diff --git a/yxt_supervise/supervise-customer/supervise-customer-biz/src/main/java/com/yxt/supervise/customer/biz/util/applet/WechatUtil.java b/yxt_supervise/supervise-customer/supervise-customer-biz/src/main/java/com/yxt/supervise/customer/biz/util/applet/WechatUtil.java new file mode 100644 index 00000000..587fba2b --- /dev/null +++ b/yxt_supervise/supervise-customer/supervise-customer-biz/src/main/java/com/yxt/supervise/customer/biz/util/applet/WechatUtil.java @@ -0,0 +1,296 @@ +package com.yxt.supervise.customer.biz.util.applet; + +//import com.supervise.rms.biz.util.CharUtil; +//import com.supervise.rms.biz.util.MapUtils; +//import com.supervise.rms.biz.util.XmlUtil; +import org.apache.http.HttpEntity; +import org.apache.http.HttpResponse; +import org.apache.http.client.HttpClient; +import org.apache.http.client.config.RequestConfig; +import org.apache.http.client.methods.CloseableHttpResponse; +import org.apache.http.client.methods.HttpPost; +import org.apache.http.config.RegistryBuilder; +import org.apache.http.conn.socket.ConnectionSocketFactory; +import org.apache.http.conn.socket.PlainConnectionSocketFactory; +import org.apache.http.conn.ssl.SSLConnectionSocketFactory; +import org.apache.http.entity.StringEntity; +import org.apache.http.impl.client.CloseableHttpClient; +import org.apache.http.impl.client.HttpClientBuilder; +import org.apache.http.impl.client.HttpClients; +import org.apache.http.impl.conn.BasicHttpClientConnectionManager; +import org.apache.http.util.EntityUtils; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import java.io.IOException; +import java.io.UnsupportedEncodingException; +import java.net.URLEncoder; +import java.text.SimpleDateFormat; +import java.util.*; + +/** + *

    Title: 微信退款工具类

    + *

    Description: 微信退款工具类,通过充值客户端的不同初始化不同的工具类,得到相应微信退款相关的appid和muchid

    + * + * @author xubo + * @date 2017年6月6日 下午5:05:03 + */ +public class WechatUtil { + /** + * 充值客户端类型--微信公众号 + */ + public static Integer CLIENTTYPE_WX = 2; + /** + * 充值客户端类型--app + */ + public static Integer CLIENTTYPE_APP = 1; + private static Logger logger = LoggerFactory.getLogger(WechatUtil.class); + + /** + * 方法描述:微信退款逻辑 + * 创建时间:2017年4月12日 上午11:04:25 + * 作者: xubo + * + * @param + * @return + */ + /* public static WechatRefundApiResult wxRefund(String out_trade_no, Double orderMoney, Double refundMoney) { + //初始化请求微信服务器的配置信息包括appid密钥等 + //转换金钱格式 + BigDecimal bdOrderMoney = new BigDecimal(orderMoney, MathContext.DECIMAL32); + BigDecimal bdRefundMoney = new BigDecimal(refundMoney, MathContext.DECIMAL32); + //构建请求参数 + Map params = buildRequsetMapParam(out_trade_no, bdOrderMoney, bdRefundMoney); + String mapToXml = MapUtils.convertMap2Xml(params); + //请求微信 + String reponseXml = sendSSLPostToWx(mapToXml, WechatConfig.getSslcsf()); + WechatRefundApiResult result = (WechatRefundApiResult) XmlUtil.xmlStrToBean(reponseXml, WechatRefundApiResult.class); + return result; + }*/ + + /** + * 方法描述:得到请求微信退款请求的参数 + * 创建时间:2017年6月8日 上午11:27:02 + * 作者: xubo + * + * @param + * @return + */ + /* private static Map buildRequsetMapParam(String out_trade_no, BigDecimal bdOrderMoney, BigDecimal bdRefundMoney) { + Map params = new HashMap(); + //微信分配的公众账号ID(企业号corpid即为此appId) + params.put("appid", ResourceUtil.getConfigByName("wx.appId")); + //微信支付分配的商户号 + params.put("mch_id", ResourceUtil.getConfigByName("wx.mchId")); + //随机字符串,不长于32位。推荐随机数生成算法 + params.put("nonce_str", CharUtil.getRandomString(16)); + //商户侧传给微信的订单号 + params.put("out_trade_no", out_trade_no); + //商户系统内部的退款单号,商户系统内部唯一,同一退款单号多次请求只退一笔 + params.put("out_refund_no", getBundleId()); + //订单总金额,单位为分,只能为整数 + params.put("total_fee", bdOrderMoney.multiply(new BigDecimal(100)).intValue()); + //退款总金额,订单总金额,单位为分,只能为整数 + params.put("refund_fee", bdRefundMoney.multiply(new BigDecimal(100)).intValue()); + //操作员帐号, 默认为商户号 + params.put("op_user_id", ResourceUtil.getConfigByName("wx.mchId")); + //签名前必须要参数全部写在前面 + params.put("sign", arraySign(params, ResourceUtil.getConfigByName("wx.paySignKey"))); + return params; + }*/ + + /** + * ResourceUtil.getConfigByName("wx.refundUrl") + * 请求微信https + **/ + public static String sendSSLPostToWx(String mapToXml, SSLConnectionSocketFactory sslcsf, String refundUrl) { + logger.info("*******退款(WX Request:" + mapToXml); + HttpPost httPost = new HttpPost(refundUrl); + httPost.addHeader("Connection", "keep-alive"); + httPost.addHeader("Accept", "*/*"); + httPost.addHeader("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8"); + httPost.addHeader("Host", "api.mch.weixin.qq.com"); + httPost.addHeader("X-Requested-With", "XMLHttpRequest"); + httPost.addHeader("Cache-Control", "max-age=0"); + httPost.addHeader("User-Agent", "Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.0) "); + httPost.setEntity(new StringEntity(mapToXml, "UTF-8")); + CloseableHttpClient httpClient = HttpClients.custom().setSSLSocketFactory(sslcsf).build(); + CloseableHttpResponse response = null; + try { + response = httpClient.execute(httPost); + HttpEntity entity = response.getEntity(); + String xmlStr = EntityUtils.toString(entity, "UTF-8"); + logger.info("*******退款(WX Response:" + xmlStr); + return xmlStr; + } catch (Exception e) { + logger.error(e.getMessage(), e); + return null; + } finally { + try { + if (response != null) { + response.close(); + } + } catch (IOException e) { + logger.error(e.getMessage(), e); + } + } + } + + /** + * 支付交易ID + */ + public static String getBundleId() { + SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMMddHHmmssSSS"); + String tradeno = dateFormat.format(new Date()); + String str = "000000" + (int) (Math.random() * 1000000); + tradeno = tradeno + str.substring(str.length() - 6); + return tradeno; + } + + /** + * 方法描述:根据签名加密请求参数 + * 创建时间:2017年6月8日 上午11:28:52 + * 作者: xubo + * + * @param + * @return + */ + public static String arraySign(Map params, String paySignKey) { + boolean encode = false; + Set keysSet = params.keySet(); + Object[] keys = keysSet.toArray(); + Arrays.sort(keys); + StringBuffer temp = new StringBuffer(); + boolean first = true; + for (Object key : keys) { + if (first) { + first = false; + } else { + temp.append("&"); + } + temp.append(key).append("="); + Object value = params.get(key); + String valueString = ""; + if (null != value) { + valueString = value.toString(); + } + if (encode) { + try { + temp.append(URLEncoder.encode(valueString, "UTF-8")); + } catch (UnsupportedEncodingException e) { + e.printStackTrace(); + } + } else { + temp.append(valueString); + } + } + temp.append("&key="); + temp.append(paySignKey); + System.out.println(temp.toString()); + String packageSign = MD5.getMessageDigest(temp.toString()); + return packageSign; + } + + /** + * 请求,只请求一次,不做重试 + * + * @param url + * @param data + * @return + * @throws Exception + */ + public static String requestOnce(final String url, String data) throws Exception { + BasicHttpClientConnectionManager connManager; + connManager = new BasicHttpClientConnectionManager( + RegistryBuilder.create() + .register("http", PlainConnectionSocketFactory.getSocketFactory()) + .register("https", SSLConnectionSocketFactory.getSocketFactory()) + .build(), + null, + null, + null + ); + + HttpClient httpClient = HttpClientBuilder.create() + .setConnectionManager(connManager) + .build(); + + HttpPost httpPost = new HttpPost(url); + + RequestConfig requestConfig = RequestConfig.custom() + .setSocketTimeout(5000) + .setConnectTimeout(5000) + .setConnectionRequestTimeout(10000).build(); + + httpPost.setConfig(requestConfig); + + StringEntity postEntity = new StringEntity(data, "UTF-8"); + httpPost.addHeader("Content-Type", "text/xml"); + httpPost.addHeader("User-Agent", "wxpay sdk java v1.0 " + "mchId"); + httpPost.setEntity(postEntity); + + HttpResponse httpResponse = httpClient.execute(httpPost); + HttpEntity httpEntity = httpResponse.getEntity(); + String reusltObj = EntityUtils.toString(httpEntity, "UTF-8"); + logger.info("请求结果:" + reusltObj); + return reusltObj; + + } + + /** + * 方法描述:微信查询退款逻辑 + * 创建时间:2017年4月12日 上午11:04:25 + * 作者: xubo + * + * @param + * @return + */ + + +// public Map wxRefundquery(String out_trade_no, String out_refund_no) { +// Map params = new HashMap(); +// //微信分配的公众账号ID(企业号corpid即为此appId) +// params.put("appid", "xx"); +// //微信支付分配的商户号 +// params.put("mch_id", "xx"); +// //随机字符串,不长于32位。推荐随机数生成算法 +// params.put("nonce_str", CharUtil.getRandomString(16)); +// //商户侧传给微信的订单号 +// params.put("out_trade_no", out_trade_no); +// //签名前必须要参数全部写在前面 +// //签名 +// params.put("sign", arraySign(params, "wx.paySignKey")); +// String mapToXml = MapUtils.convertMap2Xml(params); +// HttpPost httPost = new HttpPost("refundqueryUrl"); +// httPost.addHeader("Connection", "keep-alive"); +// httPost.addHeader("Accept", "*/*"); +// httPost.addHeader("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8"); +// httPost.addHeader("Host", "api.mch.weixin.qq.com"); +// httPost.addHeader("X-Requested-With", "XMLHttpRequest"); +// httPost.addHeader("Cache-Control", "max-age=0"); +// httPost.addHeader("User-Agent", "Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.0) "); +// httPost.setEntity(new StringEntity(mapToXml, "UTF-8")); +// CloseableHttpClient httpClient = HttpClients.custom().setSSLSocketFactory(WechatConfig.getSslcsf()).build(); +// CloseableHttpResponse response = null; +// try { +// response = httpClient.execute(httPost); +// HttpEntity entity = response.getEntity(); +// String xmlStr = EntityUtils.toString(entity, "UTF-8"); +// System.out.println(xmlStr); +// Map result = XmlUtil.xmlStrToMap(xmlStr);//.xmlStrToBean(xmlStr, WechatRefundApiResult.class); +// return result; +// //将信息保存到数据库 +// } catch (Exception e) { +// logger.error(e.getMessage(), e); +// return null; +// } finally { +// try { +// if (response != null) { +// response.close(); +// } +// } catch (IOException e) { +// logger.error(e.getMessage(), e); +// } +// } +// } +} diff --git a/yxt_supervise/supervise-customer/supervise-customer-biz/src/main/java/com/yxt/supervise/customer/biz/wechat/WechatApiService.java b/yxt_supervise/supervise-customer/supervise-customer-biz/src/main/java/com/yxt/supervise/customer/biz/wechat/WechatApiService.java new file mode 100644 index 00000000..821e7931 --- /dev/null +++ b/yxt_supervise/supervise-customer/supervise-customer-biz/src/main/java/com/yxt/supervise/customer/biz/wechat/WechatApiService.java @@ -0,0 +1,271 @@ +package com.yxt.supervise.customer.biz.wechat; + + +import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper; +import com.yxt.supervise.customer.biz.util.JedisLock; +import com.yxt.supervise.customer.biz.util.JsonUtils; +import com.yxt.supervise.customer.biz.util.MyX509TrustManager; +import net.sf.json.JSONObject; +import org.apache.commons.lang.StringUtils; +import org.apache.http.HttpResponse; +import org.apache.http.client.HttpClient; +import org.apache.http.client.config.RequestConfig; +import org.apache.http.client.methods.HttpGet; +import org.apache.http.impl.client.HttpClients; +import org.apache.http.util.EntityUtils; +import org.junit.Test; +import org.springframework.stereotype.Service; +import org.springframework.web.client.RestTemplate; +import redis.clients.jedis.Jedis; +import redis.clients.jedis.JedisPool; + +import javax.annotation.Resource; +import javax.net.ssl.HttpsURLConnection; +import javax.net.ssl.SSLContext; +import javax.net.ssl.SSLSocketFactory; +import javax.net.ssl.TrustManager; +import java.io.*; +import java.net.MalformedURLException; +import java.net.URL; +import java.security.KeyManagementException; +import java.security.NoSuchAlgorithmException; +import java.security.NoSuchProviderException; +import java.security.SecureRandom; +import java.util.HashMap; +import java.util.Map; + +/** + * 对接微信接口服务 + * Created by fei on 2017/4/24. + */ +@Service +public class WechatApiService { + public final static String access_token_url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=APPID&secret=APPSECRET"; + // 存放:1.token,2:获取token的时间,3.过期时间 + public final static Map accessTokenMap = new HashMap(); + private static final String WECHAT_API = "https://api.weixin.qq.com/cgi-bin"; + private static final String WECHAT_API_TOKEN = WECHAT_API + "/token"; + private static final String WECHAT_API_TICKET = WECHAT_API + "/ticket/getticket?type=jsapi&access_token="; + //private final HttpClient httpclient; + +// @Resource +// private SysAppletSetMapper appletSetMapper; +// private Jedis jedis; +// @Resource +// private JedisPool jedisPool; + public String getAccessToken() throws Exception { +// SysAppletSet appletSet = appletSetMapper.selectOne(new QueryWrapper<>()); +// if (null == appletSet) { +// throw new ApiMallPlusException("没有设置支付配置"); +// } + String appId="wx1d44e0fcd110351a"; + String appsecret="4764e32722a7d98656dea6afd9405701"; + String url="https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid="+appId+"&secret="+appsecret; + RestTemplate restTemplate=new RestTemplate(); + String re= restTemplate.getForObject(url,String.class); + com.alibaba.fastjson.JSONObject jsonObject= com.alibaba.fastjson.JSONObject.parseObject(re); + String at=jsonObject.getString("access_token"); + System.out.println(at); + return at; + } + +// public WechatApiService() { +// RequestConfig config = RequestConfig.custom() +// .setConnectTimeout(5000) +// .setSocketTimeout(20000) +// .setConnectionRequestTimeout(3000) +// .build(); +// httpclient = HttpClients.custom().setDefaultRequestConfig(config).build(); +// } +// +// /** +// * 发起https请求并获取结果 +// * +// * @param requestUrl 请求地址 +// * @param requestMethod 请求方式(GET、POST) +// * @param outputStr 提交的数据 +// * @return JSONObject(通过JSONObject.get ( key)的方式获取json对象的属性值) +// */ +// public static JSONObject handleRequest(String requestUrl, String requestMethod, String outputStr) { +// JSONObject jsonObject = null; +// +// try { +// URL url = new URL(requestUrl); +// HttpsURLConnection conn = (HttpsURLConnection) url.openConnection(); +// SSLContext ctx = SSLContext.getInstance("SSL", "SunJSSE"); +// TrustManager[] tm = {new MyX509TrustManager()}; +// ctx.init(null, tm, new SecureRandom()); +// SSLSocketFactory sf = ctx.getSocketFactory(); +// conn.setSSLSocketFactory(sf); +// conn.setDoInput(true); +// conn.setDoOutput(true); +// conn.setRequestMethod(requestMethod); +// conn.setUseCaches(false); +// +// if ("GET".equalsIgnoreCase(requestMethod)) { +// conn.connect(); +// } +// +// if (StringUtils.isNotEmpty(outputStr)) { +// OutputStream out = conn.getOutputStream(); +// out.write(outputStr.getBytes("utf-8")); +// out.close(); +// } +// +// InputStream in = conn.getInputStream(); +// BufferedReader br = new BufferedReader(new InputStreamReader(in, "utf-8")); +// StringBuffer buffer = new StringBuffer(); +// String line = null; +// +// while ((line = br.readLine()) != null) { +// buffer.append(line); +// } +// +// in.close(); +// conn.disconnect(); +// +// jsonObject = JSONObject.fromObject(buffer.toString()); +// } catch (MalformedURLException e) { +// e.printStackTrace(); +// } catch (IOException e) { +// e.printStackTrace(); +// } catch (NoSuchAlgorithmException e) { +// e.printStackTrace(); +// } catch (NoSuchProviderException e) { +// e.printStackTrace(); +// } catch (KeyManagementException e) { +// e.printStackTrace(); +// } +// return jsonObject; +// } +// +// /** +// * 获取默认公众号的 access_token +// * +// * @return access_token +// * @throws Exception +// */ +// +// +// +// +// /** +// * 获取 access_token +// * https://mp.weixin.qq.com/wiki?action=doc&id=mp1421140183 +// * +// * @return access_token +// * @throws Exception +// */ +// public String getAccessToken(String appid, String appSecret) throws Exception { +// +// String key = "access_token:" + appid; +// jedis = jedisPool.getResource(); +// if (jedis.ttl(key) > 30) { +// try { +// return jedis.get(key); +// } finally { +// jedis.close(); +// } +// +// } +// +// //https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=APPID&secret=APPSECRET +// String lockKey = "lock_" + key; +// JedisLock lock = new JedisLock(jedis, lockKey); +// boolean acquired = lock.acquire(); +// if (!acquired) { +// jedis.close(); +// throw new Exception("acquired lock: " + lockKey + " timeout"); +// } +// try { +// if (jedis.ttl(key) > 30) { +// try { +// return jedis.get(key); +// } finally { +// jedis.close(); +// } +// } +// +// HttpGet get = new HttpGet(WECHAT_API_TOKEN + "?grant_type=client_credential&appid=" + appid + "&secret=" + appSecret); +// HttpResponse response = httpclient.execute(get); +// String text = EntityUtils.toString(response.getEntity()); +// Map resultMap = JsonUtils.readJsonToMap(text); +// String accessToken = (String) resultMap.get("access_token"); +// int expiresIn = (int) resultMap.get("expires_in"); +// +// jedis.set(key, accessToken); +// jedis.expire(key, expiresIn); +// return accessToken; +// } finally { +// lock.release(); +// jedis.close(); +// } +// } +// +// /** +// * 获取默认公众号 jsapi_ticket +// * +// * @return jsapi_ticket +// * @throws Exception +// */ +// +// public String getJsTicket() throws Exception { +//// SysAppletSet appletSet = appletSetMapper.selectOne(new QueryWrapper<>()); +//// if (null == appletSet) { +//// throw new ApiMallPlusException("没有设置支付配置"); +//// } +//// return getJsTicket(appletSet.getAppid(), appletSet.getAppsecret()); +// return null; +// } +// +// +// /** +// * 获取 jsapi_ticket +// * https://mp.weixin.qq.com/wiki?action=doc&id=mp1421141115 +// * +// * @param appid +// * @param appSecret +// * @return ticket +// * @throws Exception +// */ +// public String getJsTicket(String appid, String appSecret) throws Exception { +// jedis = jedisPool.getResource(); +// String key = "jsapi_ticket:" + appid; +// +// if (jedis.ttl(key) > 30) { +// try { +// return jedis.get(key); +// } finally { +// jedis.close(); +// } +// } +// +// String lockKey = "lock_" + key; +// JedisLock lock = new JedisLock(jedis, lockKey); +// boolean acquired = lock.acquire(); +// if (!acquired) { +// jedis.close(); +// throw new Exception("acquired lock: " + lockKey + " timeout"); +// } +// +// try { +// if (jedis.ttl(key) > 30) { +// return jedis.get(key); +// } +// +// HttpGet get = new HttpGet(WECHAT_API_TICKET + getAccessToken(appid, appSecret)); +// HttpResponse response = httpclient.execute(get); +// String text = EntityUtils.toString(response.getEntity()); +// Map resultMap = JsonUtils.readJsonToMap(text); +// String ticket = (String) resultMap.get("ticket"); +// int expiresIn = (int) resultMap.get("expires_in"); +// +// jedis.set(key, ticket); +// jedis.expire(key, expiresIn); +// return ticket; +// } finally { +// lock.release(); +// jedis.close(); +// } +// } +} diff --git a/yxt_supervise/supervise-customer/supervise-customer-biz/src/main/java/com/yxt/supervise/customer/biz/wechat/WechatRest.java b/yxt_supervise/supervise-customer/supervise-customer-biz/src/main/java/com/yxt/supervise/customer/biz/wechat/WechatRest.java new file mode 100644 index 00000000..4ca3c9b6 --- /dev/null +++ b/yxt_supervise/supervise-customer/supervise-customer-biz/src/main/java/com/yxt/supervise/customer/biz/wechat/WechatRest.java @@ -0,0 +1,48 @@ +package com.yxt.supervise.customer.biz.wechat; + +import com.yxt.supervise.customer.biz.util.WeixinCheckoutUtil; +import io.swagger.annotations.Api; +import io.swagger.annotations.ApiOperation; +import org.apache.commons.lang3.StringUtils; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.web.bind.annotation.*; + +/** + * @author wangpengfei + * @date 2023/3/31 15:44 + */ +@Api(tags = "测试") +@RestController +@RequestMapping("v1/wechat") +public class WechatRest { + String token="yxthryy"; + @Autowired + WechatService wechatService; + @ApiOperation("token") + @GetMapping(value = "token") + public String wechate(String signature,String timestamp,String nonce,String echostr){ + String token=""; + if (signature != null && WeixinCheckoutUtil.checkSignature(signature, timestamp, nonce)) { + token=wechatService.push(); + } + + return token; + } + + @GetMapping(value = "authGet",produces = "text/plain;charset=utf-8") + public String authGet(@RequestParam(name = "signature", required = false) String signature, + @RequestParam(name = "timestamp", required = false) String timestamp, + @RequestParam(name = "nonce", required = false) String nonce, + @RequestParam(name = "echostr", required = false) String echostr) { + + if (StringUtils.isAnyBlank(signature, timestamp, nonce, echostr)) { + throw new IllegalArgumentException("请求参数非法,请核实!"); + } + if (WeixinCheckoutUtil.checkSignature( signature, timestamp, nonce)) { + return echostr; + } + return "非法请求"; + } + + +} diff --git a/yxt_supervise/supervise-customer/supervise-customer-biz/src/main/java/com/yxt/supervise/customer/biz/wechat/WechatService.java b/yxt_supervise/supervise-customer/supervise-customer-biz/src/main/java/com/yxt/supervise/customer/biz/wechat/WechatService.java new file mode 100644 index 00000000..12c9bd33 --- /dev/null +++ b/yxt_supervise/supervise-customer/supervise-customer-biz/src/main/java/com/yxt/supervise/customer/biz/wechat/WechatService.java @@ -0,0 +1,67 @@ +package com.yxt.supervise.customer.biz.wechat; + + +import lombok.extern.log4j.Log4j; +import lombok.extern.slf4j.Slf4j; +import net.sf.json.JSONObject; +import org.junit.Test; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Service; +import org.springframework.util.StringUtils; + +import javax.annotation.Resource; +import java.util.HashMap; +import java.util.Map; + +/** + * @author wangpengfei + * @date 2023/3/31 14:00 + */ +@Service +@Slf4j +public class WechatService { + @Autowired + private WechatApiService wechatApiService; + public String push() { + boolean flag = true; +// SysAppletSet appletSet = memberService.getSysAppletSet(0); +// if (null == appletSet) { +// log.error("没有设置支付配置:userId=" + umsMember.getId() + ",orderId=" + order.getId() + ",formId=" + formId); +// flag = false; +// } +// log.info("发送模版消息:userId=" + umsMember.getId() + ",orderId=" + order.getId() + ",formId=" + formId); +// if (StringUtils.isEmpty(formId)) { +// flag = false; +// log.error("发送模版消息:userId=" + umsMember.getId() + ",orderId=" + order.getId() + ",formId=" + formId); +// } + String accessToken = null; + if (flag) { + + try { + accessToken = wechatApiService.getAccessToken(); + +// String templateId = appletSet.getTemplateid1(); +// Map param = new HashMap(); +// param.put("keyword1", new TemplateData(DateUtils.format(order.getCreateTime(), "yyyy-MM-dd"), "#EE0000")); +// +// param.put("keyword2", new TemplateData(name, "#EE0000")); +// param.put("keyword3", new TemplateData(order.getOrderSn(), "#EE0000")); +// param.put("keyword3", new TemplateData(order.getPayAmount() + "", "#EE0000")); +// +// JSONObject jsonObject = JSONObject.fromObject(param); + JSONObject jsonObject = new JSONObject(); + //调用发送微信消息给用户的接口 ********这里写自己在微信公众平台拿到的模板ID + String weiXinOpenId=""; + String templateId="fVgBuwpLC43YkeGWfl1Vw0mW0Qu5WP2giD77TfKAEc4"; + String orderId=""; +// WX_TemplateMsgUtil.sendWechatMsgToUser(weiXinOpenId, templateId, page + "?id=" + orderId, +// formId, jsonObject, accessToken); + + } catch (Exception e) { + e.printStackTrace(); + } + + } + return accessToken; + } +}