【微信Java开发 --2】接入微信公众平台开发,配置自己的服务器,验证过程【验证服务器、自定义菜单、微信端消息分发】

本文涉及的产品
密钥管理服务KMS,1000个密钥,100个凭据,1个月
简介: 接入微信公众平台开发,开发者需要按照如下步骤完成:1、填写服务器配置2、验证服务器地址的有效性3、依据接口文档实现业务逻辑好我们就开始:1.登录微信公众平台,进入基本配置 修改配置,将自己的服务器的URL地址,配置在此处:填写完成后,【先不用 提交】,先进行第二步 服务器端代码的配置...

接入微信公众平台开发,开发者需要按照如下步骤完成:

1、填写服务器配置
2、验证服务器地址的有效性
3、依据接口文档实现业务逻辑


好我们就开始:
1.登录微信公众平台,进入基本配置

 修改配置,将自己的服务器的URL地址,配置在此处:

填写完成后,【先不用 提交】,先进行第二步 服务器端代码的配置

 

注意:

如果想使用  自定义菜单等相关接口权限,需要注意:

 

可以看到  个人订阅号是没有 使用自定义菜单的相关接口能力的,如果需要使用的话,需要注册服务号或使用测试号:

 

 那么 在服务器端代码中使用的 测试AppId/Secret/Token等都需要重新设置为测试号的相关信息!

 

 

 

2.服务器端配置相关

服务器端相关代码 思路:

 

  1>首先搭建web项目,使用maven管理架包,项目架构用spring+spring MVC+hibernate,pom.xml文件中,关于微信端开发的配置就是,就是使用weixin-java-tools项目使用java进行微信端开发

<!-- 微信开发工具包 -->
        
        <!-- https://mvnrepository.com/artifact/com.github.binarywang/weixin-java-common -->
        <dependency>
            <groupId>com.github.binarywang</groupId>
            <artifactId>weixin-java-common</artifactId>
            <version>2.2.0</version>
        </dependency>
        <!-- https://mvnrepository.com/artifact/com.github.binarywang/weixin-java-mp -->
        <dependency>
            <groupId>com.github.binarywang</groupId>
            <artifactId>weixin-java-mp</artifactId>
            <version>2.2.0</version>
        </dependency>

 

