赞
踩
最近在研究微信公众号java开发,今天写一个简单的程序(我使用的是自己的微信测试号):
- <dependency>
- <groupId>com.github.binarywang</groupId>
- <artifactId>weixin-java-mp</artifactId>
- <version>2.9.0</version>
- </dependency>
springMVC的环境配置就不多说了。
2、wechatContorller,
- /**
- * 微信验证
- *
- */
- @RequestMapping("/index.do")
- public void index(HttpServletRequest request, HttpServletResponse response,
- HttpSession session) throws ServletException, IOException {
- wxMpServiceInstance.doResponse(request, response);
- }
3、WxMpServiceInstance
- public class WxMpServiceInstance{
- private static WxMpService wxMpService; // API 服务接口对象
- private WxMpConfigStorage wxMpConfigStorage; // 配置信息存储对象
- public static WxMpMessageRouter wxMpMessageRouter; // 微信消息路由器对象
- private WechatSendInformationService sendInformationService;
- @Resource
- private WechatManagementService wechatManagementService;
- @Resource
- private WechatRedreceiveRecordService wechatRedreceiveRecordService;
- private WxMpServiceInstance() {
- try {
- WxMpXMLInMemoryConfigStorage config = WxMpXMLInMemoryConfigStorage
- .fromXml();
- //微信公众号相关
- wxMpConfigStorage = config;
- wxMpService = new WxMpServiceImpl();
- wxMpService.setWxMpConfigStorage(config);
- wxMpMessageRouter = new WxMpMessageRouter(wxMpService);
-
- this.addEvtRouterRule();
-
- } catch (JAXBException e) {
- throw new RuntimeException(e);
- }
- }
-
- public WxMpService getWxMpService() {
- return wxMpService;
- }
-
- public void setWxMpService(WxMpService wxMpService) {
- this.wxMpService = wxMpService;
- }
-
- public WxMpConfigStorage getWxMpConfigStorage() {
- return wxMpConfigStorage;
- }
-
- public void setWxMpConfigStorage(WxMpConfigStorage wxMpConfigStorage) {
- this.wxMpConfigStorage = wxMpConfigStorage;
- }
-
- public WxMpMessageRouter getWxMpMessageRouter() {
- return wxMpMessageRouter;
- }
-
- public void setWxMpMessageRouter(WxMpMessageRouter wxMpMessageRouter) {
- this.wxMpMessageRouter = wxMpMessageRouter;
- }
- public void doResponse(HttpServletRequest request,
- HttpServletResponse response) throws ServletException, IOException {
- String signature = request.getParameter("signature");
- String nonce = request.getParameter("nonce");
- String timestamp = request.getParameter("timestamp");
-
-
- response.setContentType("text/html;charset=utf-8");
- response.setStatus(HttpServletResponse.SC_OK);
-
-
- if (!wxMpService.checkSignature(timestamp, nonce, signature)) {
- // 消息签名不正确,说明不是公众平台发过来的消息
- response.getWriter().println("非法请求");
- return; // 非法
- }
- // 合法
- String echostr = request.getParameter("echostr");
- if (StringUtils.isNotBlank(echostr)) {
- // 说明是一个仅仅用来验证的请求,回显echostr
- response.getWriter().println(echostr);
- return;
- }
-
- // 获取消息加密类型
- String encryptType = StringUtils.isBlank(request
- .getParameter("encrypt_type")) ? "raw" : request
- .getParameter("encrypt_type");
-
-
- WxMpXmlMessage inMessage = null; // 输入消息
-
-
- if ("raw".equals(encryptType)) {
- // 明文传输的消息
- try {
- inMessage = WxMpXmlMessage.fromXml(request.getInputStream());
- } catch (Exception e) {
- e.printStackTrace();
- }
-
- } else if ("aes".equals(encryptType)) {
- // 是aes加密的消息
- String msgSignature = request.getParameter("msg_signature");
- inMessage = WxMpXmlMessage.fromEncryptedXml(
- request.getInputStream(), wxMpConfigStorage, timestamp,
- nonce, msgSignature);
- } else {
- response.getWriter().println("不可识别的加密类型");
- return;
- }
- // 通过微信消息路由器处理输入消息inMessage,得到返回消息 outMessage
- WxMpXmlOutMessage outMessage = wxMpMessageRouter.route(inMessage);
- if (outMessage != null) {
- if ("raw".equals(encryptType)) {
- response.getWriter().write(outMessage.toXml());
- } else if ("aes".equals(encryptType)) {
- response.getWriter().write(
- outMessage.toEncryptedXml(wxMpConfigStorage));
- }
- return;
- }
- }
-
- /**
- * 关注自动回复路由规则
- *
- */
- private void addEvtRouterRule(){
- WxMpMessageHandler handler = new WxMpMessageHandler() {
- @Override
- public WxMpXmlOutMessage handle(WxMpXmlMessage wxMessage,
- Map<String, Object> context, WxMpService wxMpService,
- WxSessionManager sessionManager) throws WxErrorException {
- String strOut = "欢迎你的关注";
- WxMpXmlOutTextMessage m = WxMpXmlOutMessage.TEXT()
- .content(strOut).fromUser(wxMessage.getToUser())
- .toUser(wxMessage.getFromUser()).build();
- return m;
- }
- };
- wxMpMessageRouter.rule().async(false).msgType(WxConsts.XmlMsgType.EVENT).event(WxConsts.EventType.SUBSCRIBE).handler(handler).end();
- }}
4、WxMpXMLInMemoryConfigStorage
- class WxMpXMLInMemoryConfigStorage extends WxMpInMemoryConfigStorage {
-
-
-
- // 将微信配置文件 /weixin.config.xml 解析为 WxMpXMLInMemoryConfigStorage对象返回
- public static WxMpXMLInMemoryConfigStorage fromXml(InputStream is) throws JAXBException {
-
- //微信配置参数
- WxMpXMLInMemoryConfigStorage cfg = new WxMpXMLInMemoryConfigStorage();
- cfg.setAppId("appid");
- cfg.setSecret("随机数");
- cfg.setToken("token");
- // cfg.setAesKey("密钥,测试号不用填写");
-
- return cfg;
- }
- }
5、运行项目,配置测试号中的url,token
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。