From 0cc92878478156b397facbd549fbda51a13bf8bf Mon Sep 17 00:00:00 2001 From: huanghongfa <huanghongfa123456> Date: 星期日, 25 四月 2021 13:57:39 +0800 Subject: [PATCH] 客服推送消息发送图文模式 --- springcloud_k8s_panzhihuazhihuishequ/common/src/main/java/com/panzhihua/common/constants/SecurityConstants.java | 3 springcloud_k8s_panzhihuazhihuishequ/common/src/main/java/com/panzhihua/common/utlis/WxUtil.java | 22 ++++ springcloud_k8s_panzhihuazhihuishequ/common/src/main/java/com/panzhihua/common/listen/ComMngPopulationServeExcelListen.java | 6 + springcloud_k8s_panzhihuazhihuishequ/common/src/main/java/com/panzhihua/common/utlis/HttpClientUtil.java | 1 springcloud_k8s_panzhihuazhihuishequ/common/src/main/java/com/panzhihua/common/utlis/WxXCXTempSend.java | 215 ++++++++++++++++++++++++++++++++++++------ springcloud_k8s_panzhihuazhihuishequ/applets/src/main/java/com/panzhihua/applets/api/WxMessagePushApi.java | 18 +-- 6 files changed, 221 insertions(+), 44 deletions(-) diff --git a/springcloud_k8s_panzhihuazhihuishequ/applets/src/main/java/com/panzhihua/applets/api/WxMessagePushApi.java b/springcloud_k8s_panzhihuazhihuishequ/applets/src/main/java/com/panzhihua/applets/api/WxMessagePushApi.java index a15bf97..94bedab 100644 --- a/springcloud_k8s_panzhihuazhihuishequ/applets/src/main/java/com/panzhihua/applets/api/WxMessagePushApi.java +++ b/springcloud_k8s_panzhihuazhihuishequ/applets/src/main/java/com/panzhihua/applets/api/WxMessagePushApi.java @@ -104,8 +104,6 @@ * @return */ private String acceptMessage(HttpServletRequest request, HttpServletResponse response) { -// {CreateTime=1548042266, Event=user_enter_tempsession, ToUserName=gh_e6198220cbff, -// FromUserName=oZvme4q2Oi7Dz3FChXc43kqw28, MsgType=event, SessionFrom=wxapp} String respMessage = ""; String inputLine = ""; String notityXml = ""; @@ -132,19 +130,19 @@ //公众号关注事件消息 if(msgType.equals("event")){ // log.info("公众号被关注事件.........."); -// if(StringUtils.isNotEmpty(access_token)){ -// WxUtil.sendKfLinkMessage(fromUserName,url,thumbUrl,access_token); //把封装好的信息推送给用户 -// } }else if(msgType.equals("text")){ + if(StringUtils.isNotEmpty(access_token)){ + String mediaId = wxXCXTempSend.getMediaId(access_token);//获取mediaId + WxUtil.sendKfImagesMessage(fromUserName,access_token,mediaId); + } // log.info("公众号接受文字.........."); -// if(StringUtils.isNotEmpty(access_token)){ -// WxUtil.sendKfLinkMessage(fromUserName,url,thumbUrl,access_token); -// } }else if(msgType.equals("image")){ // log.info("公众号接受图片.........."); -// WxUtil.sendKfLinkMessage(fromUserName,url,thumbUrl,access_token); }else if(msgType.equals("miniprogrampage")){ - WxUtil.sendKfLinkMessage(fromUserName,url,thumbUrl,access_token); + if(StringUtils.isNotEmpty(access_token)){ + String mediaId = wxXCXTempSend.getMediaId(access_token);//获取mediaId + WxUtil.sendKfImagesMessage(fromUserName,access_token,mediaId); + } } } catch (Exception e) { e.printStackTrace(); diff --git a/springcloud_k8s_panzhihuazhihuishequ/common/src/main/java/com/panzhihua/common/constants/SecurityConstants.java b/springcloud_k8s_panzhihuazhihuishequ/common/src/main/java/com/panzhihua/common/constants/SecurityConstants.java index 4838164..f4b32db 100644 --- a/springcloud_k8s_panzhihuazhihuishequ/common/src/main/java/com/panzhihua/common/constants/SecurityConstants.java +++ b/springcloud_k8s_panzhihuazhihuishequ/common/src/main/java/com/panzhihua/common/constants/SecurityConstants.java @@ -12,6 +12,9 @@ public static final String ROLE_USER="springsecurity:role:";//某个用户的具体权限 public static final String ROLE_APPLETS="applets";//小程序用户通用角色 public static final String APPLETS_ACCESS_TOKEN ="APPLETS_ACCESS_TOKEN";//小程序获取的access_token + public static final String APPLETS_ACCESS_TOKEN_TIME ="APPLETS_ACCESS_TOKEN_TIME";//小程序获取的access_token + public static final String APPLETS_ACCESS_MEDIA_ID ="APPLETS_ACCESS_MEDIA_ID";//小程序获取的access_token + public static final String APPLETS_ACCESS_MEDIA_ID_TIME ="APPLETS_ACCESS_MEDIA_ID_TIME";//小程序获取的access_token } diff --git a/springcloud_k8s_panzhihuazhihuishequ/common/src/main/java/com/panzhihua/common/listen/ComMngPopulationServeExcelListen.java b/springcloud_k8s_panzhihuazhihuishequ/common/src/main/java/com/panzhihua/common/listen/ComMngPopulationServeExcelListen.java index 6dde499..36fd6b8 100644 --- a/springcloud_k8s_panzhihuazhihuishequ/common/src/main/java/com/panzhihua/common/listen/ComMngPopulationServeExcelListen.java +++ b/springcloud_k8s_panzhihuazhihuishequ/common/src/main/java/com/panzhihua/common/listen/ComMngPopulationServeExcelListen.java @@ -45,7 +45,7 @@ /** * 每隔5条存储数据库,实际使用中可以3000条,然后清理list ,方便内存回收 */ - private static final int BATCH_COUNT = 100; + private static final int BATCH_COUNT = 5000; List<Map<Integer, String>> list = new ArrayList<Map<Integer, String>>(); @Override @@ -91,6 +91,10 @@ if(oneData.get(1) == null){ throw new ServiceException("500", "身份证号不可为空:第" + index + "行,第2列"); } + //判断身份证号码位数 + if(oneData.get(1).length() != 18){ + throw new ServiceException("500", "身份证号位数不正确:第" + index + "行,第2列"); + } vo.setCardNo(oneData.get(1)); //根据身份证号码解析年龄以及性别 //获取用户生日 diff --git a/springcloud_k8s_panzhihuazhihuishequ/common/src/main/java/com/panzhihua/common/utlis/HttpClientUtil.java b/springcloud_k8s_panzhihuazhihuishequ/common/src/main/java/com/panzhihua/common/utlis/HttpClientUtil.java index 5bf6c6f..6159238 100644 --- a/springcloud_k8s_panzhihuazhihuishequ/common/src/main/java/com/panzhihua/common/utlis/HttpClientUtil.java +++ b/springcloud_k8s_panzhihuazhihuishequ/common/src/main/java/com/panzhihua/common/utlis/HttpClientUtil.java @@ -234,6 +234,7 @@ while ((output = bufferedReader.readLine()) != null) { stringBuilder.append(output); } + log.info("调用微信接口返回的参数:" + stringBuilder.toString()); return stringBuilder.toString(); } catch (IOException e) { e.printStackTrace(); diff --git a/springcloud_k8s_panzhihuazhihuishequ/common/src/main/java/com/panzhihua/common/utlis/WxUtil.java b/springcloud_k8s_panzhihuazhihuishequ/common/src/main/java/com/panzhihua/common/utlis/WxUtil.java index c44a45b..320cb9b 100644 --- a/springcloud_k8s_panzhihuazhihuishequ/common/src/main/java/com/panzhihua/common/utlis/WxUtil.java +++ b/springcloud_k8s_panzhihuazhihuishequ/common/src/main/java/com/panzhihua/common/utlis/WxUtil.java @@ -1,7 +1,17 @@ package com.panzhihua.common.utlis; import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.JSONObject; +import org.apache.commons.fileupload.FileItem; +import org.apache.commons.fileupload.FileItemFactory; +import org.apache.commons.fileupload.disk.DiskFileItemFactory; +import org.apache.http.entity.ContentType; +import org.springframework.web.multipart.MultipartFile; +import org.springframework.web.multipart.commons.CommonsMultipartFile; +import java.io.*; +import java.net.HttpURLConnection; +import java.net.URL; import java.util.HashMap; import java.util.Map; @@ -34,4 +44,16 @@ String content = JSON.toJSONString(map); return HttpClientUtil.httpPost(kf_url+"?access_token="+access_token,content); } + + public static String sendKfImagesMessage(String openid,String access_token,String mediaId)throws Exception{ + Map<String,Object> map_content = new HashMap<>(); + map_content.put("media_id",mediaId); + Map<String,Object> map = new HashMap<>(); + map.put("touser",openid); + map.put("msgtype","image"); + map.put("image",map_content); + String content = JSON.toJSONString(map); + return HttpClientUtil.httpPost(kf_url+"?access_token="+access_token,content); + } + } diff --git a/springcloud_k8s_panzhihuazhihuishequ/common/src/main/java/com/panzhihua/common/utlis/WxXCXTempSend.java b/springcloud_k8s_panzhihuazhihuishequ/common/src/main/java/com/panzhihua/common/utlis/WxXCXTempSend.java index e1c81f8..85cac1b 100644 --- a/springcloud_k8s_panzhihuazhihuishequ/common/src/main/java/com/panzhihua/common/utlis/WxXCXTempSend.java +++ b/springcloud_k8s_panzhihuazhihuishequ/common/src/main/java/com/panzhihua/common/utlis/WxXCXTempSend.java @@ -1,14 +1,23 @@ package com.panzhihua.common.utlis; import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.JSONObject; import com.panzhihua.common.constants.SecurityConstants; import lombok.extern.slf4j.Slf4j; +import org.apache.commons.fileupload.FileItem; +import org.apache.commons.fileupload.FileItemFactory; +import org.apache.commons.fileupload.disk.DiskFileItemFactory; +import org.apache.http.entity.ContentType; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.redis.core.StringRedisTemplate; import org.springframework.data.redis.core.ValueOperations; import org.springframework.stereotype.Component; +import org.springframework.web.multipart.MultipartFile; +import org.springframework.web.multipart.commons.CommonsMultipartFile; -import java.io.IOException; +import java.io.*; +import java.net.HttpURLConnection; +import java.net.URL; import java.util.Map; import java.util.concurrent.TimeUnit; @@ -17,6 +26,8 @@ public class WxXCXTempSend { private static String ACCESS_TOKEN_URL = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential"; + private static String APP_IMAGE_URL = "https://www.psciio.com//idcard/8fa82cfba258498eab2fa818220fb592.jpg"; + private static String APP_IMAGE_NAME = "5.jpg"; public static final String APP_ID = "wx0cef797390444b75"; private static final String APP_SECRET = "c7ea9aaa7e391a487e8a5b9ba61045d1"; @@ -30,23 +41,26 @@ * @return */ public String getAccessToken() throws Exception { - String accessToken = ""; - Boolean aBoolean = redisTemplate.hasKey(SecurityConstants.APPLETS_ACCESS_TOKEN); - ValueOperations<String, String> valueOperations = redisTemplate.opsForValue(); - if(aBoolean){ - Long expire = redisTemplate.boundHashOps(SecurityConstants.APPLETS_ACCESS_TOKEN).getExpire(); - if(expire <= 0){ - redisTemplate.delete(SecurityConstants.APPLETS_ACCESS_TOKEN);//如果过期则删除 - accessToken = getAppAccessToken(); - valueOperations.set(SecurityConstants.APPLETS_ACCESS_TOKEN, accessToken,110, TimeUnit.MINUTES); - }else{ - accessToken = valueOperations.get(SecurityConstants.APPLETS_ACCESS_TOKEN); - } - }else{ - accessToken = getAppAccessToken(); - valueOperations.set(SecurityConstants.APPLETS_ACCESS_TOKEN, accessToken,110, TimeUnit.MINUTES); - } - return accessToken; +// String accessToken = ; +// Boolean aBoolean = redisTemplate.hasKey(SecurityConstants.APPLETS_ACCESS_TOKEN); +// ValueOperations<String, String> valueOperations = redisTemplate.opsForValue(); +// if(aBoolean){ +// Long expireTime = Long.parseLong(valueOperations.get(SecurityConstants.APPLETS_ACCESS_TOKEN_TIME)); +// if(expireTime <= System.currentTimeMillis()){ +// redisTemplate.delete(SecurityConstants.APPLETS_ACCESS_TOKEN);//如果过期则删除 +// redisTemplate.delete(SecurityConstants.APPLETS_ACCESS_TOKEN_TIME);//如果过期则删除 +// +// valueOperations.set(SecurityConstants.APPLETS_ACCESS_TOKEN, accessToken); +// valueOperations.set(SecurityConstants.APPLETS_ACCESS_TOKEN_TIME, System.currentTimeMillis() + 1100000 + ""); +// }else{ +// accessToken = valueOperations.get(SecurityConstants.APPLETS_ACCESS_TOKEN); +// } +// }else{ +// accessToken = getAppAccessToken(); +// valueOperations.set(SecurityConstants.APPLETS_ACCESS_TOKEN, accessToken); +// valueOperations.set(SecurityConstants.APPLETS_ACCESS_TOKEN_TIME, System.currentTimeMillis() + 1100000 + ""); +// } + return getAppAccessToken(); } private String getAppAccessToken() throws Exception{ @@ -67,23 +81,158 @@ return accessToken; } - public static void main(String[] args) throws Exception { -// String accessToken = "0"; -// try { -// //此处APP_ID APP_SECRET 在微信小程序后端可见 -// String accessTokenUrl = String.format(TEMP_URL, APP_ID, APP_SECRET); -// String result = HttpClientUtil.httpGet(accessTokenUrl, null, null); -// Map<String, Object> resultMap = JSON.parseObject(result, Map.class); -// if(resultMap.containsKey("access_token")) { -// accessToken = resultMap.get("access_token").toString(); -// } -// } catch (IOException ioe) { -// log.error("小程序http请求异常"); -// ioe.printStackTrace(); -// } -// System.out.println(accessToken); + public String getMediaId(String accessToken){ + String mediaId = ""; + Boolean aBoolean = redisTemplate.hasKey(SecurityConstants.APPLETS_ACCESS_MEDIA_ID); + ValueOperations<String, String> valueOperations = redisTemplate.opsForValue(); + if(aBoolean){ + Long expireTime = Long.parseLong(valueOperations.get(SecurityConstants.APPLETS_ACCESS_MEDIA_ID_TIME)); + if(expireTime <= System.currentTimeMillis()){ + redisTemplate.delete(SecurityConstants.APPLETS_ACCESS_MEDIA_ID);//如果过期则删除 + redisTemplate.delete(SecurityConstants.APPLETS_ACCESS_MEDIA_ID_TIME);//如果过期则删除 + mediaId = getAppMediaId(accessToken); + valueOperations.set(SecurityConstants.APPLETS_ACCESS_MEDIA_ID, mediaId); + valueOperations.set(SecurityConstants.APPLETS_ACCESS_MEDIA_ID_TIME, System.currentTimeMillis() + 259000000 + ""); + }else{ + mediaId = valueOperations.get(SecurityConstants.APPLETS_ACCESS_MEDIA_ID); + } + }else{ + mediaId = getAppMediaId(accessToken); + valueOperations.set(SecurityConstants.APPLETS_ACCESS_MEDIA_ID, mediaId); + valueOperations.set(SecurityConstants.APPLETS_ACCESS_MEDIA_ID_TIME, System.currentTimeMillis() + 259000000 + ""); + } + return mediaId; } + private String getAppMediaId(String accessToken){ + String appMediaId = ""; + try { + MultipartFile file = createFileItem(APP_IMAGE_URL,APP_IMAGE_NAME); + appMediaId = uploadFile(file,accessToken); + }catch (Exception e){ + log.error("上传临时图片素材失败,错误原因:" + e.getMessage()); + } + return appMediaId; + } + /** + * url转变为 MultipartFile对象 + * @param url + * @param fileName + * @return + * @throws Exception + */ + private static MultipartFile createFileItem(String url, String fileName) throws Exception{ + FileItem item = null; + try { + HttpURLConnection conn = (HttpURLConnection) new URL(url).openConnection(); + conn.setReadTimeout(30000); + conn.setConnectTimeout(30000); + //设置应用程序要从网络连接读取数据 + conn.setDoInput(true); + conn.setRequestMethod("GET"); + if (conn.getResponseCode() == HttpURLConnection.HTTP_OK) { + InputStream is = conn.getInputStream(); + + FileItemFactory factory = new DiskFileItemFactory(16, null); + String textFieldName = "uploadfile"; + item = factory.createItem(textFieldName, ContentType.APPLICATION_OCTET_STREAM.toString(), false, fileName); + OutputStream os = item.getOutputStream(); + + int bytesRead = 0; + byte[] buffer = new byte[8192]; + while ((bytesRead = is.read(buffer, 0, 8192)) != -1) { + os.write(buffer, 0, bytesRead); + } + os.close(); + is.close(); + } + } catch (IOException e) { + throw new RuntimeException("文件下载失败", e); + } + + return new CommonsMultipartFile(item); + } + + /** + * 微信小程序临时素材上传 + * + * @param file + * @return + * @author yixiu + * @throws Exception + */ + public String uploadFile(MultipartFile file,String access_token) throws Exception { + String url = "https://api.weixin.qq.com/cgi-bin/media/upload?access_token=" + access_token + "&type=image"; + String result = null; + String fileName = file.getOriginalFilename(); + URL urlObj = new URL(url); + HttpURLConnection con = (HttpURLConnection) urlObj.openConnection(); + con.setRequestMethod("POST"); + con.setDoInput(true); + con.setDoOutput(true); + con.setUseCaches(false); + // 设置请求头信息 + con.setRequestProperty("Connection", "Keep-Alive"); + con.setRequestProperty("Charset", "UTF-8"); + // 设置边界 + String BOUNDARY = "----------" + System.currentTimeMillis(); + con.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + BOUNDARY); + // 请求正文信息 + // 第一部分: + StringBuilder sb = new StringBuilder(); + sb.append("--"); // 必须多两道线 + sb.append(BOUNDARY); + sb.append("\r\n"); + sb.append("Content-Disposition: form-data;name=\"media\";filename=\"" + fileName + "\"\r\n"); + sb.append("Content-Type:application/octet-stream\r\n\r\n"); + byte[] head = sb.toString().getBytes("utf-8"); + // 获得输出流 + OutputStream out = new DataOutputStream(con.getOutputStream()); + // 输出表头 + out.write(head); + // 文件正文部分 + // 把文件已流文件的方式 推入到url中 + DataInputStream in = new DataInputStream(file.getInputStream()); + int bytes = 0; + byte[] bufferOut = new byte[1024]; + while ((bytes = in.read(bufferOut)) != -1) { + out.write(bufferOut, 0, bytes); + } + in.close(); + // 结尾部分 + byte[] foot = ("\r\n--" + BOUNDARY + "--\r\n").getBytes("utf-8");// 定义最后数据分隔线 + out.write(foot); + out.flush(); + out.close(); + StringBuffer buffer = new StringBuffer(); + BufferedReader reader = null; + try { + // 定义BufferedReader输入流来读取URL的响应 + reader = new BufferedReader(new InputStreamReader(con.getInputStream())); + String line = null; + while ((line = reader.readLine()) != null) { + buffer.append(line); + } + if (result == null) { + result = buffer.toString(); + } + } catch (IOException e) { + System.out.println("发送POST请求出现异常! {}"); + e.printStackTrace(); + throw new IOException("数据读取异常"); + } finally { + if (reader != null) { + reader.close(); + } + } + // 获取到返回HTTP结果 + Map<String, Object> map = JSONObject.parseObject(result, Map.class); + if (map.containsKey("media_id")) { + return map.get("media_id").toString(); + } + System.out.println("小程序上传临时素材出错,返回信息为: " + result); + return null; + } } -- Gitblit v1.7.1