接收消息text–微信企业号开发

前言:

接收消息是有移动端在企业号中发送消息,微信服务器收到信息加密后,发送到指定的服务中(例如:企业服务器的服务地址中,也可以是自己写web工程服务中),然后在自己的服务中解密,获取其中信息,然后处理,按照返回格式拼接字符,之后加密发送给微信服务器,微信服务器处理信息,展示到企业号中;
接收消息难度在于加密与解密,获取解密个个字段信息,且按照格式发送各种信息;附上整个项目war包,修改部分参数变量,直接可以用

注意点:

1 获取url请求字段时用:request.getParameter(“xxxx”),不要使用接收请求参数整体request.getQueryString()之后自己做处理;
2 在建立web工程时,引入jar时,需要将jar放到WEB-INF中的lib文件夹中,因为有时候启动tomcat时,也需要用到jar,如果不发到lib中可能出错(无法找到相应的类);
3 在其中用到微信提供的工具类时,会用到codec的jar(import org.apache.commons.codec.binary.Base64;),有可能出错,所以我用的是:import org.apache.tomcat.util.codec.binary.Base64;

建立web工程

使用java建立本地web工程,编写处理请求的服务,使用httpservlet类,写一个简单servlet,可以处理请求和发送请求,GET和POST请求;
我以前练习写的servlet:

内网穿刺,网络访问本地

使用ngrok软件,简单易用,用于测试;因为需要将本地的web工程通过网络可以访问,所以需要将本地映射到一个网址上,参考本连接的3中方式,选ngrok:免费

加入工具类

在企业微信api文档中下载加密解密工具类;java的url验证,加密,解密连接

同时其中需要注意的问题和操作也要多加注意:

工具类中有例子:Sample ,可根据这个类,做修改;
能抄就抄吧

url校验

写好servlet处理类后,第一步,需要校验能处理url的验证;必须在1s内解密且明文回复,如何处理参考Sample ,校验是用到是get请求;
需要配置在企业号后台,一下是我配置好后的:

完成url校验后,使用发送text信息,这个使用的post请求;

发送文本信息

发送文本信息,处理text和image之外的返回相同信息;

这个serlvet代码如下:

package servlet;import java.io.BufferedReader;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.StringReader;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Random;import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;import net.sf.json.JSONObject;
import util.AesException;
import util.MediaUploadUtil;
import util.WXBizMsgCrypt;
import util.WxworkUtil;public class ResponseNews extends HttpServlet {// 设置企业号后台参数static String sToken = "QDG6eK";static String sEncodingAESKey = "jWmYm7qr5nMoAUwZRjGtBxmz3KA1tkAj3ykkR6q2B2C";static String sCorpID = "ww248ac59c619621da";static String sAgentId = "1000002";static String corpsecret = "uXWrHT-Kxjttu1nDga-fdKqs6SCi01cq-nVb4bfXsSE";/*** */private static final long serialVersionUID = 1L;public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException {SimpleDateFormat sFormat = new SimpleDateFormat("yyyy-mm-dd HH:mm:ss");//System.out.println("request-url:" + request.getRequestURL().toString());System.out.println("ResponseNews----get--" + sFormat.format(new Date()));//System.out.println("请求格式:" + request.getContentType());request.setCharacterEncoding("utf-8");String getContextPath = request.getContextPath();String basePath = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort()+ getContextPath + "/";//System.out.println("basePath:" + basePath);/** String getRemoteAddress=request.getRemoteAddr(); String* getServletPath =request.getServletPath(); String* getServletContext_getRealPath =request.getServletPath();*/String getRequestURL = request.getRequestURL().toString();//System.out.println("getRequestURL:" + getRequestURL);/** String getRequestURI =request.getRequestURI(); String getRemoteUser* =request.getRemoteUser();*/String getQueryString = request.getQueryString();//System.out.println("请求参数getQueryString:" + getQueryString);// System.out.println("需要解密的字段,获取其中echostr信息:"+teMap.get("echostr"));//System.out.println("request.getParameter--" + request.getParameter("echostr"));String sVerifyMsgSig = request.getParameter("msg_signature");String sVerifyTimeStamp = request.getParameter("timestamp");String sVerifyNonce = request.getParameter("nonce");String sVerifyEchoStr = request.getParameter("echostr");String sEchoStr = null; // 需要返回的明文WXBizMsgCrypt wxcpt = null;if (sEncodingAESKey.length() != 43) {System.out.println("sEncodingAESKey 长度异常");}try {wxcpt = new WXBizMsgCrypt(sToken, sEncodingAESKey, sCorpID);sEchoStr = wxcpt.VerifyURL(sVerifyMsgSig, sVerifyTimeStamp, sVerifyNonce, sVerifyEchoStr);System.out.println("解密结果verifyurl echostr: " + sEchoStr);// 验证URL成功,将sEchoStr返回} catch (Exception e) {// 验证URL失败,错误原因请查看异常e.printStackTrace();}/** response.setCharacterEncoding("UTF-8");//设置将字符以"UTF-8"编码输出到客户端浏览器* response.setHeader("content-type", "text/html;charset=UTF-8");* response.setContentType("text/htmll;charset=utf-8");*/PrintWriter out = response.getWriter();String numbers = sEchoStr;out.println(numbers);}/*** The doPost method of the servlet. <br>** This method is called when a form has its tag value method equals to* post.* * @param request*            the request send by the client to the server* @param response*            the response send by the server to the client* @throws ServletException*             if an error occurred* @throws IOException*             if an error occurred*/public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {// 获取accestoken后,发送post请求,目前发送txt格式,发送的参数为json格式JSONObject jsparam = new JSONObject();JSONObject jsparam2 = new JSONObject();WXBizMsgCrypt wxcpt = null;String sReqMsgSig = null;//String sReqTimeStamp = null;// 时间戳String sReqNonce = null;// 随机数// 解密消息参数String ToUserName = null;// 发送信息用户名String MsgId = null;// 此次消息的msgidString Content = null;// 请求消息try {wxcpt = new WXBizMsgCrypt(sToken, sEncodingAESKey, sCorpID);} catch (AesException e1) {e1.printStackTrace();}System.out.println("处理Post()请求------");System.out.println("request信息如下:");response.setContentType("text/html;charset=UTF-8");/** String getContextPath = request.getContextPath(); String basePath =* request.getScheme()+"://"+request.getServerName()+":"+request.* getServerPort()+getContextPath+"/"; String getServletPath =* request.getServletPath(); String getRemoteUser =* request.getRemoteUser(); String getRequestUri =* request.getRequestURI();*/String getRequestUrl = request.getRequestURL().toString();String getQueryString = request.getQueryString();// 获取请求体BufferedReader bReader = request.getReader();String str, sReqData = "";while ((str = bReader.readLine()) != null) {sReqData += str;}// System.out.println("getContextPath:"+getContextPath);// System.out.println("basePath:"+basePath);System.out.println("getRequestUrl:" + getRequestUrl);// System.out.println("getRequestUri:"+getRequestUri);// System.out.println("getQueryString:" + getQueryString);System.out.println("请求body的加密信息:" + sReqData);// 对url中的参数进行校验和处理if (getQueryString == null && ("").equals(getQueryString)) {System.out.println("请求url的参数为空");}System.out.println("获取url参数后,需要解密");sReqMsgSig = request.getParameter("msg_signature");sReqTimeStamp = request.getParameter("timestamp");sReqNonce = request.getParameter("nonce");String sMsg = "";try {sMsg = wxcpt.DecryptMsg(sReqMsgSig, sReqTimeStamp, sReqNonce, sReqData);System.out.println("解密结果after decrypt msg: " + sMsg);// TODO: 解析出明文xml标签的内容进行处理// For example:DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();DocumentBuilder db = dbf.newDocumentBuilder();StringReader sr = new StringReader(sMsg);InputSource is = new InputSource(sr);Document document = db.parse(is);Element root = document.getDocumentElement();NodeList nodelist1 = root.getElementsByTagName("Content");Content = nodelist1.item(0).getTextContent();ToUserName = root.getElementsByTagName("AgentID").item(0).getTextContent();MsgId = root.getElementsByTagName("MsgId").item(0).getTextContent();System.out.println("解析企业号发送信息Content:" + Content);} catch (AesException e) {System.out.println("获取request参数及body后,解析异常");e.printStackTrace();} catch (ParserConfigurationException e) {// TODO Auto-generated catch blocke.printStackTrace();} catch (SAXException e) {// TODO Auto-generated catch blocke.printStackTrace();}System.out.println("response信息");response.setContentType("text/htmll;charset=utf-8");/** 处理返回的加密信息 其中xml中的Nonce是随机数,TimeStamp是时间戳 sReqTimeStamp,* sReqNonce取自请求request参数* */PrintWriter out = response.getWriter();// String sRespData =// "<xml><ToUserName><![CDATA[mycreate]]></ToUserName><FromUserName><![CDATA[wx5823bf96d3bd56c7]]></FromUserName><CreateTime>1348831860</CreateTime><MsgType><![CDATA[text]]></MsgType><Content><![CDATA[this// is a// test]]></Content><MsgId>1234567890123456</MsgId><AgentID>128</AgentID></xml>";// String sRespData =// "<xml><ToUserName><![CDATA[PengWu]]></ToUserName><FromUserName><![CDATA[wx5823bf96d3bd56c7]]></FromUserName><CreateTime>1348831860</CreateTime><MsgType><![CDATA[text]]></MsgType><Content><![CDATA[this// is a// test]]></Content><MsgId>1234567890123456</MsgId><AgentID>1000002</AgentID></xml>";String sRespData = "";if (("text").equals(Content)) {sRespData = "<xml><ToUserName><![CDATA[" + ToUserName+ "]]></ToUserName><FromUserName><![CDATA[wx5823bf96d3bd56c7]]></FromUserName><CreateTime>"+ System.currentTimeMillis() + "</CreateTime><MsgType><![CDATA[text]]></MsgType><Content><![CDATA["+ "response news -- test,type:text" + "]]></Content><MsgId>" + MsgId + "</MsgId><AgentID>"+ sAgentId + "</AgentID></xml>";} else if (("image").equals(Content)) {sRespData="200";} else {sRespData = "<xml><ToUserName><![CDATA[" + ToUserName + "]]></ToUserName><FromUserName><![CDATA[" + sCorpID+ "]]></FromUserName><CreateTime>" + System.currentTimeMillis() + "</CreateTime><MsgType><![CDATA["+ "text" + "]]></MsgType><Content><![CDATA[" + Content + "]]></Content><MsgId>" + MsgId+ "</MsgId><AgentID>" + sAgentId + "</AgentID></xml>";}// String sRespData = ToXmlString("response news -- test ",ToUserName);try {String sEncryptMsg = wxcpt.EncryptMsg(sRespData, sReqTimeStamp, sReqNonce);System.out.println("相应消息加密结果--after encrypt sEncrytMsg: " + sEncryptMsg);out.println(sEncryptMsg);// 加密成功// TODO:// HttpUtils.SetResponse(sEncryptMsg);} catch (Exception e) {e.printStackTrace();// 加密失败}}// 对于txt格式的xml生成private String ToXmlString(String content, String ToUserName) {Random random = new Random();// "<xml><ToUserName><![CDATA[mycreate]]></ToUserName><FromUserName><![CDATA[wx5823bf96d3bd56c7]]></FromUserName><CreateTime>1348831860</CreateTime><MsgType><![CDATA[text]]></MsgType><Content><![CDATA[this// is a// test]]></Content><MsgId>1234567890123456</MsgId><AgentID>128</AgentID></xml>";String lString = "<xml><ToUserName><![CDATA[{0}]]></ToUserName><FromUserName><![CDATA[{1}]]></FromUserName><CreateTime>{2}</CreateTime><MsgType><![CDATA[{3}]]></MsgType><Content><![CDATA[{4}]]></Content><MsgId>{5}</MsgId><AgentID>{6}</AgentID></xml>";lString = String.format(lString, ToUserName, sCorpID, System.currentTimeMillis(), "text", content,random.nextInt(214748364) + 1, sAgentId);// String s =// "<xml><ToUserName><![CDATA[{0}]]></ToUserName><FromUserName><![CDATA[{1}]]></FromUserName><CreateTime>{2}</CreateTime><MsgType><![CDATA[{3}]]></MsgType><Content><![CDATA[{4}]]></Content></xml>";// s = String.format(s,"wzwl005", sCorpID, System.currentTimeMillis(),// "text", content);return lString;}}

简单的web工程接收消息text--微信企业号相关推荐

  1. 最简单web工程接收消息图片--微信企业号

    java的web 工程,接收消息,发送图片信息 企业微信api 企业号开发者接口文档 企业微信接口调试工具 微信企业号错误代码查询工具 原理:有移动端输入信息到企业号,企业号中的信息有微信服务器加密之 ...

  2. 微信企业号接收消息服务器配置,微信企业号企业消息功能介绍与操作

    昨日微信企业号有重大的更新,出现了不用加好友也能进行聊天的功能,这个功能叫做"企业消息"下面我们来看看微信企业号企业消息功能介绍与操作吧. 相信很多人在微信上都有过这种经历: 因为 ...

  3. java 微信 接收消息_微信公众平台开发教程Java版(三) 消息接收和发送

    https://www.iteye.com/blog/tuposky-2017429 前面两章已经介绍了如何接入微信公众平台,这一章说说消息的接收和发送 可以先了解公众平台的消息api接口(接收消息, ...

  4. PC微信逆向:发送与接收消息的分析与代码实现

    文章目录 定位微信的消息接收函数 定位消息接收函数的相关思路 定位消息内容的地址 分析接收消息函数 好友消息 群消息 总结 代码实现 定位微信的消息发送函数 定位消息发送函数的相关思路 过滤当前聊天窗 ...

  5. 配置Tomcat和在Eclipse中创建Web工程

    配置Tomcat服务器信息: 在Tomcat的安装目录下有一个conf目录,里面存放着Tomcat服务器的配置文件,其中最为核心的配置文件是server.xml,在这个文件里我们可以配置服务器的各种参 ...

  6. IntelliJ IDEA 部署Tomcat及创建一个web工程

    一.部署Tomcat 二.新建一个web工程 1.新建一个Project 2.现在建立一个简单的web工程,所以只勾选下面选中的,此外,本版本(IntelliJ IDEA 14.1.5只支持3.1版本 ...

  7. 微信企业号_智能机器人_python3

    前提,不使用网络上提供的第三方机器人接口(类似微软小冰.图灵机器人),而是部署自己训练的智能机器人. ##TODO 部署机器人 ##选择明文模式 在后面会作说明为何不选安全模式. 具体配置以及要注意的 ...

  8. 微信企业号开发:微信考勤摇一摇考勤

    看到网上又不少微信企业号的摇一摇考勤,自己也想做一个,但查遍了微信企业号文档,也没有看到摇一摇的相关API,本以为做不出来了,想不到再问了同事后,才知道其实很简单,摇一摇不需要微信企业号的文档,HTM ...

  9. C# 企业微信:开启消息接受接收消息推送消息

    前言:微信吧!接触的人都会100%各种踩坑,就算同样东西去年做过,今年来一样踩坑,因为太多你稍微不记得一点点的细节就能让你研究N久.为此,我要把这个过程详细的记录下来. 一.开启消息接受 1.拿到企业 ...

最新文章

  1. 隐去浏览器中当鼠标移到图片上跳出的工具栏
  2. 计算机应用基础2016高起专,计算机应用基础-2016年秋季《计算机应用基础(高起专)》期末考核(20210407163441).pdf...
  3. 三、HDFS中的Java和Python API接口连接
  4. 便捷的flex弹性布局
  5. 怎么说呢。留个纪念,关于字符串的重载
  6. android模拟器上安装/卸载app
  7. JavaScript 里 window, document, screen, body 这几个名词的区别
  8. python flask快速入门与进阶 百度云_Python Flask快速入门与进阶
  9. 面试被问线程池,真香
  10. 稀缺时尚男模促销海报|PSD分层,简单搞定设计稿
  11. php 用header()下载文件在firefox下没有后缀名
  12. Microsoft Visio Pro 2016产品密钥破解完整免费下载
  13. 智能运维发展史及核心技术研究
  14. Python】Scrapy抓取多玩Gif图片
  15. Skype不能打开解决记录(win7)
  16. sumifs两个求和列如何计算_「sumifs」多条件求和函数Sumifs的用法 - seo实验室
  17. 417分上那所计算机学院,2021年高考417分左右能上什么大学(100所)
  18. Spring实例(DI注入)——女生追男生
  19. shell脚本开头#!/bin/bash和#!/bin/sh是什么意思以及区别
  20. 记一次quartz定时任务不执行排雷

热门文章

  1. 用Simulink对Carsim车辆进行档位控制
  2. 3D视觉检测:智能工业机器人从平面到立体的“视界”升级
  3. Prolific USB-to-Serial Comm Port在win8.1下
  4. RationalDMIS 7.1 状态区-测量设置
  5. cloop( )和feedback( )的区别
  6. MySQL高级篇知识点——其它数据库日志
  7. 安徽阜阳计算机高中学校排名,阜阳中学排名前十名,2021年阜阳中学排名一览表...
  8. http://www.dewen.net.cn/q/14665/个人感觉用二分法最完美的,需要操作系统支持随机读取指定一行的数据,貌似现在还不行,江湖救急呀...
  9. linux主机通过top看CPU性能指标
  10. js搞定网页的简繁转换