Java企業微信開發_05_消息推送之被動回覆消息

1、本節要點

1.消息的加解密

微信加解密包 下載地址http://qydev.weixin.qq.com/java.zip      ,此包中封裝好了AES加解密方法,直接調用方法便可。html

其中,解密方法爲:java

            //2.獲取消息明文:對加密的請求消息進行解密得到明文  
            WXBizMsgCrypt wxcpt=new WXBizMsgCrypt(WeiXinParamesUtil.token,WeiXinParamesUtil.encodingAESKey,WeiXinParamesUtil.corpId);
            result = wxcpt.DecryptMsg(msg_signature, timestamp, nonce, postData);

 

加密方法爲:web

            //6.加密
            WXBizMsgCrypt wxcpt=new WXBizMsgCrypt(WeiXinParamesUtil.token,WeiXinParamesUtil.encodingAESKey,WeiXinParamesUtil.corpId);
            respMessage = wxcpt.EncryptMsg(respMessage, timestamp, msgType);
            

 

2.被動回覆消息的流程

用戶發送消息以後,微信服務器將消息傳遞給 第三方服務器,第三方服務器接收到消息後,再對消息作出相應的回覆消息。服務器

接收消息:需先從request請求對象的輸入流中獲取請求參數和已加密的請求消息,再對已加密的請求消息進行解密操做,便可得到明文。微信

                  而後就行對明文消息的業務處理了。微信開發

回覆消息:封裝好回覆消息後,需先對回覆消息進行加密,得到已已加密消息,而後再經過http請求調用被動回覆消息的接口,來發送消息。app

 

 

2、接收消息服務器配置

見  Java企業微信開發_02_接收消息服務器配置dom

 

接受消息服務器配置好後,用戶發送消息時,微信服務器會將消息轉發到配置的接受消息服務器url上,即以POST方式轉發到 CoreServlet 上。jsp

 

3、接收消息實體類的封裝(req)

參見官方文檔的說明ide

3.1 消息基類——BaseMessage

package com.ray.pojo.message.req;  
  
/**
 * 消息基類(普通用戶 -> 企業微信) 
 * @author shirayner
 *
 */
public class BaseMessage {  
    // 開發者微信號  
    private String ToUserName;  
    // 發送方賬號(一個OpenID)  
    private String FromUserName;  
    // 消息建立時間 (整型)  
    private long CreateTime;  
    // 消息類型(text/image/location/link)  
    private String MsgType;  
    // 消息id,64位整型  
    private long MsgId;  
    //企業應用的id,整型。可在應用的設置頁面查看
    private int AgentID;
  
    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;  
    }  
  
    public long getMsgId() {  
        return MsgId;  
    }  
  
    public void setMsgId(long msgId) {  
        MsgId = msgId;  
    }

    public int getAgentID() {
        return AgentID;
    }

    public void setAgentID(int agentID) {
        AgentID = agentID;
    }

    
    
}  
View Code

 

3.2 文本消息——TextMessage

package com.ray.pojo.message.req;  
  
/**
 * 文本消息
 * @author shirayner
 *
 */
public class TextMessage extends BaseMessage {  
    // 消息內容  
    private String Content;  
  
    public String getContent() {  
        return Content;  
    }  
  
    public void setContent(String content) {  
        Content = content;  
    }  
}  
View Code

 

3.3圖片消息——ImageMessage

package com.ray.pojo.message.req;  

/**
 *  圖片消息 
 * @author shirayner
 *
 */
public class ImageMessage extends BaseMessage {  
    // 圖片連接  
    private String PicUrl;  
    // 圖片媒體文件id,能夠調用獲取媒體文件接口拉取
    private String MediaId;  

    public String getPicUrl() {  
        return PicUrl;  
    }  

    public void setPicUrl(String picUrl) {  
        PicUrl = picUrl;  
    }

    public String getMediaId() {
        return MediaId;
    }

    public void setMediaId(String mediaId) {
        MediaId = mediaId;
    }  

}  
View Code

 

3.4 語音消息——VoiceMessage

package com.ray.pojo.message.req;  
  
/**
 * 語音消息 
 * @author shirayner
 *
 */
