package com.dg.core.util; import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.JSONObject; import com.dg.core.annotation.Authorization; import com.dg.core.db.gen.entity.GuideEvolveEntity; import com.dg.core.db.gen.entity.GuideRepairOrder; import com.dg.core.db.gen.entity.SysUser; import com.dg.core.db.manual.mapper.util.ConstantPropertiesUtil; import lombok.extern.slf4j.Slf4j; import org.apache.commons.lang3.StringUtils; import org.apache.http.HttpEntity; import org.apache.http.HttpResponse; 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.DefaultHttpClient; import org.springframework.data.redis.core.RedisTemplate; import org.springframework.data.redis.core.StringRedisTemplate; import org.springframework.stereotype.Component; import org.springframework.stereotype.Service; import javax.annotation.PostConstruct; import javax.annotation.Resource; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.*; @Slf4j @Component public class WxUtil { private static String ACCESS_TOKEN_URL = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential"; private static String miniprogramState="trial";//trial 为测试版 formal 为正式版 切记发布版本时候改为正式版 @Resource(name = "stringRedisTemplate") private StringRedisTemplate stringRedisTemplate; private static WxUtil wxUtil; @PostConstruct public void init() { wxUtil = this; wxUtil.stringRedisTemplate = this.stringRedisTemplate; } /** * 获取花城token,(ps:0=token获取失败) * * @return */ public String getBatteryCarAccessToken() throws Exception { String accessToken = "0"; // try { // // 此处APP_ID APP_SECRET 在微信小程序后端可见 // // String accessTokenUrl = String.format(TEMP_URL, APP_ID, APP_SECRET); // String accessTokenUrl = ACCESS_TOKEN_URL + "&appid=" + ConstantPropertiesUtil.WX_OPEN_APP_ID // + "&secret=" +ConstantPropertiesUtil.WX_OPEN_APP_SECRET; // String result = httpGet(accessTokenUrl, null, null); // Map resultMap = JSON.parseObject(result, Map.class); // if (resultMap.containsKey("access_token")) { // accessToken = resultMap.get("access_token").toString(); // } // } catch (IOException ioe) { // ioe.printStackTrace(); // } accessToken =wxUtil.stringRedisTemplate.boundValueOps("access_token:access_token:" + ConstantPropertiesUtil.WX_OPEN_APP_ID).get(); return accessToken; } /** * http请求工具类,get请求 * * @param url * @param params * @param resonseCharSet * @return * @throws Exception */ public static String httpGet(String url, Map params, String... resonseCharSet) throws Exception { DefaultHttpClient defaultHttpClient = null; BufferedReader bufferedReader = null; try { defaultHttpClient = new DefaultHttpClient(); if (params != null) { StringBuilder stringBuilder = new StringBuilder(); Iterator iterator = params.keySet().iterator(); String key; while (iterator.hasNext()) { key = iterator.next(); Object val = params.get(key); if (val instanceof List) { List v = (List) val; for (Object o : v) { stringBuilder.append(key).append("=").append(o.toString()).append("&"); } } else { stringBuilder.append(key).append("=").append(val.toString()).append("&"); } } stringBuilder.deleteCharAt(stringBuilder.length() - 1); url = url + "?" + stringBuilder.toString(); } HttpGet httpGet = new HttpGet(url); httpGet.setHeader("Content-Type", "application/json;charset=ut-8"); HttpResponse httpResponse = defaultHttpClient.execute(httpGet); if (httpResponse.getStatusLine().getStatusCode() != 200) { String errorLog = "请求失败,errorCode:" + httpResponse.getStatusLine().getStatusCode(); throw new Exception(url + errorLog); } // 读取返回信息 String charSet = "utf-8"; if (resonseCharSet != null && resonseCharSet.length > 0) charSet = resonseCharSet[0]; String output; bufferedReader = new BufferedReader(new InputStreamReader(httpResponse.getEntity().getContent(), charSet)); StringBuilder dataBuilder = new StringBuilder(); while ((output = bufferedReader.readLine()) != null) { dataBuilder.append(output); } return dataBuilder.toString(); } catch (IOException e) { e.printStackTrace(); throw e; } finally { if (defaultHttpClient != null) defaultHttpClient.getConnectionManager().shutdown(); if (bufferedReader != null) bufferedReader.close(); } } /** * http请求工具类,post请求 * * @param url url * @param param 参数值 仅支持String * @return * @throws Exception */ public static String httpPost(String url, String param) throws Exception { DefaultHttpClient defaultHttpClient = null; BufferedReader bufferedReader = null; try { defaultHttpClient = new DefaultHttpClient(); HttpPost httpPost = new HttpPost(url); httpPost.setHeader("Content-Type", "application/json;charset=ut-8"); if (StringUtils.isNotBlank(param)) { HttpEntity httpEntity = new StringEntity(param, "utf-8"); httpPost.setEntity(httpEntity); } HttpResponse httpResponse = defaultHttpClient.execute(httpPost); if (httpResponse.getStatusLine().getStatusCode() != 200) { String errorLog = "请求失败,errorCode:" + httpResponse.getStatusLine().getStatusCode(); throw new Exception(url + errorLog); } // 读取返回信息 String output; bufferedReader = new BufferedReader(new InputStreamReader(httpResponse.getEntity().getContent(), "utf-8")); StringBuilder stringBuilder = new StringBuilder(); while ((output = bufferedReader.readLine()) != null) { stringBuilder.append(output); } return stringBuilder.toString(); } catch (IOException e) { e.printStackTrace(); throw e; } finally { if (defaultHttpClient != null) defaultHttpClient.getConnectionManager().shutdown(); if (bufferedReader != null) bufferedReader.close(); } } public static String wxMessageModeSendUrl(String token, WxSubscribeDTO subscribeDTO) throws Exception { String tmpurl = "https://api.weixin.qq.com/cgi-bin/message/subscribe/send?access_token=ACCESS_TOKEN"; String url = tmpurl.replace("ACCESS_TOKEN", token); return httpPost(url, subscribeDTO.toJSON()); } /** * 订阅消息推送 * * @param accessToken * 获取会话token * @return 消息推送结果 */ static void sendSubscribe(String accessToken, WxSubscribeDTO subscribeDTO) throws Exception { String resultString = wxMessageModeSendUrl(accessToken, subscribeDTO); JSONObject jsonResult = JSON.parseObject(resultString); if (jsonResult != null) { int errorCode = jsonResult.getIntValue("errcode"); String errorMessage = jsonResult.getString("errmsg"); if (errorCode == 0) { System.out.println("订阅消息推送成功,openId:" + subscribeDTO.getTouser()); } else { System.out.println( "订阅消息发送失败,错误码:" + errorCode + ",错误信息:" + errorMessage + "用户openid:" + subscribeDTO.getTouser()); } } } /** * 工单完成推送 * * @param openId * 用户openid * @param accessToken * token会话标识 */ public void sendGuideRepairOrderComplete(String openId, String accessToken, String templateId, GuideEvolveEntity guideRepairOrder){ WxSubscribeDTO subscribeDTO = new WxSubscribeDTO(); subscribeDTO.setTouser(openId); subscribeDTO.setTemplate_id(templateId); subscribeDTO.setMiniprogram_state(miniprogramState); subscribeDTO.setPage("packageE/pages/myApply/myApply"); List paras=new ArrayList(); Calendar calendar = Calendar.getInstance(); paras.add(new TemplateParam("thing1","导办申请"));//业务办理类型 paras.add(new TemplateParam("thing3",guideRepairOrder.getRemark())); paras.add(new TemplateParam("phrase8","已完成")); calendar.setTime(new Date()); paras.add(new TemplateParam("time4",calendar.get(Calendar.YEAR)+"年"+(calendar.get(Calendar.MONTH)+1)+"月"+calendar.get(Calendar.DATE)+"日"));//结束日期 subscribeDTO.setTemplateParamList(paras); try { sendSubscribe(accessToken,subscribeDTO); }catch (Exception e){ System.out.println(e.getMessage()); } } /** * 工单提交推送 * * @param openId * 用户openid * @param accessToken * token会话标识 */ public void sendGuideRepairOrderSubmit(String openId, String accessToken, String templateId, GuideRepairOrder guideRepairOrder){ WxSubscribeDTO subscribeDTO = new WxSubscribeDTO(); subscribeDTO.setTouser(openId); subscribeDTO.setTemplate_id(templateId); subscribeDTO.setMiniprogram_state(miniprogramState); subscribeDTO.setPage("packageE/pages/applyHandle/index/index"); List paras=new ArrayList(); paras.add(new TemplateParam("thing4","您有一个新的导办工单需要处理"));//工单新增提示内容 paras.add(new TemplateParam("thing2",guideRepairOrder.getConsultUserName()));//咨询人 paras.add(new TemplateParam("thing3",guideRepairOrder.getConsultContent()));//咨询内容 subscribeDTO.setTemplateParamList(paras); try { sendSubscribe(accessToken,subscribeDTO); }catch (Exception e){ System.out.println(e.getMessage()); } } /** * 工单超时推送 * * @param openId * 用户openid * @param accessToken * token会话标识 */ public void sendGuideRepairOrderOvertime(String openId, String accessToken, String templateId, SysUser sysUser){ WxSubscribeDTO subscribeDTO = new WxSubscribeDTO(); subscribeDTO.setTouser(openId); subscribeDTO.setTemplate_id(templateId); subscribeDTO.setMiniprogram_state(miniprogramState); subscribeDTO.setPage("packageE/pages/applyHandle/index/index"); List paras=new ArrayList(); Calendar calendar = Calendar.getInstance(); calendar.setTime(new Date()); paras.add(new TemplateParam("time1",calendar.get(Calendar.YEAR)+"年"+(calendar.get(Calendar.MONTH)+1)+"月"+calendar.get(Calendar.DATE)+"日"));//超时时间 paras.add(new TemplateParam("thing2",sysUser.getUserName()+"导办人员有个工单已超时"));//咨询人 subscribeDTO.setTemplateParamList(paras); try { sendSubscribe(accessToken,subscribeDTO); }catch (Exception e){ System.out.println(e.getMessage()); } } }