Home php教程 php手册 微信公众帐号开发教程第5篇-各种消息的接收与响应

微信公众帐号开发教程第5篇-各种消息的接收与响应

Jun 13, 2016 am 11:28 AM
and response develop WeChat us Bundle take over Tutorial article information of

前一篇文章里我们已经把微信公众平台接口中消息及相关操作都进行了封装,本章节将主要介绍如何接收微信服务器发送的消息并做出响应。

 

明确在哪接收消息

从微信公众平台接口消息指南中可以了解到,当用户向公众帐号发消息时,微信服务器会将消息通过POST方式提交给我们在接口配置信息中填写的URL,而我们就需要在URL所指向的请求处理类CoreServlet的doPost方法中接收消息、处理消息和响应消息。

 

接收、处理、响应消息

下面先来看我已经写好的CoreServlet的完整代码:

package org.liufeng.course.servlet;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.liufeng.course.service.CoreService;
import org.liufeng.course.util.SignUtil;

/**
 * 核心请求处理类
 * 
 * @author liufeng
 * @date 2013-05-18
 */
public class CoreServlet extends HttpServlet {
	private static final long serialVersionUID = 4440739483644821986L;

	/**
	 * 确认请求来自微信服务器
	 */
	public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// 微信加密签名
		String signature = request.getParameter("signature");
		// 时间戳
		String timestamp = request.getParameter("timestamp");
		// 随机数
		String nonce = request.getParameter("nonce");
		// 随机字符串
		String echostr = request.getParameter("echostr");

		PrintWriter out = response.getWriter();
		// 通过检验signature对请求进行校验,若校验成功则原样返回echostr,表示接入成功,否则接入失败
		if (SignUtil.checkSignature(signature, timestamp, nonce)) {
			out.print(echostr);
		}
		out.close();
		out = null;
	}

	/**
	 * 处理微信服务器发来的消息
	 */
	public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// 将请求、响应的编码均设置为UTF-8(防止中文乱码)
		request.setCharacterEncoding("UTF-8");
		response.setCharacterEncoding("UTF-8");

		// 调用核心业务类接收消息、处理消息
		String respMessage = CoreService.processRequest(request);
		
		// 响应消息
		PrintWriter out = response.getWriter();
		out.print(respMessage);
		out.close();
	}

}
Copy after login
 

代码说明:

1)第29行:调用消息工具类MessageUtil解析微信发来的xml格式的消息,解析的结果放在HashMap里;

2)32~36行:从HashMap中取出消息中的字段;

3)39-44、84行:组装要返回的文本消息对象;

4)47~82行:演示了如何接收微信发送的各类型的消息,根据MsgType判断属于哪种类型的消息;

5)85行:调用消息工具类MessageUtil将要返回的文本消息对象TextMessage转化成xml格式的字符串;

 

关于事件推送(关注、取消关注、菜单点击)

对于消息类型的判断,像文本消息、图片消息、地理位置消息、链接消息和语音消息都比较好理解,有很多刚接触的朋友搞不懂事件推送消息有什么用,或者不清楚该如何判断用户关注的消息。那我们就专门来看下事件推送,下图是官方消息接口文档中关于事件推送的说明:

这里我们只要关心两个参数:MsgType和Event。当MsgType=event时,就表示这是一条事件推送消息;而Event表示事件类型,包括订阅、取消订阅和自定义菜单点击事件。也就是说,无论用户是关注了公众帐号、取消对公众帐号的关注,还是在使用公众帐号的菜单,微信服务器都会发送一条MsgType=event的消息给我们,而至于具体这条消息表示关注、取消关注,还是菜单的点击事件,就需要通过Event的值来判断了。(注意区分Event和event)

 

连载五篇教程总结

经过5篇的讲解,已经把开发模式启用,接口配置,消息相关工具类的封装,消息的接收与响应全部讲解完了,而且贴上了完整的源代码,相信有一定Java基础的朋友可以看的明白,能够通过系列文章基本掌握微信公众平台开发的相关技术知识。下面我把目前项目的完整结构贴出,方便大家对照:


Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

Java Tutorial
1663
14
PHP Tutorial
1266
29
C# Tutorial
1239
24
Advanced Bootstrap Tutorial: Mastering Customization & Components Advanced Bootstrap Tutorial: Mastering Customization & Components Apr 04, 2025 am 12:04 AM

How to master Bootstrap customization and component usage includes: 1. Use CSS variables and Sass preprocessor for style customization; 2. Deeply understand and modify component structure and behavior. Through these methods, a unique user interface can be created to improve the responsiveness and user experience of the website.

Is the company's security software causing the application to fail to run? How to troubleshoot and solve it? Is the company's security software causing the application to fail to run? How to troubleshoot and solve it? Apr 19, 2025 pm 04:51 PM

Troubleshooting and solutions to the company's security software that causes some applications to not function properly. Many companies will deploy security software in order to ensure internal network security. ...

What is the difference between H5 page production and WeChat applets What is the difference between H5 page production and WeChat applets Apr 05, 2025 pm 11:51 PM

H5 is more flexible and customizable, but requires skilled technology; mini programs are quick to get started and easy to maintain, but are limited by the WeChat framework.

The difference between H5 and mini-programs and APPs The difference between H5 and mini-programs and APPs Apr 06, 2025 am 10:42 AM

H5. The main difference between mini programs and APP is: technical architecture: H5 is based on web technology, and mini programs and APP are independent applications. Experience and functions: H5 is light and easy to use, with limited functions; mini programs are lightweight and have good interactiveness; APPs are powerful and have smooth experience. Compatibility: H5 is cross-platform compatible, applets and APPs are restricted by the platform. Development cost: H5 has low development cost, medium mini programs, and highest APP. Applicable scenarios: H5 is suitable for information display, applets are suitable for lightweight applications, and APPs are suitable for complex functions.

How to solve the problem of JS resource caching in enterprise WeChat? How to solve the problem of JS resource caching in enterprise WeChat? Apr 04, 2025 pm 05:06 PM

Discussion on the JS resource caching issue of Enterprise WeChat. When upgrading project functions, some users often encounter situations where they fail to successfully upgrade, especially in the enterprise...

What should I do if the company's security software conflicts with applications? How to troubleshoot HUES security software causes common software to fail to open? What should I do if the company's security software conflicts with applications? How to troubleshoot HUES security software causes common software to fail to open? Apr 01, 2025 pm 10:48 PM

Compatibility issues and troubleshooting methods for company security software and application. Many companies will install security software in order to ensure intranet security. However, security software sometimes...

Ouyi Exchange app domestic download tutorial Ouyi Exchange app domestic download tutorial Mar 21, 2025 pm 05:42 PM

This article provides a detailed guide to safe download of Ouyi OKX App in China. Due to restrictions on domestic app stores, users are advised to download the App through the official website of Ouyi OKX, or use the QR code provided by the official website to scan and download. During the download process, be sure to verify the official website address, check the application permissions, perform a security scan after installation, and enable two-factor verification. During use, please abide by local laws and regulations, use a safe network environment, protect account security, be vigilant against fraud, and invest rationally. This article is for reference only and does not constitute investment advice. Digital asset transactions are at your own risk.

What are the development tools for H5 and mini program? What are the development tools for H5 and mini program? Apr 06, 2025 am 09:54 AM

H5 development tools recommendations: VSCode, WebStorm, Atom, Brackets, Sublime Text; Mini Program Development Tools: WeChat Developer Tools, Alipay Mini Program Developer Tools, Baidu Smart Mini Program IDE, Toutiao Mini Program Developer Tools, Taro.

See all articles