public class VoiceMessage extends BaseMessage {  
    // 語音媒體文件id,能夠調用獲取媒體文件接口拉取數據 
    private String MediaId;  
    // 語音格式,如amr,speex等
    private String Format;  
  
    public String getMediaId() {  
        return MediaId;  
    }  
  
    public void setMediaId(String mediaId) {  
        MediaId = mediaId;  
    }  
  
    public String getFormat() {  
        return Format;  
    }  
  
    public void setFormat(String format) {  
        Format = format;  
    }  
}  
View Code

 

3.5 視頻消息——Video、VideoMessage

Video.java

package com.ray.pojo.message.resp;

/**
 * @desc  : 視頻
 * 
 * @author: shirayner
 * @date  : 2017-8-17 下午2:00:22
 */
public class Video {

    //視頻文件id,能夠調用獲取媒體文件接口拉取
    private String MediaId;
    //視頻消息的標題
    private String Title;
    //視頻消息的描述
    private String Description;
    public String getMediaId() {
        return MediaId;
    }
    public void setMediaId(String mediaId) {
        MediaId = mediaId;
    }
    public String getTitle() {
        return Title;
    }
    public void setTitle(String title) {
        Title = title;
    }
    public String getDescription() {
        return Description;
    }
    public void setDescription(String description) {
        Description = description;
    }
   
    
}
View Code

VideoMessage.java

package com.ray.pojo.message.resp;

/**
 * @desc  : 視頻消息
 * 
 * @author: shirayner
 * @date  : 2017-8-21 上午10:36:33
 */
public class VideoMessage extends BaseMessage {
    // 視頻
    private Video Video;

    public Video getVideo() {
        return Video;
    }

    public void setVideo(Video video) {
        Video = video;
    }
}
View Code

 

3.6 位置消息——LocationMessage

package com.ray.pojo.message.req;  
  
/**
 * 位置消息 
 * @author shirayner
 *
 */
public class LocationMessage extends BaseMessage {  
    // 地理位置維度  
    private String Location_X;  
    // 地理位置經度  
    private String Location_Y;  
    // 地圖縮放大小  
    private String Scale;  
    // 地理位置信息  
    private String Label;  
    

  
    public String getLocation_X() {  
        return Location_X;  
    }  
  
    public void setLocation_X(String location_X) {  
        Location_X = location_X;  
    }  
  
    public String getLocation_Y() {  
        return Location_Y;  
    }  
  
    public void setLocation_Y(String location_Y) {  
        Location_Y = location_Y;  
    }  
  
    public String getScale() {  
        return Scale;  
    }  
  
    public void setScale(String scale) {  
        Scale = scale;  
    }  
  
    public String getLabel() {  
        return Label;  
    }  
  
    public void setLabel(String label) {  
        Label = label;  
    }  
}  
View Code

 

3.7 連接消息——LinkMessage

package com.ray.pojo.message.req;  

/**
 * 連接消息 
 * @author shirayner
 *
 */
public class LinkMessage extends BaseMessage {  
    // 消息標題  
    private String Title;  
    // 消息描述  
    private String Description;  
    // 封面縮略圖的url
    private String PicUrl;  

    public String getTitle() {  
        return Title;  
    }  

    public void setTitle(String title) {  
        Title = title;  
    }  

    public String getDescription() {  
        return Description;  
    }  

    public void setDescription(String description) {  
        Description = description;  
    }

    public String getPicUrl() {
        return PicUrl;
    }

    public void setPicUrl(String picUrl) {
        PicUrl = picUrl;
    }  


}  
View Code

 

4、被動回覆消息的封裝(resp)

4.1 消息基類——BaseMessage

package com.ray.pojo.message.resp;

/**
 * 消息基類(企業微信 -> 普通用戶)
 * @author shirayner
 *
 */
public class BaseMessage {
    // 成員UserID
    private String ToUserName;
    // 企業微信CorpID
    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;
    }
}
View Code

 

4.2 文本消息——TextMessage

package com.ray.pojo.message.resp;

/**
 * 文本消息
 * @author shirayner
 *
 */
public class TextMessage extends BaseMessage {
    // 回覆的消息內容
    private String Content;

    public String getContent() {
        return Content;
    }

    public void setContent(String content) {
        Content = content;
    }
}
View Code

 

