1. 程式人生 > >微信公眾號開發系列三:響應關注和取關事件

微信公眾號開發系列三:響應關注和取關事件

一、實際需求      

       當我們關注某些微信公眾號的時候,有的公眾號會給我們回覆一條文字資訊。本節內容,我們就來實現如何在使用者關注公眾號後,由公眾號給使用者回覆一條文字資訊。同樣在使用者取消關注時,也可以給使用者傳送一條資訊。

二、開發文件


      由此可知,我們的公眾號服務接收到微信伺服器回傳的xml資訊,從中獲取MsgType和Event的值,可以區分出使用者的關注和取消關注的行為,對不同的行為程式可以做出不同的響應。

三、編碼實現

1、引入相關jar包:dom4j-1.6.1.jar、servlet-api-2.5.jar、xstream-1.3.1.jar用來處理xml檔案。

2、根據開發文件中的xml內容,建立訊息物件基礎類BaseMessage:

/*
 * 訊息體基礎類
 */
public class BaseMessage {
	private String ToUserName;
	private String FromUserName;
	private long CreateTime;
	private String MsgType;
	public String getToUserName() {
		return ToUserName;
	}
	public void setToUserName(String toUserName) {
		ToUserName = toUserName;
	}
	public String getFromUserName() {
		return FromUserName;
	}
	public void setFromUserName(String fromUserName) {
		FromUserName = fromUserName;
	}
	public long getCreateTime() {
		return CreateTime;
	}
	public void setCreateTime(long createTime) {
		CreateTime = createTime;
	}
	public String getMsgType() {
		return MsgType;
	}
	public void setMsgType(String msgType) {
		MsgType = msgType;
	}
}
3、建立文字訊息類TextMessage繼承訊息基礎類:
/*
 * 文字訊息類
 */
public class TextMessage extends BaseMessage{
	private String Content;
	private String MsgId;	
	public String getContent() {
		return Content;
	}
	public void setContent(String content) {
		Content = content;
	}
	public String getMsgId() {
		return MsgId;
	}
	public void setMsgId(String msgId) {
		MsgId = msgId;
	}
	
}
4、建立處理xml的工具類XmlUtil:
/*
 * xml處理工具類
 */
public class XmlUtil {
	/*
	 * xml轉map
	 */
	public static Map<String, String> xmlToMap(HttpServletRequest request) throws IOException, DocumentException{
		HashMap<String, String> map = new HashMap<String,String>();
		SAXReader reader = new SAXReader();

		InputStream ins = request.getInputStream();
		Document doc = reader.read(ins);

		Element root = doc.getRootElement();
		@SuppressWarnings("unchecked")
		List<Element> list = (List<Element>)root.elements();

		for(Element e:list){
			map.put(e.getName(), e.getText());
		}
		ins.close();
		return map;
	}
	/*
	 * 文字訊息物件轉xml
	 */
	public static String textMsgToxml(TextMessage textMessage){
		XStream xstream = new XStream();
		xstream.alias("xml", textMessage.getClass());
		return xstream.toXML(textMessage);
	}
}
5、建立訊息處理類MessageUtil:
/*
 * 訊息處理工具類
 */
public class MessageUtil {
	public static final String MSGTYPE_EVENT = "event";//訊息型別--事件
	public static final String MESSAGE_SUBSCIBE = "subscribe";//訊息事件型別--訂閱事件
	public static final String MESSAGE_UNSUBSCIBE = "unsubscribe";//訊息事件型別--取消訂閱事件
	public static final String MESSAGE_TEXT = "text";//訊息型別--文字訊息
	
	/*
	 * 組裝文字訊息
	 */
	public static String textMsg(String toUserName,String fromUserName,String content){
		TextMessage text = new TextMessage();
		text.setFromUserName(toUserName);
		text.setToUserName(fromUserName);
		text.setMsgType(MESSAGE_TEXT);
		text.setCreateTime(new Date().getTime());
		text.setContent(content);
		return XmlUtil.textMsgToxml(text);
	}
	
	/*
	 * 響應訂閱事件--回覆文字訊息
	 */
	public static String subscribeForText(String toUserName,String fromUserName){
		return textMsg(toUserName, fromUserName, "歡迎關注,精彩內容不容錯過!!!");
	}
	
	/*
	 * 響應取消訂閱事件
	 */
	public static String unsubscribe(String toUserName,String fromUserName){
		//TODO 可以進行取關後的其他後續業務處理
		System.out.println("使用者:"+ fromUserName +"取消關注~");
		return "";
	}
}
6、在WeixinServlet類中新增doPost方法,用來響應微信使用者發來的操作請求:
        /*
	 * 響應post請求,微信中訊息和選單互動都是採用post請求
	 */
	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws IOException{
		req.setCharacterEncoding("UTF-8");
		resp.setCharacterEncoding("UTF-8");
		PrintWriter out = resp.getWriter();
		String message = "success";
		try {
			//把微信返回的xml資訊轉義成map
			Map<String, String> map = XmlUtil.xmlToMap(req);
			String fromUserName = map.get("FromUserName");//訊息來源使用者標識
			String toUserName = map.get("ToUserName");//訊息目的使用者標識
			String msgType = map.get("MsgType");//訊息型別
			String content = map.get("Content");//訊息內容
			
			String eventType = map.get("Event");
			if(MessageUtil.MSGTYPE_EVENT.equals(msgType)){//如果為事件型別
				if(MessageUtil.MESSAGE_SUBSCIBE.equals(eventType)){//處理訂閱事件
					message = MessageUtil.subscribeForText(toUserName, fromUserName);
				}else if(MessageUtil.MESSAGE_UNSUBSCIBE.equals(eventType)){//處理取消訂閱事件
					message = MessageUtil.unsubscribe(toUserName, fromUserName);
				}
			}
		} catch (DocumentException e) {
			e.printStackTrace();
		}finally{
			out.println(message);
			if(out!=null){
				out.close();
			}
		}
	}

7、程式碼結構圖:


四、本節小結

       通過以上操作,我們在新增加一個功能的時候,首先要檢視官方開發文件,依據其xml互動格式來封裝自己的類和方法,在此基礎上增加業務邏輯來實現符合自己的需求實現。

五、相關連結

更多學習討論, 請加入

官方爬蟲、nlp技術qq群:320349384 

天亮教育官方群:318971238,

hadoop & spark & hive技術群:297585251, 

官網:myhope365.com

歡迎關注天亮教育公眾號: