Переглянути джерело

微信会话内容存储开发

anderx 5 місяців тому
батько
коміт
b0a56a2d48

+ 1 - 0
pom.xml

@@ -390,6 +390,7 @@
 			<version>1.64</version>
 		</dependency>
 
+
 	</dependencies>
 	<build>
 		<resources>

+ 212 - 0
src/main/java/com/kede/common/utils/HttpUtils.java

@@ -0,0 +1,212 @@
+package com.kede.common.utils;
+
+import com.alibaba.fastjson.JSON;
+import com.alibaba.fastjson.JSONObject;
+import org.apache.http.HttpResponse;
+import org.apache.http.HttpStatus;
+import org.apache.http.ParseException;
+import org.apache.http.client.HttpClient;
+import org.apache.http.client.methods.HttpGet;
+import org.apache.http.client.methods.HttpPost;
+import org.apache.http.entity.StringEntity;
+import org.apache.http.impl.client.HttpClientBuilder;
+import org.apache.http.util.EntityUtils;
+
+import javax.net.ssl.HttpsURLConnection;
+import javax.net.ssl.SSLContext;
+import javax.net.ssl.TrustManager;
+import javax.net.ssl.X509TrustManager;
+import java.io.*;
+import java.net.URL;
+import java.net.UnknownHostException;
+import java.nio.charset.StandardCharsets;
+import java.security.KeyManagementException;
+import java.security.NoSuchAlgorithmException;
+import java.security.SecureRandom;
+import java.security.cert.CertificateException;
+import java.security.cert.X509Certificate;
+import java.util.Map;
+import java.util.Set;
+
+public class HttpUtils {
+
+	/**
+	 * 发送https请求
+	 *
+	 * @param url           url
+	 * @param requestMethod 请求方式
+	 * @param param         请求参数
+	 * @return 返回值
+	 */
+	public String sendHttpsRequest(String url, String requestMethod, Map<String,Object> param) {
+		StringBuilder result = new StringBuilder();
+		try {
+			SSLContext sc = SSLContext.getInstance("SSL");
+			sc.init(null, new TrustManager[]{
+					new X509TrustManager() {
+						@Override
+						public void checkClientTrusted(X509Certificate[] x509Certificates, String s) throws CertificateException {
+						}
+
+						@Override
+						public void checkServerTrusted(X509Certificate[] x509Certificates, String s) throws CertificateException {
+						}
+
+						@Override
+						public X509Certificate[] getAcceptedIssuers() {
+							return new X509Certificate[0];
+						}
+					}
+			}, new SecureRandom());
+			URL console = new URL(url);
+			HttpsURLConnection conn = (HttpsURLConnection) console.openConnection();
+			// GET/POST
+			conn.setRequestMethod(requestMethod);
+			conn.setRequestProperty("Content-Type", "application/json");
+			conn.setDoOutput(true);
+			conn.setDoInput(true);
+			// 设置证书忽略相关操作
+			conn.setSSLSocketFactory(sc.getSocketFactory());
+			if (null != param) {
+				OutputStream outputStream = conn.getOutputStream();
+				// 注意编码格式
+				outputStream.write(JSON.toJSONString(param).getBytes(StandardCharsets.UTF_8));
+				outputStream.close();
+			}
+
+
+			conn.setHostnameVerifier((s, sslSession) -> true);
+			conn.connect();
+			InputStream is = conn.getInputStream();
+			BufferedReader br = new BufferedReader(new InputStreamReader(is,StandardCharsets.UTF_8));
+			String ret = "";
+			while ((ret = br.readLine()) != null) {
+				if (!ret.trim().isEmpty()) {
+					result.append(ret);
+				}
+			}
+			conn.disconnect();
+			br.close();
+		} catch (NoSuchAlgorithmException | KeyManagementException | IOException e) {
+			e.printStackTrace();
+		}
+        return result.toString();
+	}
+
+	// http协议访问方法
+//	public String sendHttpRequest(String url, String requestMethod, String param) {
+//		StringBuilder result = new StringBuilder();
+//		try {
+//			URL console = new URL(url);
+//			HttpURLConnection conn = (HttpURLConnection) console.openConnection();
+//			// GET/POST
+//			conn.setRequestMethod(requestMethod);
+//			conn.setRequestProperty("Content-Type", "application/json");
+//			conn.setDoOutput(true);
+//			conn.setDoInput(true);
+//			if (null != param) {
+//				OutputStream outputStream = conn.getOutputStream();
+//				// 注意编码格式
+//				outputStream.write(param.getBytes("UTF-8"));
+//				outputStream.close();
+//			}
+//
+//			conn.connect();
+//			InputStream is = conn.getInputStream();
+//			BufferedReader br = new BufferedReader(new InputStreamReader(is));
+//			String ret = "";
+//			while ((ret = br.readLine()) != null) {
+//				if (ret != null && !ret.trim().equals("")) {
+//					result.append(new String(ret.getBytes("utf-8"), "utf-8"));
+//				}
+//			}
+//			conn.disconnect();
+//			br.close();
+//		} catch (IOException ioException) {
+//			ioException.printStackTrace();
+//		}
+//		return result.toString();
+//	}
+
+
+
+	 public static JSONObject httpGet(String url) {
+			JSONObject jsonResult = null;
+			try {
+			HttpClient client = HttpClientBuilder.create().build();//获取DefaultHttpClient请求
+			HttpGet request = new HttpGet(url);
+			HttpResponse response = client.execute(request);
+			if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
+			String strResult = EntityUtils.toString(response.getEntity(),"UTF-8");//此处设定编码格式
+			jsonResult = JSON.parseObject(strResult);
+			} else {
+			LoggerUtils.error(HttpUtils.class,"HttpStatus异常");
+			}
+			} catch (IOException e) {
+			e.printStackTrace();
+			}
+			return jsonResult;
+		}
+
+
+	public static JSONObject httpPost(String url,Map<String, Object>map){
+		return httpPost(url,map,0);
+	}
+	public static JSONObject httpPostBody(String url,Map<String, Object>map){
+		return httpPost(url,map,1);
+	}
+		 /**
+		  *
+		  * @param url 地址
+		  * @param map 参数
+		  * @param type  0 json  1body
+		  * @return
+		  */
+		public static JSONObject httpPost(String url,Map<String, Object>map,Integer type) {
+			HttpClient httpClient = HttpClientBuilder.create().build();
+			HttpPost httpPost = new HttpPost(url);
+			httpPost.setHeader("Accept", "application/json");
+			if (type==0){
+				httpPost.addHeader("Content-type", "application/json");
+				httpPost.setEntity(new StringEntity(JSON.toJSONString(map), StandardCharsets.UTF_8));
+			}else{
+				httpPost.addHeader("Content-type", "application/x-www-form-urlencoded");
+				httpPost.setEntity(new StringEntity(ParamMap(map), StandardCharsets.UTF_8));
+			}
+
+			HttpResponse response = null;
+			try {
+				response = httpClient.execute(httpPost);
+				if (null == response || response.getStatusLine() == null) {
+					throw new Exception("Post Request For Url[{}] is not ok. Response is null");
+				} else if (response.getStatusLine().getStatusCode() != HttpStatus.SC_OK) {
+					throw new Exception("Post Request For Url[{}] is not ok. Response Status Code is {"+response.getStatusLine().getStatusCode()+"}");
+				}
+			} catch (UnknownHostException uhe) {
+				LoggerUtils.error(HttpUtils.class,uhe.getMessage());
+			} catch (Exception e) {
+				e.printStackTrace();
+			}
+			String resultString=null;
+			try {
+                if (response != null) {
+                    resultString = EntityUtils.toString(response.getEntity());
+                }
+            } catch (ParseException | IOException e) {
+				e.printStackTrace();
+			}
+            return JSONObject.parseObject(resultString);
+			}
+
+	private static String ParamMap(Map<String, Object> map) {
+		StringBuilder str =new StringBuilder();
+		Set<String> strings = map.keySet();
+		for (String string : strings) {
+            str.append(string).append("=").append(map.get(string)).append("&");
+        }
+        return str.substring(0, str.length() - 1);
+	}
+
+
+
+}