4.3 圖片類、語音類——Media

package com.ray.pojo.message.resp;

/**
 * @desc  : 圖片、語音
 * 
 * @author: shirayner
 * @date  : 2017-8-17 下午1:52:19
 */
public class Media {
    
    private String MediaId;

    public String getMediaId() {
        return MediaId;
    }

    public void setMediaId(String mediaId) {
        MediaId = mediaId;
    }
}
View Code

 

4.3.1 圖片消息——ImageMessage

package com.ray.pojo.message.resp;

/**
 * @desc  : 圖片消息
 * 
 * @author: shirayner
 * @date  : 2017-8-17 下午1:53:28
 */
public class ImageMessage extends BaseMessage {
    
    private Media Image;

    public Media getImage() {
        return Image;
    }

    public void setImage(Media image) {
        Image = image;
    }
}
View Code

 

4.3.2 語音消息——VoiceMessage

package com.ray.pojo.message.resp;

/**
 * @desc  : 語音消息
 * 
 * @author: shirayner
 * @date  : 2017-8-17 下午1:57:42
 */
public class VoiceMessage extends BaseMessage {
    // 語音
    private Media Voice;

    public Media getVoice() {
        return Voice;
    }

    public void setVoice(Media voice) {
        Voice = voice;
    }

   
}
View Code

 

4.4 視頻消息——VoiceMessage

package com.ray.pojo.message.resp;

/**
 * @desc  : 語音消息
 * 
 * @author: shirayner
 * @date  : 2017-8-17 下午1:57:42
 */
public class VoiceMessage extends BaseMessage {
    // 語音
    private Media Voice;

    public Media getVoice() {
        return Voice;
    }

    public void setVoice(Media voice) {
        Voice = voice;
    }

   
}
View Code

 

4.5 圖文消息——Article、NewsMessage

Article.java

package com.ray.pojo.message.resp;

/**
 * @desc  : 圖文
 * 
 * @author: shirayner
 * @date  : 2017-8-17 下午2:02:33
 */
public class Article {
    // 圖文消息名稱
    private String Title;
    // 圖文消息描述
    private String Description;
    // 圖片連接,支持JPG、PNG格式,較好的效果爲大圖640*320,小圖80*80
    private String PicUrl;
    // 點擊圖文消息跳轉連接
    private String Url;

    public String getTitle() {
        return Title;
    }

    public void setTitle(String title) {
        Title = title;
    }

    public String getDescription() {
        return null == Description ? "" : Description;
    }

    public void setDescription(String description) {
        Description = description;
    }

    public String getPicUrl() {
        return null == PicUrl ? "" : PicUrl;
    }

    public void setPicUrl(String picUrl) {
        PicUrl = picUrl;
    }

    public String getUrl() {
        return null == Url ? "" : Url;
    }

    public void setUrl(String url) {
        Url = url;
    }
}
View Code

NewsMessage.java

package com.ray.pojo.message.resp;

import java.util.List;

/**
 * @desc  : 圖文消息
 * 
 * @author: shirayner
 * @date  : 2017-8-17 下午2:03:31
 */
public class NewsMessage extends BaseMessage {
    // 圖文消息個數,限制爲10條之內
    private int ArticleCount;
    // 多條圖文消息信息,默認第一個item爲大圖
    private List<Article> Articles;

    public int getArticleCount() {
        return ArticleCount;
    }

    public void setArticleCount(int articleCount) {
        ArticleCount = articleCount;
    }

    public List<Article> getArticles() {
        return Articles;
    }

    public void setArticles(List<Article> articles) {
        Articles = articles;
    }
}
View Code

 

5、消息工具類——MessageUtil

package com.ray.util;  
  
import java.io.InputStream;  
import java.io.Writer;  
import java.util.HashMap;  
import java.util.List;  
import java.util.Map;  
  
  
import org.dom4j.Document;  
import org.dom4j.DocumentHelper;
import org.dom4j.Element;  
import org.dom4j.io.SAXReader;  