完整pom.xml文件信息

  1 <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  2   <modelVersion>4.0.0</modelVersion>
  3   <groupId>com.sxd.wx1</groupId>
  4   <artifactId>wxSecond</artifactId>
  5   <version>0.0.1-SNAPSHOT</version>
  6   <packaging>war</packaging>
  7   <build>
  8       <plugins>
  9           <plugin>
 10               <artifactId>maven-war-plugin</artifactId>
 11               <configuration>
 12                   <version>3.0</version>
 13               </configuration>
 14           </plugin>
 15       </plugins>
 16   </build>
 17   
 18       <properties>
 19         <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
 20         <spring.version>4.1.4.RELEASE</spring.version>
 21         <hibernate.version>4.3.8.Final</hibernate.version>
 22     </properties>
 23     
 24   <dependencies>
 25       <!-- https://mvnrepository.com/artifact/javax.persistence/persistence-api -->
 26     <dependency>
 27         <groupId>javax.persistence</groupId>
 28         <artifactId>persistence-api</artifactId>
 29         <version>1.0</version>
 30     </dependency>
 31       <!-- 进行加密操作 -->
 32         <dependency>
 33             <groupId>commons-codec</groupId>
 34             <artifactId>commons-codec</artifactId>
 35             <version>1.10</version>
 36         </dependency>
 37           
 38           <!-- https://mvnrepository.com/artifact/dom4j/dom4j -->
 39         <dependency>
 40             <groupId>dom4j</groupId>
 41             <artifactId>dom4j</artifactId>
 42             <version>1.6.1</version>
 43         </dependency>
 44 
 45           
 46       <!-- 微信开发工具包 -->
 47         
 48         <!-- https://mvnrepository.com/artifact/com.github.binarywang/weixin-java-common -->
 49         <dependency>
 50             <groupId>com.github.binarywang</groupId>
 51             <artifactId>weixin-java-common</artifactId>
 52             <version>2.2.0</version>
 53         </dependency>
 54         <!-- https://mvnrepository.com/artifact/com.github.binarywang/weixin-java-mp -->
 55         <dependency>
 56             <groupId>com.github.binarywang</groupId>
 57             <artifactId>weixin-java-mp</artifactId>
 58             <version>2.2.0</version>
 59         </dependency>
 60         
 61         
 62         <!-- junit -->
 63         <dependency>
 64             <groupId>junit</groupId>
 65             <artifactId>junit</artifactId>
 66             <version>4.12</version>
 67             <scope>test</scope>
 68         </dependency>
 69 
 70         <!-- https://mvnrepository.com/artifact/com.github.pagehelper/pagehelper -->
 71         <dependency>
 72             <groupId>com.github.pagehelper</groupId>
 73             <artifactId>pagehelper</artifactId>
 74             <version>4.1.4</version>
 75         </dependency>
 76         
 77         <!-- spring -->
 78         <dependency>
 79             <groupId>org.springframework</groupId>
 80             <artifactId>spring-core</artifactId>
 81             <version>${spring.version}</version>
 82         </dependency>
 83 
 84         <dependency>
 85             <groupId>org.springframework</groupId>
 86             <artifactId>spring-beans</artifactId>
 87             <version>${spring.version}</version>
 88         </dependency>
 89 
 90         <dependency>
 91             <groupId>org.springframework</groupId>
 92             <artifactId>spring-context</artifactId>
 93             <version>${spring.version}</version>
 94         </dependency>
 95 
 96         <dependency>
 97             <groupId>org.springframework</groupId>
 98             <artifactId>spring-tx</artifactId>
 99             <version>${spring.version}</version>
