微信小程式訊息推送伺服器接入
阿新 • • 發佈:2019-01-11
1、訊息轉發地址填寫,需要注意的是token和encodingaeskey要和專案中配置一致
2、URL要實現兩個路由相同的方法但是一個需要時GET另一個是POST,如下,其中TOKEN引數需要與微信後臺配置一致;
@ResponseBody @RequestMapping(method=RequestMethod.GET,produces= "text/plain;charset=utf-8") public void 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,HttpServletResponse response) throws Exception { this.logger.info("\n接收到來自微信伺服器的認證訊息:[{}, {}, {}, {}]", signature, timestamp, nonce, echostr); if (StringUtils.isAnyBlank(signature, timestamp, nonce, echostr)) { throw new IllegalArgumentException("請求引數非法,請核實!"); } String[] str = { TOKEN, timestamp, nonce }; Arrays.sort(str); // 字典序排序 String bigStr = str[0] + str[1] + str[2]; // SHA1加密 SHA1 sha1= new SHA1(); String digest =sha1.gen(str); // 確認請求來至微信 if (digest.equals(signature)) { response.getWriter().print(echostr); } }
第一個方法用於驗證,第二個方法用於接收訊息轉發和其他業務邏輯實現,方法二中也實現了接收到的客服訊息轉發給客服,關鍵點在於/** * POST請求: * 接收客服訊息; * 此處的value值也就是往微信公眾平臺要配置的請求的地址 */ @ResponseBody @RequestMapping(method=RequestMethod.POST) public JSONObject doMessagePost(HttpServletRequest request,HttpServletResponse response) { try { ServletInputStream stream = request.getInputStream(); BufferedReader reader = new BufferedReader(new InputStreamReader(stream)); StringBuffer buffer = new StringBuffer(); String line = new String(""); while((line = reader.readLine()) != null){ buffer.append(line); } JSONObject jsonObject = JSONObject.fromObject(buffer.toString()); String to=jsonObject.getString("ToUserName"); String from=jsonObject.getString("FromUserName"); String time=jsonObject.getString("CreateTime"); String sessionFrom=jsonObject.getString("SessionFrom"); String msgType=jsonObject.getString("MsgType"); PrintWriter out=response.getWriter(); String msg="<xml>\r\n" + " <ToUserName><![CDATA["+to+"]]></ToUserName>\r\n" + " <FromUserName><![CDATA["+from+"]]></FromUserName>\r\n" + " <CreateTime>"+time+"</CreateTime>\r\n" + " <MsgType><![CDATA[transfer_customer_service]]></MsgType>\r\n" + " </xml>"; out.print(msg); if("event".equals(msgType)&&"follow".equals(sessionFrom)) { pushService.setSendCustomerMsgLink(from); } } catch (Exception e) { e.printStackTrace(); } return null; }
<MsgType><![CDATA[transfer_customer_service]]></MsgType>
至此也就全部完成了。