import com.ray.pojo.message.resp.Article;
import com.ray.pojo.message.resp.NewsMessage;
import com.ray.pojo.message.resp.TextMessage;
import com.thoughtworks.xstream.XStream;  
import com.thoughtworks.xstream.core.util.QuickWriter;  
import com.thoughtworks.xstream.io.HierarchicalStreamWriter;  
import com.thoughtworks.xstream.io.xml.PrettyPrintWriter;  
import com.thoughtworks.xstream.io.xml.XppDriver;  
  
/**
 * 消息工具類 
 * @author shirayner
 *
 */
public class MessageUtil {  
    
    //返回消息類型:文本 
    public static final String RESP_MESSAGE_TYPE_TEXT = "text";  
    //返回消息類型:音樂 
    public static final String RESP_MESSAGE_TYPE_MUSIC = "music";  
    //返回消息類型:圖文 
    public static final String RESP_MESSAGE_TYPE_NEWS = "news";
    
    //請求消息類型:文本  
    public static final String REQ_MESSAGE_TYPE_TEXT = "text";  
    //請求消息類型:圖片 
    public static final String REQ_MESSAGE_TYPE_IMAGE = "image";  
    //請求消息類型:連接 
    public static final String REQ_MESSAGE_TYPE_LINK = "link";  
    //請求消息類型:地理位置 
    public static final String REQ_MESSAGE_TYPE_LOCATION = "location";  
    //請求消息類型:音頻 
    public static final String REQ_MESSAGE_TYPE_VOICE = "voice";  
    //請求消息類型:推送  
    public static final String REQ_MESSAGE_TYPE_EVENT = "event";  
    
    //事件類型:subscribe(訂閱) 
    public static final String EVENT_TYPE_SUBSCRIBE = "subscribe";  
    //事件類型:unsubscribe(取消訂閱) 
    public static final String EVENT_TYPE_UNSUBSCRIBE = "unsubscribe";  
    //事件類型:CLICK(自定義菜單點擊事件)  
    public static final String EVENT_TYPE_CLICK = "click";  
  
    /**
     * @desc :1.解析微信發來的請求(XML),獲取請求參數 
     *  
     * @param request
     * @return
     * @throws Exception Map<String,String>
     */
    public static Map<String, String> parseXml(HttpServletRequest request) throws Exception {  
        // 將解析結果存儲在HashMap中  
        Map<String, String> map = new HashMap<String, String>();  
  
        // 從request中取得輸入流  
        InputStream inputStream = request.getInputStream();  
        // 讀取輸入流  
        SAXReader reader = new SAXReader();  
        Document document = reader.read(inputStream);  
        // 獲得xml根元素  
        Element root = document.getRootElement();  
        // 獲得根元素的全部子節點  
        List<Element> elementList = root.elements();  
  
        // 遍歷全部子節點  
        for (Element e : elementList)  
            map.put(e.getName(), e.getText());  
  
        // 釋放資源  
        inputStream.close();  
        inputStream = null;  
  
        return map;  
    } 
    
    /**
     * @desc :2.解析微信發來的請求(xmlStr),獲取請求參數 
     *  
     * @param xmlStr
     * @return
     * @throws Exception Map<String,String>
     */
    public static Map<String, String> parseXml(String xmlStr) throws Exception {  
        // 將解析結果存儲在HashMap中  
        Map<String, String> map = new HashMap<String, String>();  
  

        //1.將字符串轉爲Document
        Document document = DocumentHelper.parseText(xmlStr);
        
        //2.獲取根元素的全部子節點
        // 獲得xml根元素  
        Element root = document.getRootElement();  
        // 獲得根元素的全部子節點  
        List<Element> elementList = root.elements();  
  
        //3.遍歷全部子節點 
        for (Element e : elementList)  
            map.put(e.getName(), e.getText());  
        
        return map;  
    }  
  
    /** 
     * 2.文本消息對象轉換成xml 
     *  
     * @param textMessage 文本消息對象 
     * @return xml 
     */  
    public static String textMessageToXml(TextMessage textMessage) {  
        xstream.alias("xml", textMessage.getClass());  
        return xstream.toXML(textMessage);  
    }  
  