100         </dependency>
101 
102         <dependency>
103             <groupId>org.springframework</groupId>
104             <artifactId>spring-web</artifactId>
105             <version>${spring.version}</version>
106         </dependency>
107 
108         <dependency>
109             <groupId>org.springframework</groupId>
110             <artifactId>spring-test</artifactId>
111             <version>${spring.version}</version>
112             <scope>test</scope>
113         </dependency>
114 
115         <!-- 使用SpringMVC需配置 -->
116         <dependency>
117             <groupId>org.springframework</groupId>
118             <artifactId>spring-webmvc</artifactId>
119             <version>${spring.version}</version>
120         </dependency>
121         <!-- spring cglib 代理 -->
122         <dependency>
123             <groupId>cglib</groupId>
124             <artifactId>cglib</artifactId>
125             <version>2.2.2</version>
126         </dependency>
127         <!-- 关系型数据库整合时需配置 如hibernate jpa等 -->
128         <dependency>
129             <groupId>org.springframework</groupId>
130             <artifactId>spring-orm</artifactId>
131             <version>${spring.version}</version>
132         </dependency>
133 
134         <!-- hibernate -->
135         <dependency>
136             <groupId>org.hibernate</groupId>
137             <artifactId>hibernate-core</artifactId>
138             <version>${hibernate.version}</version>
139         </dependency>
140 
141         <dependency>
142             <groupId>org.hibernate</groupId>
143             <artifactId>hibernate-ehcache</artifactId>
144             <version>${hibernate.version}</version>
145         </dependency>
146 
147         <!-- 二级缓存ehcache -->
148         <dependency>
149             <groupId>net.sf.ehcache</groupId>
150             <artifactId>ehcache</artifactId>
151             <version>2.9.0</version>
152         </dependency>
153 
154         <!-- log4j -->
155         <dependency>
156             <groupId>log4j</groupId>
157             <artifactId>log4j</artifactId>
158             <version>1.2.17</version>
159         </dependency>
160 
161         <!-- mysql连接 -->
162         <dependency>
163             <groupId>mysql</groupId>
164             <artifactId>mysql-connector-java</artifactId>
165             <version>5.1.34</version>
166         </dependency>
167 
168         <!-- c3p0数据源 -->
169         <dependency>
170             <groupId>com.mchange</groupId>
171             <artifactId>c3p0</artifactId>
172             <version>0.9.5-pre10</version>
173         </dependency>
174 
175         <!-- json -->
176 
177         <!-- 1号 -->
178         <dependency>
179             <groupId>com.fasterxml.jackson.core</groupId>
180             <artifactId>jackson-core</artifactId>
181             <version>2.8.1</version>
182         </dependency>
183         <!-- 2号 -->
184         <dependency>
185             <groupId>com.fasterxml.jackson.core</groupId>
186             <artifactId>jackson-annotations</artifactId>
187             <version>2.8.1</version>
188         </dependency>
189 
190         <!-- 3号 -->
191         <dependency>
192             <groupId>com.fasterxml.jackson.core</groupId>
193             <artifactId>jackson-databind</artifactId>
194             <version>2.8.1</version>
195             <exclusions>
196                 <exclusion>
197                     <artifactId>jackson-core</artifactId>
198                     <groupId>com.fasterxml.jackson.core</groupId>
199                 </exclusion>
200                 <exclusion>
201                     <artifactId>jackson-annotations</artifactId>
202                     <groupId>com.fasterxml.jackson.core</groupId>
203                 </exclusion>
204             </exclusions>
205         </dependency>
206 
207         <!-- 4号 -->
208         <dependency>
209             <groupId>com.google.code.gson</groupId>
210             <artifactId>gson</artifactId>
211             <version>2.7</version>
212         </dependency>
213         <!-- 5号 -->
214         <dependency>
215             <groupId>net.sf.json-lib</groupId>
216             <artifactId>json-lib</artifactId>
217             <version>2.4</version>
218             <classifier>jdk15</classifier>
219         </dependency>
220         <!-- 5号json-lib还需要以下依赖包 -->
221         <dependency>
222             <groupId>commons-lang</groupId>
223             <artifactId>commons-lang</artifactId>
224             <version>2.5</version>
225         </dependency>
226         <dependency>
227             <groupId>commons-beanutils</groupId>
228             <artifactId>commons-beanutils</artifactId>
229             <version>1.9.2</version>
230         </dependency>
231         <dependency>
232             <groupId>commons-collections</groupId>
233             <artifactId>commons-collections</artifactId>
234             <version>3.2.1</version>
235         </dependency>
236         <dependency>
237             <groupId>commons-logging</groupId>
238             <artifactId>commons-logging</artifactId>
239             <version>1.2</version>
240         </dependency>
241         
242         <!-- aop -->
243         <dependency>
244             <groupId>org.aspectj</groupId>
245             <artifactId>aspectjweaver</artifactId>
246             <version>1.8.4</version>
247         </dependency>
248 
249         <!-- servlet -->
250         <dependency>
251             <groupId>javax.servlet</groupId>
252             <artifactId>servlet-api</artifactId>
253             <version>3.0-alpha-1</version>
254             <scope>provided</scope>
255         </dependency>
256 
257         <dependency>
258             <groupId>javax.servlet</groupId>
259             <artifactId>jstl</artifactId>
260             <version>1.2</version>
261         </dependency>
262         <!-- guava 集合的交并操作 -->        
263         <dependency>
264             <groupId>com.google.guava</groupId>
265             <artifactId>guava</artifactId>
266             <version>19.0</version>
267         </dependency>
268         <dependency>
269             <groupId>com.google.guava</groupId>
270             <artifactId>guava-collections</artifactId>
271             <version>r03</version>
272         </dependency>
273         
274         <!-- 文件上传 -->
275         <dependency>
276             <groupId>commons-fileupload</groupId>
277             <artifactId>commons-fileupload</artifactId>
278             <version>1.3.1</version>
279         </dependency>
280 
281   </dependencies>
282 </project>
View Code

 2>服务器端代码:

  CenterController.java  

  1 package com.sxd.controller;
  2 
  3 import java.io.IOException;
  4 import java.util.ArrayList;
  5 import java.util.List;
  6 import java.util.Map;
  7 
  8 import javax.servlet.http.HttpServletRequest;
  9 import javax.servlet.http.HttpServletResponse;
 10 
 11 import me.chanjar.weixin.common.api.WxConsts;
 12 import me.chanjar.weixin.common.bean.menu.WxMenu;
 13 import me.chanjar.weixin.common.bean.menu.WxMenuButton;
 14 import me.chanjar.weixin.common.exception.WxErrorException;
 15 import me.chanjar.weixin.common.session.WxSessionManager;
 16 import me.chanjar.weixin.mp.api.WxMpConfigStorage;
 17 import me.chanjar.weixin.mp.api.WxMpInMemoryConfigStorage;
 18 import me.chanjar.weixin.mp.api.WxMpMessageHandler;
 19 import me.chanjar.weixin.mp.api.WxMpMessageRouter;
 20 import me.chanjar.weixin.mp.api.WxMpService;
 21 import me.chanjar.weixin.mp.api.impl.WxMpServiceImpl;
 22 import me.chanjar.weixin.mp.bean.WxMpXmlMessage;
 23 import me.chanjar.weixin.mp.bean.WxMpXmlOutMessage;
 24 import me.chanjar.weixin.mp.bean.WxMpXmlOutTextMessage;
 25 
 26 import org.springframework.context.annotation.Lazy;
 27 import org.springframework.stereotype.Controller;
 28 import org.springframework.web.bind.annotation.RequestMapping;
 29 import org.springframework.web.bind.annotation.ResponseBody;
 30 
 31 import com.sxd.util.ButtonMenuUtils;
 32 import com.sxd.util.Dom4jUtils;
 33 import com.sxd.util.RuleManager;
 34 
 35 
 36 /**
 37  * 中央处理器  
 38  * 
 39  * @author Administrator
 40  *
 41  */
 42 @Controller
 43 @RequestMapping("centercontroller")
 44 public class CenterController {
 45     
 46       public WxMpInMemoryConfigStorage config;//微信基本配置信息+Access Token
 47       public static WxMpService wxMpService;    //微信API的Service
 48       public WxMpMessageRouter wxMpMessageRouter;//微信消息路由器
 49       public static String accessToken; 
 50       
 51       
 52     /**
 53      * 1.处理微信首次配置信息+创建按钮   【首次创建后可以  注释initWeiXin()方法 不用每次都执行】
 54      * 2.验证接口配置信息 【如果过时重新获取】
 55      * 3.消息转发---中转站   【每次微信端的信息都会从微信服务器转发到这里,然后从这里转发出去】
 56      * @param request
 57      * @param response
 58      * @return
 59      * @throws IOException
 60      * @throws WxErrorException
 61      */
 62     @RequestMapping("test")
 63     public String test1(HttpServletRequest request, HttpServletResponse response) throws IOException, WxErrorException{
 64         /**
 65          * 1.处理微信首次配置信息+创建按钮
 66          */
 67 //        initWeiXin();
 68         /**
 69          * 2.验证接口配置信息  如果过时重新获取
 70          */
 71         String echostr = request.getParameter("echostr");
 72         if(echostr != null){
 73             return "forward:/tokenCheckController/tokenCheck.htmls";
 74         }
 75         
 76         /**
 77          * 3.消息转发---中转站  每次微信端的消息都会来到这里进行分发
 78          */
 79         WxMpXmlMessage message = WxMpXmlMessage.fromXml(request.getInputStream());
 80         String msgType = message.getMsgType();
 81         Dom4jUtils dom4El = new Dom4jUtils();
 82         String url = dom4El.msgDispather(msgType);
 83         if(url != null){
 84             request.setAttribute("message", message);
 85             return url;
 86         }
 87         
 88         response.getWriter().write("无法辨识消息类型!!");
 89         return null;
 90         
 91     }
 92     
 93     
 94     /**
 95      * 初始化 微信相关配置  并且创建按钮
 96      * @throws WxErrorException 
 97      */
 98     public void initWeiXin() throws WxErrorException{
 99         config = new WxMpInMemoryConfigStorage();
100         config.setAppId("wx4848686e5bd4efce"); // 设置微信公众号的appid
101         config.setSecret("fc37ce345b3612d615d4ead83f21bdff"); // 设置微信公众号的app corpSecret
102         config.setToken("F0932398023"); // 设置微信公众号的token
103 
104         wxMpService = new WxMpServiceImpl();
105         wxMpService.setWxMpConfigStorage(config);//创建自己的service
106         if(config.getAccessToken() == null){
107             accessToken =  wxMpService.getAccessToken(true);//手动刷新获取了Access Token
108         }
109         //创建菜单按钮
110         ButtonMenuUtils bm = new ButtonMenuUtils();
111         WxMenu menu =  bm.createButtonMenu();
112         wxMpService.getMenuService().menuCreate(menu);
113     }
114     
115 }
View Code

  TokenCheckController.java

 1 package com.sxd.util.controller;
 2 
 3 import java.io.IOException;
 4 
 5 import javax.servlet.http.HttpServletRequest;
 6 import javax.servlet.http.HttpServletResponse;
 7 
 8 import org.springframework.stereotype.Controller;
 9 import org.springframework.web.bind.annotation.RequestMapping;
