1. 程式人生 > >微信訊息接收以及被動回覆

微信訊息接收以及被動回覆

微信有很多訊息時間,如:文字、圖片、語音、事件等訊息,微信伺服器將POST訊息的XML資料包到開發者填寫的URL上。即與你微信驗證token的介面一樣,不過是post請求,此處只演示訊息的接收,以及文字訊息的被動回覆。

需要額外引用的maven依賴:

<!--xml解析-->
<dependency>
	<groupId>org.dom4j</groupId>
	<artifactId>dom4j</artifactId>
	<version>2.1.0</version>
</dependency>

定義返回訊息POJO類:

public class TextMsgDTO{

    public String ToUserName;

    public String FromUserName;

    public String CreateTime;

    public String MsgType;
    
    public String Content;

    public String msgToXml(){
        XStream xstream=new XStream();
        xstream.alias("xml", this.getClass());
        return xstream.toXML(this);
    }
}

定義xml解析工具類:

public class XMLUtil {
    public static Document readXML(String str){
        Document document=null;
        try {
            document= DocumentHelper.parseText(str);
        } catch (DocumentException e) {
            e.printStackTrace();
        }
        return document;
    }

    /**
     * 讀取節點資訊
     * @param node
     * @param name
     * @return
     */
    public static String readNode(Element node,String name){
        return node.element(name).getTextTrim();
    }
}

定義訊息接收介面以及訊息的處理:

@RestController
@RequestMapping("/wx")
public class WXController {
    @Autowired
    WXService wxService;

    @PostMapping("")
    public Object receiveMessage(@RequestBody String xml){
        return wxService.TXMessage(xml);
    }
public interface WXService {
    Object TXMessage(String xml);
}
@Service
public class WXServiceImpl implements WXService  {
	private Logger logger = LoggerFactory.getLogger(WXServiceImpl.class);

	/**
	 * 接收微信訊息回撥並返回
	 * @param xml
	 * @return
	 */
	@Override
	public Object TXMessage(String xml) {

		/**將資訊轉換為Document*/
		Document document = XMLUtil.readXML(xml);
		Element root = document.getRootElement();
		logger.info("receive:"+xml);
		String replyContent;

		String toUserName = XMLUtil.readNode(root, "ToUserName");
		String fromUserName = XMLUtil.readNode(root, "FromUserName");
		String msgType = XMLUtil.readNode(root, "MsgType");

		if("text".equals(msgType)){
			replyContent = XMLUtil.readNode(root, "Content");
		}else{
			replyContent = "你傳送的訊息型別為:"+msgType;
		}
		
		String replyMsg = packageReplyTextMsg(fromUserName,toUserName,replyContent);
		logger.info("reply:"+replyMsg);
		return replyMsg;
	}
	
	/**封裝返回訊息*/
	private String packageReplyTextMsg(String fromUserName, String toUserName,  String replyContent){
		TextMsgDTO textMsg = new TextMsgDTO();
		textMsg.MsgType = "text";
		textMsg.FromUserName = toUserName;
		textMsg.ToUserName = fromUserName;
		textMsg.CreateTime = String.valueOf(System.currentTimeMillis()).substring(0,10);
		//將XML訊息的引數都轉化內容回覆給微信
		textMsg.Content = replyContent;
		
		String replyMsg = null;
		try {
			//將物件轉化為XML
			replyMsg = textMsg.msgToXml();
		} catch (Exception e) {
			e.printStackTrace();
		}
		return replyMsg;
	}
}