    /** 
     * 音樂消息對象轉換成xml 
     *  
     * @param musicMessage 音樂消息對象 
     * @return xml 
     */  
  /*  public static String musicMessageToXml(MusicMessage musicMessage) {  
        xstream.alias("xml", musicMessage.getClass());  
        return xstream.toXML(musicMessage);  
    }  
  */
    /** 
     * 圖文消息對象轉換成xml 
     *  
     * @param newsMessage 圖文消息對象 
     * @return xml 
     */  
    public static String newsMessageToXml(NewsMessage newsMessage) {  
        xstream.alias("xml", newsMessage.getClass());  
        xstream.alias("item", new Article().getClass());  
        return xstream.toXML(newsMessage);  
    }  
  
    /** 
     * 擴展xstream,使其支持CDATA塊 
     *  
     * @date 2013-05-19 
     */  
    private static XStream xstream = new XStream(new XppDriver() {  
        public HierarchicalStreamWriter createWriter(Writer out) {  
            return new PrettyPrintWriter(out) {  
                // 對全部xml節點的轉換都增長CDATA標記  
                boolean cdata = true;  
  
                @SuppressWarnings("unchecked")  
                public void startNode(String name, Class clazz) {  
                    super.startNode(name, clazz);  
                }  
  
                protected void writeText(QuickWriter writer, String text) {  
                    if (cdata) {  
                        writer.write("<![CDATA[");  
                        writer.write(text);  
                        writer.write("]]>");  
                    } else {  
                        writer.write(text);  
                    }  
                }  
            };  
        }  
    });  
}  
View Code

 

6、消息業務類——MessageService

package com.ray.service;

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

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


import com.qq.weixin.mp.aes.AesException;
import com.qq.weixin.mp.aes.WXBizMsgCrypt;
import com.ray.pojo.message.resp.TextMessage;
import com.ray.util.MessageUtil;
import com.ray.util.WeiXinParamesUtil;

/**
 * @desc  : 被動回覆消息
 * 
 * @author: shirayner
 * @date  : 2017-8-17 下午3:37:17
 */
public class MessageService {

    private String msg_signature ; // 微信加密簽名  
    private String timestamp ;    // 時間戳    
    private String nonce ;       // 隨機數  


    /**
     * @desc :獲取加密後的回覆消息
     *  
     * @param request
     * @return String  返回加密後的回覆消息
     */
    public String getEncryptRespMessage(HttpServletRequest request){
        String respMessage = null; 

        try {
            //1.解密微信發過來的消息
            String xmlMsg=this.getDecryptMsg(request);

            //2.解析微信發來的請求,解析xml字符串
            Map<String, String> requestMap= MessageUtil.parseXml(xmlMsg);    

            //3.獲取請求參數
            //3.1 企業微信CorpID  
            String fromUserName = requestMap.get("FromUserName");  
            //3.2 成員UserID
            String toUserName = requestMap.get("ToUserName");  
            //3.3 消息類型與事件 
            String msgType = requestMap.get("MsgType"); 
            String eventType = requestMap.get("Event");  
            String eventKey = requestMap.get("EventKey"); 
            System.out.println("msgType:"+msgType);
            System.out.println("Event:"+eventType+"  eventKey:"+eventKey);
            

            //4.組裝 回覆文本消息  
            TextMessage textMessage = new TextMessage();  
            textMessage.setToUserName(fromUserName);  
            textMessage.setFromUserName(toUserName);  
            textMessage.setCreateTime(new Date().getTime());  
            textMessage.setMsgType(MessageUtil.RESP_MESSAGE_TYPE_TEXT);  
            //4.1.獲取回覆消息的內容 :消息的分類處理
            String respContent=this.getRespContentByMsgType(msgType, eventType, eventKey);
            textMessage.setContent(respContent);  
            System.out.println("respContent:"+respContent);

            //5.獲取xml字符串: 將(被動回覆消息型的)文本消息對象 轉成  xml字符串
            respMessage = MessageUtil.textMessageToXml(textMessage); 
            

            //6.加密
            WXBizMsgCrypt wxcpt=new WXBizMsgCrypt(WeiXinParamesUtil.token,WeiXinParamesUtil.encodingAESKey,WeiXinParamesUtil.corpId);
            respMessage = wxcpt.EncryptMsg(respMessage, timestamp, msgType);
            

        } catch (Exception e) {
            e.printStackTrace();
        }  

        return respMessage;
    }


    /**
     * @desc :2.從request中獲取消息明文
     *  
     * @param request
     * @return String   消息明文
     */
    public String getDecryptMsg(HttpServletRequest request) {

        String postData="";   // 密文,對應POST請求的數據
        String result="";     // 明文,解密以後的結果

        this.msg_signature = request.getParameter("msg_signature"); // 微信加密簽名  
        this.timestamp = request.getParameter("timestamp");   // 時間戳    
        this.nonce = request.getParameter("nonce");          // 隨機數  

        try {
            //1.獲取加密的請求消息:使用輸入流得到加密請求消息postData
            ServletInputStream in = request.getInputStream();
            BufferedReader reader =new BufferedReader(new InputStreamReader(in));  

            String tempStr="";   //做爲輸出字符串的臨時串,用於判斷是否讀取完畢  
            while(null!=(tempStr=reader.readLine())){  
                postData+=tempStr;  
            }  

            //2.獲取消息明文:對加密的請求消息進行解密得到明文  
            WXBizMsgCrypt wxcpt=new WXBizMsgCrypt(WeiXinParamesUtil.token,WeiXinParamesUtil.encodingAESKey,WeiXinParamesUtil.corpId);
            result = wxcpt.DecryptMsg(msg_signature, timestamp, nonce, postData);

        } catch (IOException e) {
            e.printStackTrace();
        } catch (AesException e) {
            e.printStackTrace();
        }  

        return result;
    }

    /**
     * @desc :3.處理消息:根據消息類型獲取回覆內容
     *  
     * @param msgType
     * @return String
     */
    public String getRespContentByMsgType(String msgType,String eventType,String eventKey){
        String respContent="";
        //1.文本消息  
        if (msgType.equals(MessageUtil.REQ_MESSAGE_TYPE_TEXT)) {  
            respContent = "您發送的是文本消息!";  

        }  
        //2.圖片消息  
        else if (msgType.equals(MessageUtil.REQ_MESSAGE_TYPE_IMAGE)) {  
            respContent = "您發送的是圖片消息!";  
        }  
        //3.地理位置消息  
        else if (msgType.equals(MessageUtil.REQ_MESSAGE_TYPE_LOCATION)) { 
            System.out.println("消息類型:定位");
        }  
        //4.連接消息  
        else if (msgType.equals(MessageUtil.REQ_MESSAGE_TYPE_LINK)) {  
            respContent = "您發送的是連接消息!";  
        }  
        //5.音頻消息  
        else if (msgType.equals(MessageUtil.REQ_MESSAGE_TYPE_VOICE)) {  
            respContent = "您發送的是音頻消息!";  
        }
        //6.事件推送  
        else if (msgType.equals(MessageUtil.REQ_MESSAGE_TYPE_EVENT)) { 
            respContent=this.processEevent(eventType, eventKey);
        }
        //7.請求異常
        else {
            respContent="請求處理異常,請稍候嘗試!";
        }  

        return respContent;
    }

    public String processEevent(String eventType,String eventKey){
        
        String respContent="";
        // 訂閱  
        if (eventType.equals(MessageUtil.EVENT_TYPE_SUBSCRIBE)) {  
            respContent = "歡迎關注!";  
        }  
        // 取消訂閱  
        else if (eventType.equals(MessageUtil.EVENT_TYPE_UNSUBSCRIBE)) {  
            // TODO 取消訂閱後用戶再收不到公衆號發送的消息,所以不須要回復消息  
        } 
        //上報地理位置事件
        else if(eventType.equals("LOCATION")){
            
        }
        // 自定義菜單點擊事件  
        else if (eventType.equals(MessageUtil.EVENT_TYPE_CLICK)) {  

            if (eventKey.equals("12")) {  
                // TODO  help
            } else if (eventKey.equals("13")) {  
                respContent = "周邊搜索菜單項被點擊!";  
            } else if (eventKey.equals("14")) {  
                respContent = "歷史上的今天菜單項被點擊!";  
            } else if (eventKey.equals("21")) {  
                respContent = "歌曲點播菜單項被點擊!";  
            } else if (eventKey.equals("22")) {  

                respContent = "經典遊戲菜單項被點擊!";  
            } else if (eventKey.equals("23")) {  
                respContent = "美女電臺菜單項被點擊!";  
            } else if (eventKey.equals("24")) {  
                respContent = "人臉識別菜單項被點擊!";  
            } else if (eventKey.equals("25")) {  
                respContent = "聊天嘮嗑菜單項被點擊!";  
            } else if (eventKey.equals("31")) {  
                respContent = "Q友圈菜單項被點擊!";  
            } else if (eventKey.equals("32")) {  
                respContent = "電影排行榜菜單項被點擊!";  
            } else if (eventKey.equals("33")) {  
                respContent = "幽默笑話菜單項被點擊!";  
            }  
        } 
        return respContent;
    }  
  
    
    
    
    
}
View Code

 