10 import org.springframework.web.bind.annotation.ResponseBody;
11 
12 import com.sxd.util.TokenCheckUtils;
13 
14 @Controller
15 @RequestMapping("tokenCheckController")
16 public class TokenCheckController {
17 
18     @RequestMapping("tokenCheck")
19     public void tokenCheck(HttpServletRequest request,HttpServletResponse response) throws IOException{
20         String signature = request.getParameter("signature");
21         String timestamp = request.getParameter("timestamp");
22         String nonce = request.getParameter("nonce");
23         String echostr = request.getParameter("echostr");
24         
25         TokenCheckUtils tokenCheckUtils = new TokenCheckUtils();
26         echostr = tokenCheckUtils.tokenCheck(signature, timestamp, nonce, echostr);
27         
28         response.getWriter().write(echostr);
29     }
30 }
View Code

  TokenCheckUtils.java

 1 package com.sxd.util;
 2 
 3 import java.util.ArrayList;
 4 import java.util.Collections;
 5 import java.util.List;
 6 
 7 import org.apache.commons.codec.digest.DigestUtils;
 8 
 9 /**
10  * 验证接口配置信息
11  * @author SXD
12  *
13  */
14 public class TokenCheckUtils {
15     
16     /**
17      * 验证接口配置信息
18      * 加密/校验流程如下:
19     1. 将token、timestamp、nonce三个参数进行字典序排序
20     2. 将三个参数字符串拼接成一个字符串进行sha1加密
21     3. 开发者获得加密后的字符串可与signature对比,标识该请求来源于微信
22      */
23     public String tokenCheck(String signature,String timestamp,String nonce,String echostr){
24         String token = "F0932398023";
25         List<String> list = new ArrayList<>();
26         list.add(timestamp);
27         list.add(token);
28         list.add(nonce);
29         
30         Collections.sort(list);//1.字典排序
31         
32         String str = DigestUtils.sha1Hex(list.get(0)+list.get(1)+list.get(2));//2.sha1加密
33         if(signature.equals(str)){//3.判断是否微信信息  此处判断echostr!=null是为了进行下面的操作不影响此处原本的效果
34             return echostr;
35             //    也就是说 如果echostr!=null,那么此次的请求是在验证是否成为开发者的;否则就是其他的微信请求,不用跳出程序
36         }
37         return null;
38     }
39 }
View Code

  msgTypeDispather.xml

 1 <?xml version="1.0" encoding="UTF-8"?>
 2 <WxDispather>
 3     <WxMsgType type="text" url="forward:/textMsgController/msgDeal.htmls"></WxMsgType>
 4     <WxMsgType type="image" url="forward:/imageMsgController/msgDeal.htmls"></WxMsgType>
 5     <WxMsgType type="voice" url="forward:/voiceMsgController/msgDeal.htmls"></WxMsgType>
 6     <WxMsgType type="video" url="forward:/videoMsgController/msgDeal.htmls"></WxMsgType>
 7     <WxMsgType type="shortvideo" url="forward:/shortvideoMsgController/msgDeal.htmls"></WxMsgType>
 8     <WxMsgType type="location" url="forward:/locationMsgController/msgDeal.htmls"></WxMsgType>
 9     <WxMsgType type="link" url="forward:/linkMsgController/msgDeal.htmls"></WxMsgType>
