微信回传事件的xml报文解析

一.微信回传报文格式


  
  
  1566264938
  
  
  
  0
  
  
  0
  
  
  0
  0
  
  

二.解析pom依赖(核心部分)

2.9.8


    com.fasterxml.jackson.dataformat
    jackson-dataformat-xml
    ${jackson.version}

三.完整解析代码

import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.dataformat.xml.XmlMapper;
import com.google.common.base.Strings;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.ws.rs.QueryParam;
import javax.ws.rs.core.MediaType;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;

import com.fasterxml.jackson.dataformat.xml.annotation.JacksonXmlProperty;
import com.fasterxml.jackson.dataformat.xml.annotation.JacksonXmlRootElement;
import lombok.Data;
import lombok.ToString;

/**
 * 服务实现:接收微信后台处理结果
 *
 * @author 
 * @date 
 */
@RestController
public class WxController {

    private static final Logger logger = LoggerFactory.getLogger(WxController.class);

    @RequestMapping(value = "", method = RequestMethod.POST, produces = MediaType.TEXT_XML)
    public String rcvProcess(@RequestBody String receiveMsg) {
        logger.info("接收到微信的通知报文,receiveMsg=[{}]", receiveMsg);

        XmlMapper xmlMapper = new XmlMapper();
        xmlMapper.setDefaultUseWrapper(false);

        //自动忽略无法对应pojo的字段
        xmlMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);

        try {

            // 获取微信异步通知结果
            WxReceiveResponseBody xml = xmlMapper.readValue(receiveMsg, WxReceiveResponseBody.class);
            String event = xml.getEvent();
            logger.info("Event=[{}]", event);

            if ("user_get_card".equals(event)) {
                // todo: 处理user_get_card时间对应的业务逻辑
            }

        } catch (IOException ie) {
            logger.info("报文解析错误=[{}]", ie.toString());
        }

        return null;
    }
    
    @Data
    @ToString
    @JacksonXmlRootElement(localName = "xml")
    public static class WxReceiveResponseBody {
        @JacksonXmlProperty(localName = "Event")
        private String event;
    }
}

你可能感兴趣的:(微信开发的一些东东)