7、CoreServlet

 

package com.ray.servlet;
  
  

import java.io.IOException;  
import java.io.PrintWriter;   
import javax.servlet.ServletException;  
import javax.servlet.http.HttpServlet;  
import javax.servlet.http.HttpServletRequest;  
import javax.servlet.http.HttpServletResponse;  


import com.qq.weixin.mp.aes.AesException;
import com.qq.weixin.mp.aes.WXBizMsgCrypt;
import com.ray.service.MessageService;
import com.ray.util.WeiXinParamesUtil;

  

  
/**
 * 核心請求處理類 
 * @author shirayner
 *
 */
public class CoreServlet extends HttpServlet {  
    private static final long serialVersionUID = 4440739483644821986L;  
  
    /** 
     * 確認請求來自微信服務器 
     */  
    public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {      
        
            // 微信加密簽名  
            String msg_signature = request.getParameter("msg_signature");  
            // 時間戳  
            String timestamp = request.getParameter("timestamp");  
            // 隨機數  
            String nonce = request.getParameter("nonce");  
            // 隨機字符串   
            String echostr = request.getParameter("echostr");  
      
            System.out.println("request=" + request.getRequestURL());  
      
            PrintWriter out = response.getWriter();  
            // 經過檢驗msg_signature對請求進行校驗,若校驗成功則原樣返回echostr,表示接入成功,不然接入失敗  
            String result = null;  
            try {
                WXBizMsgCrypt wxcpt = new WXBizMsgCrypt(WeiXinParamesUtil.token, WeiXinParamesUtil.encodingAESKey, WeiXinParamesUtil.corpId);  
                result = wxcpt.VerifyURL(msg_signature, timestamp, nonce, echostr);  
            } catch (AesException e) {  
                e.printStackTrace();  
            }  
            if (result == null) {  
                result = WeiXinParamesUtil.token;  
            }  
            out.print(result);  
            out.close();  
            out = null;  
    }  
  
    /** 
     * 處理微信服務器發來的消息 
     */  
    public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {  
        //1.將請求、響應的編碼均設置爲UTF-8(防止中文亂碼)  
        request.setCharacterEncoding("UTF-8");  
        response.setCharacterEncoding("UTF-8");  
        
        //2.調用消息業務類接收消息、處理消息  
        MessageService msgsv=new MessageService();
        String respMessage = msgsv.getEncryptRespMessage(request);  
     
        //處理表情
        // String respMessage = CoreService.processRequest_emoj(request);
        //處理圖文消息
        //String respMessage = Test_NewsService.processRequest(request);

        
        //3.響應消息  
        PrintWriter out = response.getWriter();  
        out.print(respMessage);  
        out.close(); 
    }  
  
}  
View Code

 

8、web.xml

註冊servlet

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" version="2.5">
  <welcome-file-list>
  <welcome-file>index.jsp</welcome-file>
  </welcome-file-list>
    
  <servlet>
    <servlet-name>coreServlet</servlet-name>
    <servlet-class>  
            com.ray.servlet.CoreServlet
    </servlet-class>
  </servlet>
    
  <servlet>
    <servlet-name>uploadTempMaterialServlet</servlet-name>
    <servlet-class>  
            com.ray.servlet.UploadTempMaterialServlet
    </servlet-class>
  </servlet>
    
  <servlet-mapping>
    <servlet-name>uploadTempMaterialServlet</servlet-name>
    <url-pattern>/uploadTempMaterialServlet</url-pattern>
  </servlet-mapping>
    

</web-app>
View Code
相關文章
相關標籤/搜索