10     <WxMsgType type="event" url="forward:/eventMsgController/msgDeal.htmls"></WxMsgType>
11     
12 </WxDispather>
View Code

  Dom4jUtils.java

 1 package com.sxd.util;
 2 
 3 import java.util.List;
 4 
 5 import org.dom4j.Document;
 6 import org.dom4j.DocumentException;
 7 import org.dom4j.Element;
 8 import org.dom4j.io.SAXReader;
 9 
10 import com.sxd.test.util.Dom4jTest;
11 
12 /**
13  * 根据微信端发送的消息,解析出消息类型,加载配置文件,根据消息类型,将消息转发到对应
14  * 消息类型对应的Controller中进行响应处理
15  * @author SXD
16  *
17  */
18 public class Dom4jUtils {
19     
20     /**
21      * 使用dom4j解析消息类型配置文件,解析获得的相对应的服务器端的地址,进行访问
22      * @param msgType
23      * @return
24      */
25     public String msgDispather(String msgType){
26         SAXReader sReader = new SAXReader();
27         Document document;
28         try {
29             document = sReader.read(Dom4jUtils.class.getResourceAsStream("/msgTypeDispather.xml"));
30             List<Element> list =  document.getRootElement().elements();
31             for (Element element : list) {
32                 if(msgType.equals(element.attributeValue("type"))){
33                     return element.attributeValue("url");
34                 }
35             }
36         } catch (DocumentException e) {
37             e.printStackTrace();
38         }
39         return null;
40     }
41 }
View Code

  EventMsgController.java

 1 package com.sxd.message.controller;
 2 
 3 import java.util.stream.Stream;
 4 
 5 import javax.servlet.http.HttpServletRequest;
 6 import javax.servlet.http.HttpServletResponse;
 7 
 8 import me.chanjar.weixin.common.exception.WxErrorException;
 9 import me.chanjar.weixin.mp.bean.WxMpXmlMessage;
