微信公衆平臺開發學習記錄(3)————接收消息和發送回覆消息

當普通微信用戶向公衆賬號發消息時,微信服務器將POST消息的XML數據包到開發者填寫的URL上。

當用戶發送消息給公衆號時(或某些特定的用戶操作引發的事件推送時),會產生一個POST請求,開發者可以在響應包(Get)中返回特定XML結構,來對該消息進行響應(現支持回覆文本、圖片、圖文、語音、視頻、音樂)。嚴格來說,發送被動響應消息其實並不是一種接口,而是對微信服務器發過來消息的一次回覆。回覆消息是根據接收的xml中獲取到用戶信息,根據各類型消息XML結構示例進行拼接。

代碼:

package com.qs.action;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.Date;

import javax.servlet.ServletInputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.struts2.interceptor.ServletRequestAware;
import org.apache.struts2.interceptor.ServletResponseAware;

import com.opensymphony.xwork2.ActionSupport;
import com.qs.util.SignUtil;

/**
 * @author qiaoshuai
 * @createDate 2016-3-1
 */
public class TestWeiXinAction extends ActionSupport implements
		ServletRequestAware, ServletResponseAware {

	private static final long serialVersionUID = -799327593656049028L;
	protected HttpServletRequest request;
	private HttpServletResponse response;

	public void setServletResponse(HttpServletResponse response) {
		this.response = response;
	}

	public void setServletRequest(HttpServletRequest request) {
		this.request = request;
	}

	public void checkSignature() throws IOException {
		boolean isGet = request.getMethod().toLowerCase().equals("get");
		if (isGet) {
			// 微信加密簽名
			String signature = request.getParameter("signature");
			System.out.println("signature=" + signature);
			// 時間戳
			String timestamp = request.getParameter("timestamp");
			System.out.println("timestamp=" + timestamp);
			// 隨機數
			String nonce = request.getParameter("nonce");
			System.out.println("nonce=" + nonce);
			// 隨機字符串
			String echostr = request.getParameter("echostr");
			System.out.println("echostr=" + echostr);
			PrintWriter out = response.getWriter();
			// 通過檢驗signature對請求進行校驗,若校驗成功則原樣返回echostr,表示接入成功,否則接入失敗
			if (SignUtil.checkSignature(signature, timestamp, nonce)) {
				out.print(echostr);
			}
			out.close();
			out = null;
		} else {
			// POST
			responseMsg();
		}

	}
	
	public void responseMsg() throws  IOException{
		String outString = "";
		String replyString = "";
		BufferedReader br = new BufferedReader(new InputStreamReader(
				(ServletInputStream) request.getInputStream(), "utf-8"));
		String line = null;
		StringBuilder sb = new StringBuilder();
		while ((line = br.readLine()) != null) {
			sb.append(line);
		}
		String xmlS = sb.toString();
		System.out.println(xmlS);

		if (xmlS != null && !xmlS.equals("")) {
			// 用戶發送者
			int fromuser_s = xmlS.indexOf("<FromUserName><![CDATA[");
			int fromuser_e = xmlS.indexOf("]]></FromUserName>");
			String fromuser = xmlS.substring(fromuser_s + 23, fromuser_e);
			System.out.println("fromuser:" + fromuser);

			// 取出目標用戶
			int touser_s = xmlS.indexOf("<ToUserName><![CDATA[");
			int touser_e = xmlS.indexOf("]]></ToUserName>");
			String touser = xmlS.substring(touser_s + 21, touser_e);
			System.out.println("touser:" + touser);

			// 獲取請求類型
			int msgType_s = xmlS.indexOf("<MsgType><![CDATA[");
			int msgType_e = xmlS.indexOf("]]></MsgType>");
			String msgType = xmlS.substring(msgType_s + 18, msgType_e);
			System.out.println("msgType:" + msgType);

			// 獲取請求當前時間
			int createTime_s = xmlS.indexOf("<CreateTime>");
			int createTime_e = xmlS.indexOf("</CreateTime>");
			String createTime = xmlS.substring(createTime_s + 12, createTime_e);
			int createTimeInt = Integer.parseInt(createTime);
			System.out.println("createTime:" + createTimeInt);
			
			// 接收點擊推事件消息
			if ("event".equals(msgType)) {
				StringBuilder outBuilder = new StringBuilder();
				int EventKey_s = xmlS.indexOf("<EventKey><![CDATA[");
				int EventKey_e = xmlS.indexOf("]]></EventKey>");
				String eventKey = xmlS.substring(EventKey_s + 19, EventKey_e);
				System.out.println("EventKey:" + eventKey);
				if (eventKey.equals("V1001_TODAY_MUSIC")) { //

					outBuilder.append("《燕歸巢》");
					outString = textDemo(outBuilder.toString());
				}else if(eventKey.equals("V1001_GOOD")){
					outBuilder.append("謝謝您的贊!");
					outString = textDemo(outBuilder.toString());
				}
			}

			// 接收文本消息
			if ("text".equals(msgType)) {
				StringBuilder outBuilder = new StringBuilder();
				int content_s = xmlS.indexOf("<Content><![CDATA[");
				int content_e = xmlS.indexOf("]]></Content>");
				String content = xmlS.substring(content_s + 18, content_e);
				System.out.println("content:" + content);
				if (content.equals("天氣")) { // 幫助回覆(文本回復)

					outBuilder.append("今天是晴天");
					outString = textDemo(outBuilder.toString());
				}else{
					outBuilder.append(content + "啊哈");
					outString = textDemo(outBuilder.toString());
				}
				
			}

			//
			replyString = this.replyDemo(fromuser, touser, outString);
		}
		System.out.println("replyString:" + replyString);
		this.print(replyString);

	}


	// 向請求端發送返回數據
	public void print(String content) {
		try {
			response.setContentType("text/html;charset=utf-8");
			response.getWriter().print(content);
			response.getWriter().flush();
			response.getWriter().close();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	public String replyDemo(String fromuser, String touser, String content) {
		StringBuilder outString = new StringBuilder();
		// 表頭
		outString.append("<xml>");
		outString.append("    <ToUserName><![CDATA[" + fromuser
				+ "]]></ToUserName>");
		outString.append("    <FromUserName><![CDATA[" + touser
				+ "]]></FromUserName>");
		outString.append("    <CreateTime>" + new Date().getTime()
				+ "</CreateTime>");
		// 表中
		outString.append(content);
		// 表尾
		outString.append("    <FuncFlag>0</FuncFlag>");
		outString.append("</xml>");
		return outString.toString();
	}


	/**
	 *文本回復 Demo
	 * 
	 * @param content
	 *            字符串內容
	 **/
	public String textDemo(String content) {
		StringBuilder textString = new StringBuilder();
		textString.append("<MsgType><![CDATA[text]]></MsgType>");
		textString.append("<Content><![CDATA[").append(content).append(
				"]]></Content>");
		return textString.toString();
	}

	/**
	 *圖文回覆 Demo
	 * 
	 * @param title
	 *            標題
	 * @param description
	 *            簡介內容
	 * @param picUrl
	 *            圖片路徑
	 * @param skipUrl
	 *            鏈接路徑
	 * 
	 **/
	public String textPicDemo(String title, String description, String picUrl,
			String skipUrl) {
		StringBuilder textPicString = new StringBuilder();
		textPicString.append("  <MsgType><![CDATA[news]]></MsgType>");
		textPicString.append("  <ArticleCount>1</ArticleCount>");
		textPicString.append("  <Articles>");
		textPicString.append("    <item>");
		textPicString.append("      <Title><![CDATA[" + title + "]]></Title> ");
		if (description != null) {
			textPicString.append("      <Description><![CDATA[" + description
					+ "]]></Description>");
		}
		textPicString
				.append("	    <PicUrl><![CDATA[" + picUrl + "]]></PicUrl>");
		textPicString.append("      <Url><![CDATA[" + skipUrl + "]]></Url>");
		textPicString.append("    </item>");
		textPicString.append("  </Articles>");
		return textPicString.toString();
	}

	/**
	 * 多張圖文回覆 Demo
	 * 
	 * @param articleCount
	 *            圖文數量
	 * @param content
	 *            圖文內容
	 **/
	public String textPicListDemosun(String[] titles, String[] descriptions,
			String[] picUrls, String[] skipUrls) {
		StringBuilder textPicString = new StringBuilder();
		textPicString.append("  <MsgType><![CDATA[news]]></MsgType>");
		textPicString.append("  <ArticleCount>" + 1 + "</ArticleCount>");
		textPicString.append("  <Articles>");
		textPicString.append("    <item>");
		textPicString.append("      <Title><![CDATA[" + titles[0]
				+ "]]></Title> ");
		if (descriptions != null) {
			textPicString.append("      <Description><![CDATA["
					+ descriptions[0] + "]]></Description>");
		}
		textPicString.append("	    <PicUrl><![CDATA[" + picUrls[0]
				+ "]]></PicUrl>");
		textPicString
				.append("      <Url><![CDATA[" + skipUrls[0] + "]]></Url>");
		textPicString.append("    </item>");
		textPicString.append("  </Articles>");
		return textPicString.toString();
	}

	/**
	 * 多張圖文回覆 Demo
	 * 
	 * @param articleCount
	 *            圖文數量
	 * @param content
	 *            圖文內容
	 **/
	public String textPicListDemo(int articleCount, String content) {
		StringBuilder textPicString = new StringBuilder();
		textPicString.append("  <MsgType><![CDATA[news]]></MsgType>");
		textPicString.append("  <ArticleCount>" + articleCount
				+ "</ArticleCount>");
		textPicString.append("  <Articles>");
		textPicString.append(content);
		textPicString.append("  </Articles>");
		return textPicString.toString();
	}


}

效果:





發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章