+ 17 - 0
src/main/java/com/kede/wechat/controller/ConversationContentController.java

@@ -27,5 +27,22 @@ public class ConversationContentController extends BaseController {
     	return conversationContentService.getChatData();
     }
 
+    /**
+     * 获取access_token
+     * @return
+     */
+    @RequestMapping(value = "/getAccessToken",  method = RequestMethod.GET)
+    public String getAccessToken()
+    {
+    	return conversationContentService.getAccessToken();
+    }
+    /**
+     * 获取开启成员列表
+     *
+     */
+    @RequestMapping(value = "/getPermitUserList",  method = RequestMethod.GET)
+    public String getPermitUserList(){
+        return conversationContentService.getPermitUserList();
+    }
 
 }

+ 4 - 0
src/main/java/com/kede/wechat/service/ConversationContentService.java

@@ -4,4 +4,8 @@ import java.util.List;
 
 public interface ConversationContentService {
     List getChatData();
+
+    String getAccessToken();
+
+    String getPermitUserList();
 }

+ 71 - 3
src/main/java/com/kede/wechat/service/impl/ConversationContentServiceImpl.java

@@ -1,19 +1,29 @@
 package com.kede.wechat.service.impl;
 
+import com.kede.common.utils.DateUtils;
+import com.kede.common.utils.HttpUtils;
 import com.kede.common.utils.RSAEncrypt;
 import com.kede.wechat.service.ConversationContentService;
 import com.tencent.wework.Finance;
 import org.json.JSONArray;
 import org.json.JSONObject;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
 import org.springframework.beans.factory.annotation.Value;
+import org.springframework.data.redis.core.RedisTemplate;
 import org.springframework.stereotype.Service;
 
-import java.util.ArrayList;
-import java.util.List;
+import javax.annotation.Resource;
+import java.sql.SQLOutput;
+import java.util.*;
 
 @Service("ConversationContentService")
 public class ConversationContentServiceImpl implements ConversationContentService {
 
+    Logger logger = LoggerFactory.getLogger(ConversationContentServiceImpl.class);
+    @Resource
+    private RedisTemplate redisTemplate;
+
     @Value(value = "${conversationContent.corpid}")
     private String corpid;
     @Value(value = "${conversationContent.secret}")
@@ -64,7 +74,7 @@ public class ConversationContentServiceImpl implements ConversationContentServic
         System.out.println(Finance.Init(sdk, corpid, secret));
         long ret = 0;
         int seq = 0;
-        int limit = 20;
+        int limit = 200;
         long slice = Finance.NewSlice();
         ret = Finance.GetChatData(sdk, seq, limit, null, null, 3, slice);
         if (ret != 0) {
@@ -114,4 +124,62 @@ public class ConversationContentServiceImpl implements ConversationContentServic
         Finance.FreeSlice(slice);
     return list;
     }
+
+    @Override
+    public String getAccessToken() {
+        //获取redis缓存数据
+        String accessToken = null;
+        Map<String,String> accessMap = (Map<String, String>) redisTemplate.opsForValue().get("ACCESS_TOKEN");
+        if (accessMap == null){
+            logger.debug("getAccessToken无缓存从接口获取");
+            Map<String, String> map = getAccessMap();
+            //新增redis缓存数据
+            redisTemplate.opsForValue().set("ACCESS_TOKEN",map);
+            accessToken = map.get("accessToken");
+        }else {
+            logger.debug("getAccessToken有缓存从缓存获取");
+            accessToken = accessMap.get("accessToken");
+            Long expireDate = Long.valueOf(accessMap.get("expireDate"));
+            System.out.println(expireDate);
+            System.out.println(System.currentTimeMillis());
+            if (expireDate < System.currentTimeMillis()){
+                logger.debug("getAccessToken缓存已过期从接口获取");
+                Map<String, String> map = getAccessMap();
+                accessToken = map.get("accessToken");
+                //新增redis缓存数据
+                redisTemplate.opsForValue().set("ACCESS_TOKEN",map);
+            }
+        }
+        return accessToken;
+    }
+
+    @Override
+    public String getPermitUserList() {
+        String url=String.format("https://qyapi.weixin.qq.com/cgi-bin/msgaudit/get_permit_user_list?access_token=%s",getAccessToken());
+        com.alibaba.fastjson.JSONObject result = HttpUtils.httpGet(url);
+
+        if (result.getInteger("errcode")==0){
+            List<String> ids = result.getJSONArray("ids").toJavaList(String.class);
+            ids.stream().forEach(System.out::println);
+        }else {
+            System.out.println(result.getString("errcode"));
+            System.out.println("获取会话内容存档成员列表失败");
+        }
+        return null;
+    }
+
+    private Map<String, String> getAccessMap() {
+        String url=String.format("https://qyapi.weixin.qq.com/cgi-bin/gettoken?corpid=%s&corpsecret=%s",corpid,secret);
+        logger.debug("API获取access_token");
+        Date date = new Date();
+        com.alibaba.fastjson.JSONObject jsonObject = HttpUtils.httpGet(url);
+        String access_token = (String) jsonObject.get("access_token");
+        Integer expires_in = (Integer) jsonObject.get("expires_in");
+        //时间加上过期时间
+        Date expireDate = DateUtils.addMilliseconds(date, expires_in);
+        Map<String,String> map = new HashMap<>();
+        map.put("accessToken",access_token);
+        map.put("expireDate", String.valueOf(expireDate.getTime()));
+        return map;
+    }
 }

+ 5 - 3
src/main/java/com/tencent/wework/Finance.java

@@ -145,9 +145,9 @@ public class Finance {
             System.load(path.concat("C:\\gitProject\\kede-officialWeb-HN\\src\\main\\resources\\lib\\WeWorkFinanceSdk.dll"));
         } else if (osname.contains("Linux")) {
             System.out.println("系统为Linux");
-//            System.load(" /usr/local/tomcat4/webapps/ow-hn-prod/WEB-INF/classes/lib/libWeWorkFinanceSdk_Java.so");
-            System.out.println(System.getProperty("java.library.path"));
-            System.loadLibrary("libWeWorkFinanceSdk_Java.so");
+            System.load("/usr/lib/libWeWorkFinanceSdk_Java.so");
+//            System.out.println(System.getProperty("java.library.path"));
+//            System.loadLibrary("libWeWorkFinanceSdk_Java.so");
         } else {
             System.out.println(String.format("不兼容的系统:{%s}, osname"));
         }
@@ -155,4 +155,6 @@ public class Finance {
 
 
 
+
+
 }