10 
11 import org.springframework.stereotype.Controller;
12 import org.springframework.web.bind.annotation.RequestMapping;
13 
14 import com.sxd.material.PermanentMaterialManager;
15 
16 /**
17  * event事件的服务端
18  * @author SXD
19  *
20  */
21 @Controller
22 @RequestMapping("eventMsgController")
23 public class EventMsgController {
24     
25     
26     @RequestMapping("msgDeal")
27     public void msgDeal(HttpServletRequest request, HttpServletResponse response) throws WxErrorException{
28         WxMpXmlMessage message = (WxMpXmlMessage) request.getAttribute("message");
29         //取消关注
30         if("unsubscribe".equals(message.getEvent())){
31             System.out.println("事件类型:"+message.getEvent());
32         }else if("subscribe".equals(message.getEvent())){//关注公众号
33             System.out.println("事件类型:"+message.getEvent());
34         }else{    //按钮点击事件
35             System.out.println("按钮的EventType:"+message.getEvent());
36             System.out.println("按钮的buttonKey:"+message.getEventKey());
37         }
38     }
39 }
View Code

  TextMsgController.java

 1 package com.sxd.message.controller;
 2 
 3 import java.io.IOException;
 4 
 5 import javax.servlet.http.HttpServletRequest;
 6 import javax.servlet.http.HttpServletResponse;
 7 
 8 import me.chanjar.weixin.mp.api.WxMpService;
 9 
