Skip to content
jinyu edited this page May 9, 2016 · 3 revisions

weixin4j-server可单独作为一个服务启动,用于处理微信的被动消息,即用户主动发送给公众号的消息、系统通知等消息

###编写服务启动类 明文模式并总是调试输出微信请求信息的服务启动类.

public class MessageServerStartup{
	public static void main(String[] args) {
		new WeixinServerBootstrap("token").addHandler(
				DebugMessageHandler.global).startup();
	}
}

密文模式的服务启动类

public class MessageServerStartup{
	public static void main(String[] args) {
		new WeixinServerBootstrap("appid/corpid","token","aesKey").addHandler(
				DebugMessageHandler.global).startup();
	}
}

只针对文本消息的服务启动类

public class MessageServerStartup{
	public static void main(String[] args) {
		// 针对文本消息回复
		WeixinMessageHandler messageHandler = new MessageHandlerAdapter<TextMessage>() {
			@Override
			public WeixinResponse doHandle0(WeixinRequest request,
				TextMessage message) throws WeixinException {
					return new TextResponse("HelloWorld!");
			}
		};
		// 当消息类型为文本(text)时回复「HelloWorld」, 否则回复调试消息
		new WeixinServerBootstrap(appid, token, aesKey).addHandler(
				messageHandler, DebugMessageHandler.global).startup();
		}
	}
}

使用拦截器处理消息请求的启动类

public static void main(String[] args) {
	// 拦截所有请求
	WeixinMessageInterceptor interceptor = new MessageInterceptorAdapter() {
		@Override
		public boolean preHandle(ChannelHandlerContext context,
				WeixinRequest request, WeixinResponse response, Object message,
				WeixinMessageHandler handler) throws WeixinException {
			context.write(new TextResponse("所有消息被拦截了!"));
			return false;
		}
		@Override
		public void postHandle(ChannelHandlerContext context,
				WeixinRequest request, WeixinResponse response, WeixinResponse response,
				Object message, WeixinMessageHandler handler)
				throws WeixinException {
			System.err.println("preHandle返回为true,执行handler后");
		}
		@Override
		public void afterCompletion(ChannelHandlerContext context,
				WeixinRequest request, WeixinResponse response, Object message,
				WeixinMessageHandler handler, WeixinException exception)
				throws WeixinException {
			System.err.println("请求处理完毕");
		}
	};
	new WeixinServerBootstrap("token").addInterceptor(interceptor)
			.addHandler(BlankMessageHandler.global).startup();
}

相关参考

本地测试

扫描下图二维码进行体验

在线体验

消息服务时序图

assembly打包(辅助)

spring-webmvc:DispatcherServlet

spring-webmvc:HandlerAdapter

spring-webmvc:HandlerInterceptor

Clone this wiki locally