import com.thoughtworks.xstream.XStream; import net.sf.json.JSONObject; 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.CloseableHttpClient; import org.apache.http.impl.client.DefaultHttpClient; import org.apache.http.impl.client.HttpClients; import org.apache.http.util.EntityUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; import javax.servlet.ServletInputStream; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; import java.text.ParseException; import java.util.Calendar; import java.util.Date; import java.util.HashMap; import java.util.Map; /** * 接收微信推送的工具類 */ @Component public class WeixinUtil { @Autowired WeixinConfig weixinConfig; public static boolean hasWxError(JSONObject jsonObject) { System.out.println("hasWxError()"); return jsonObject.get("errcode") != null; } public static boolean hasWxIntError(JSONObject jsonObject) { System.out.println("hasWxIntError()"); return NumberUtil.isNotEmpty((Number) jsonObject.get("errcode"))&&!((Integer)jsonObject.get("errcode")).equals(0); } /** * 微信驗證第三方服務器 及推送消息 * @param request * @param response */ public void wxapicheck(HttpServletRequest request, HttpServletResponse response) { System.out.println("進入wxapicheck"); boolean isGet = request.getMethod().toLowerCase().equals("get"); if (isGet) { System.out.println("enter get"); access(request, response); } else { // 進入POST聊天處理 System.out.println("enter post"); try { // 接收消息並返回消息 acceptMessage(request, response); } catch (IOException e) { e.printStackTrace(); } } } /** * 驗證URL真實性 * */ public String access(HttpServletRequest request, HttpServletResponse response) { // 驗證URL真實性 System.out.println("進入驗證access"); String signature = request.getParameter("signature");// 微信加密簽名 String timestamp = request.getParameter("timestamp");// 時間戳 String nonce = request.getParameter("nonce");// 隨機數 String echostr = request.getParameter("echostr");// 隨機字符串 System.out.println(signature); System.out.println(timestamp); System.out.println(nonce); System.out.println(echostr); Map<String, Object> map = new HashMap<String, Object>(); map.put("token", "52eybzmgglpbiasownoffwfchmrcm5jt"); map.put("timestamp", timestamp); map.put("nonce", nonce); String sign= WeixinSign.sign(map); if(!sign.equals(signature)){ try { response.getWriter().write(echostr); System.out.println("成功返回 echostr:" + echostr); return echostr; } catch (IOException e) { e.printStackTrace(); } } System.out.println("失敗 認證"); return null; } public InputMessage acceptMessage(HttpServletRequest request, HttpServletResponse response) throws IOException { // 處理接收消息 ServletInputStream in = request.getInputStream(); // 將POST流轉換爲XStream對象 XStream xs = SerializeXmlUtil.createXstream(); xs.processAnnotations(InputMessage.class); xs.processAnnotations(OutputMessage.class); // 將指定節點下的xml節點數據映射爲對象 xs.alias("xml", InputMessage.class); // 將流轉換爲字符串 StringBuilder xmlMsg = new StringBuilder(); byte[] b = new byte[4096]; for (int n; (n = in.read(b)) != -1;) { xmlMsg.append(new String(b, 0, n, "UTF-8")); } // 將xml內容轉換爲InputMessage對象 System.out.println("獲取的流"+xmlMsg.toString()); // InputMessage inputMsg = (InputMessage) XmlUtils.parseToObject(xmlMsg.toString(), InputMessage.class); // InputMessageNew inputMsgn = (InputMessageNew) XmlUtils.parseToObject(xmlMsg.toString(),InputMessageNew.class); InputMessage inputMsg =(InputMessage)xs.fromXML(xmlMsg.toString()); String servername = inputMsg.getToUserName();// 服務端 String custermname = inputMsg.getFromUserName();// 客戶端 long createTime = inputMsg.getCreateTime();// 接收時間 Long returnTime = Calendar.getInstance().getTimeInMillis() / 1000;// 返回時間 // 取得消息類型 String msgType = inputMsg.getMsgType(); try { // String retrunMsg= WeiXinMsgTypeOperator.getService(msgType).getMsgTypeReturn(inputMsg); // if(StringUtils.isNotEmpty(retrunMsg)){ // System.out.println("operator:" + retrunMsg); // } }catch (Exception e) { e.printStackTrace(); } // 根據消息類型獲取對應的消息內容 if (msgType.equals(WXEnum.MsgType.text.toString().toLowerCase())) { // 文本消息 System.out.println("開發者微信號:" + inputMsg.getToUserName()); System.out.println("發送方帳號:" + inputMsg.getFromUserName()); System.out.println("消息創建時間:" + inputMsg.getCreateTime() + new Date(createTime * 1000l)); System.out.println("消息內容:" + inputMsg.getContent()); System.out.println("消息Id:" + inputMsg.getMsgId()); StringBuffer str = new StringBuffer(); str.append("<xml>"); str.append("<ToUserName><![CDATA[" + custermname + "]]></ToUserName>"); str.append("<FromUserName><![CDATA[" + servername + "]]></FromUserName>"); str.append("<CreateTime>" + returnTime + "</CreateTime>"); str.append("<MsgType><![CDATA[" + msgType + "]]></MsgType>"); str.append("<Content><![CDATA[你說的是:" + inputMsg.getContent() + ",嗎?]]></Content>"); str.append("</xml>"); System.out.println(str.toString()); response.getWriter().write(str.toString()); } // 獲取並返回多圖片消息 if (msgType.equals(WXEnum.MsgType.image.toString().toLowerCase())) { System.out.println("獲取多媒體信息"); System.out.println("多媒體文件id:" + inputMsg.getMediaId()); System.out.println("圖片鏈接:" + inputMsg.getPicUrl()); System.out.println("消息id,64位整型:" + inputMsg.getMsgId()); OutputMessage outputMsg = new OutputMessage(); outputMsg.setFromUserName(servername); outputMsg.setToUserName(custermname); outputMsg.setCreateTime(returnTime); outputMsg.setMsgType(msgType); ImageMessage images = new ImageMessage(); images.setMediaId(inputMsg.getMediaId()); // outputMsg.setImage(images); System.out.println("xml轉換:/n" + xs.toXML(outputMsg)); response.getWriter().write(xs.toXML(outputMsg)); } return inputMsg; } public static JSONObject doGetStr(String url) throws ParseException, IOException{ CloseableHttpClient httpClient = HttpClients.createDefault(); HttpGet httpGet = new HttpGet(url); JSONObject jsonObject = null; try { HttpResponse httpResponse = httpClient.execute(httpGet); HttpEntity entity = httpResponse.getEntity(); if (entity != null) { String result = EntityUtils.toString(entity, "UTF-8"); jsonObject = JSONObject.fromObject(result); } }catch (Exception e){ e.printStackTrace(); }finally { httpGet.abort(); httpClient.close(); } return jsonObject; } public static String doPostStr(String outStr,String url) throws Exception { CloseableHttpClient httpClient = HttpClients.createDefault(); HttpPost httpPost = new HttpPost(url); httpPost.setEntity(new StringEntity(outStr,"UTF-8")); String result = null; try { HttpResponse response = httpClient.execute(httpPost); result = EntityUtils.toString(response.getEntity(), "UTF-8"); } catch (Exception e) { e.printStackTrace(); } finally { httpPost.abort(); httpClient.close(); } return result; } }
微信自定義菜單的應用:
@Component public class PublicMenuAPI { @Autowired PublicMenuURL publicMenuURL; @Autowired PublicAPI publicAPI; @Autowired WeixinUtil weixinUtil; public JSONObject add_menu(String menu) throws Exception{ String result = null; result = weixinUtil.doPostStr(menu,publicMenuURL.add_memu_url(publicAPI.getAccess_token())); JSONObject jsonObject = null; jsonObject = jsonObject.fromObject(result); if (WeixinUtil.hasWxIntError(jsonObject)) throw new Exception("Add menu Error!"); return jsonObject; } public JSONObject get_menu() throws Exception { return weixinUtil.doGetStr(publicMenuURL.getMenuUrl(publicAPI.getAccess_token())); } public JSONObject delete_menu() throws Exception { return weixinUtil.doGetStr(publicMenuURL.getMenuDeleteUrl(publicAPI.getAccess_token())); } }