10 import org.springframework.stereotype.Controller;
11 import org.springframework.web.bind.annotation.RequestMapping;
12 
13 import com.sxd.controller.CenterController;
14 import com.sxd.util.RuleManager;
15 
16 /**
17  * Text文本类型消息的服务端
18  * @author SXD
19  *
20  */
21 @Controller
22 @RequestMapping("textMsgController")
23 public class TextMsgController {
24 
25     /**
26      * Text消息处理逻辑
27      * @throws IOException 
28      */
29     @RequestMapping("msgDeal")
30     public void msgDeal(HttpServletRequest request, HttpServletResponse response) throws IOException{
31         WxMpService  wxMpService = CenterController.wxMpService;
32         RuleManager rm = new RuleManager();
33         rm.dealRule(wxMpService, request, response);
34     }
35 }
View Code

  RuleManager.java

 1 package com.sxd.util;
 2 
 3 import java.io.IOException;
 4 import java.util.Map;
 5 
 6 import javax.servlet.http.HttpServletRequest;
 7 import javax.servlet.http.HttpServletResponse;
 8 
 9 import me.chanjar.weixin.common.api.WxConsts;
10 import me.chanjar.weixin.common.exception.WxErrorException;
11 import me.chanjar.weixin.common.session.WxSessionManager;
12 import me.chanjar.weixin.mp.api.WxMpMessageHandler;
13 import me.chanjar.weixin.mp.api.WxMpMessageRouter;
14 import me.chanjar.weixin.mp.api.WxMpService;
15 import me.chanjar.weixin.mp.bean.WxMpXmlMessage;
16 import me.chanjar.weixin.mp.bean.WxMpXmlOutMessage;
17 import me.chanjar.weixin.mp.bean.WxMpXmlOutTextMessage;
18 
19 public class RuleManager {
20     
21      /**
22      * 消息处理逻辑  
23      * Text消息处理规则
24      */
25     public void dealRule(WxMpService wxMpService,HttpServletRequest request, HttpServletResponse response) throws IOException{
26         
27         WxMpMessageHandler handlerText = new WxMpMessageHandler() {
28             
29             @Override
30             public WxMpXmlOutMessage handle(WxMpXmlMessage wxMessage,
31                     Map<String, Object> context, WxMpService wxMpService,
32                     WxSessionManager sessionManager) throws WxErrorException {
33                 
34                 WxMpXmlOutTextMessage outMessage = new WxMpXmlOutTextMessage();
35                 outMessage.setToUserName(wxMessage.getFromUser());
36                 outMessage.setFromUserName(wxMessage.getToUser());
37                 outMessage.setCreateTime(System.currentTimeMillis()/1000);
38                 outMessage.setContent("你发送的<"+wxMessage.getContent()+">是一首歌么");
39                 return outMessage;
40             }
41         };
42         WxMpMessageHandler handlerText2 = new WxMpMessageHandler() {
43             
44             @Override
45             public WxMpXmlOutMessage handle(WxMpXmlMessage wxMessage,
46                     Map<String, Object> context, WxMpService wxMpService,
47                     WxSessionManager sessionManager) throws WxErrorException {
48                 
49                 WxMpXmlOutTextMessage outMessage = new WxMpXmlOutTextMessage();
50                 outMessage.setToUserName(wxMessage.getFromUser());
51                 outMessage.setFromUserName(wxMessage.getToUser());
52                 outMessage.setCreateTime(System.currentTimeMillis()/1000);
53                 outMessage.setContent("第二个满足了");
54                 return outMessage;
55             }
56         };
57         
58         
59         /**
60          * 消息处理规则,下面示例两个并列的规则,粗细粒度
61          */
62         WxMpMessageRouter router = new WxMpMessageRouter(wxMpService);
63         router.rule()
64         .async(false)
65         .msgType(WxConsts.XML_MSG_TEXT)
66         .content("我")
67         .handler(handlerText)
68         .end()
69         .rule()
70         .async(false)
71         .msgType(WxConsts.XML_MSG_TEXT)
72         .rContent(".*(我|你|他).*")
73         .handler(handlerText2)
74         .end();
75         
76         WxMpXmlMessage message = (WxMpXmlMessage) request.getAttribute("message");
77         WxMpXmlOutMessage outMessage = router.route(message);
78         if(outMessage==null){
79             WxMpXmlOutTextMessage outMessageCopy = new WxMpXmlOutTextMessage();
80             outMessageCopy.setToUserName(message.getFromUser());
81             outMessageCopy.setFromUserName(message.getToUser());
82             outMessageCopy.setCreateTime(System.currentTimeMillis()/1000);
83             outMessageCopy.setContent(message.getContent());
84             response.getWriter().write(outMessageCopy.toXml());
85             return ;
86         }
87         response.getWriter().write(outMessage.toXml());
88     }
89 }
View Code

 

 

在这里,不仅验证了服务器,也初始化了 自定义菜单,并且微信端的消息都进行了 分发!

3.服务器端代码写好后,启动服务器,然后再回头点击微信公众平台这里的提交按钮【此处使用测试号】

 

提示提交成功后就知道配置成功与否了。

相关文章
|
6月前
|
前端开发 开发者
【微信公众号对接】有关签名一直报错,提示invalid signature问题(我的签名和使用微信开发者工具验证返回的签名的是一致的)但还是报错!!!
【微信公众号对接】有关签名一直报错,提示invalid signature问题(我的签名和使用微信开发者工具验证返回的签名的是一致的)但还是报错!!!
384 0
|
2月前
|
弹性计算 负载均衡 监控
slb分发流量到ecs一般是如何判断?
【9月更文挑战第1天】
58 1
|
4月前
|
移动开发 JavaScript
thinkPHP5.0开发微信H5页面分享接口signature验证失败,signature与微信 JS 接口签名校验工具返回结果不一致
thinkPHP5.0开发微信H5页面分享接口signature验证失败,signature与微信 JS 接口签名校验工具返回结果不一致
86 0
|
4月前
|
PHP 开发工具
tp5+微信公众号服务器配置时使用官方sdk还是token验证失败
tp5+微信公众号服务器配置时使用官方sdk还是token验证失败
40 0
|
5月前
|
Java API
java进行微信公众号开发
java进行微信公众号开发
148 0
|
5月前
|
Linux 数据库 iOS开发
超级签名源码/超级签/ios分发/签名端本地linux服务器完成签名
该系统完全在linux下运行,不存在使用第三方收费工具,市面上很多系统都是使用的是第三方收费系统,例如:某心签名工具,某测侠等,不开源而且需要每年交费,这种系统只是在这些工具的基础上套了一层壳。请需要系统的放大你们的眼睛。
42 0
|
6月前
|
安全 Java Linux
企业微信应用结合Cpolar内网穿透实现固定域名验证回调本地接口服务
企业微信应用结合Cpolar内网穿透实现固定域名验证回调本地接口服务
|
6月前
|
人工智能 Python
【Python + 微信】微信公众号开发避坑指南
【Python + 微信】微信公众号开发避坑指南
121 0
|
6月前
|
XML 安全 Java
如何开发微信公众号后台
如何开发微信公众号后台
164 0
|
6月前
|
移动开发 JavaScript
微信公众号H5开发,在微信浏览器打开H5,无法一键下载图片
微信公众号H5开发,在微信浏览器打开H5,无法一键下载图片
219 0

热门文章

最新文章

下一篇
无影云桌面