JAVA微信公众号网页开发 —— 接收微信服务器发送的消息



WeixinMessage.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
package com.test;
 
import java.io.Serializable;
 
 
/**
 * This is an object that contains data related to the jg_weixinmessage table.
 * Do not modify this class because it will be overwritten if the configuration file
 * related to this class is modified.
 *
 * @hibernate.class
 *  table="jg_weixinmessage"
 */
 
public abstract class WeixinMessage implements Serializable {
 
 
    private static final long serialVersionUID = 1L;
    public static final int CONTENT_ONLY=2;
    public static final int CONTENT_WITH_KEY=1;
    public static final int CONTENT_WITH_IMG=0;
 
    // constructors
    public WeixinMessage() {
        initialize();
    }
 
    /**
     * Constructor for primary key
     */
    public WeixinMessage(Integer id) {
        this.setId(id);
        initialize();
    }
 
    protected void initialize () {}
 
 
 
    private int hashCode = Integer.MIN_VALUE;
 
    // primary key
    private Integer id;
 
    // fields
    private String number;
    private String title;
    private String path;
    private String url;
    private String content;
    private Boolean welcome;
    private Integer type;
 
    // many to one
 
 
 
    /**
     * Return the unique identifier of this class
     * @hibernate.id
     *  generator-class="identity"
     *  column="wm_id"
     */
    public Integer getId () {
        return id;
    }
 
    /**
     * Set the unique identifier of this class
     * @param id the new ID
     */
    public void setId (Integer id) {
        this.id = id;
        this.hashCode = Integer.MIN_VALUE;
    }
 
 
 
 
    /**
     * Return the value associated with the column: wm_number
     */
    public String getNumber () {
        return number;
    }
 
    /**
     * Set the value related to the column: wm_number
     * @param number the wm_number value
     */
    public void setNumber (String number) {
        this.number = number;
    }
 
 
 
    /**
     * Return the value associated with the column: wm_title
     */
    public String getTitle () {
        return title;
    }
 
    /**
     * Set the value related to the column: wm_title
     * @param title the wm_title value
     */
    public void setTitle (String title) {
        this.title = title;
    }
 
 
 
    /**
     * Return the value associated with the column: wm_path
     */
    public String getPath () {
        return path;
    }
 
    /**
     * Set the value related to the column: wm_path
     * @param path the wm_path value
     */
    public void setPath (String path) {
        this.path = path;
    }
 
 
 
    /**
     * Return the value associated with the column: wm_url
     */
    public String getUrl () {
        return url;
    }
 
    /**
     * Set the value related to the column: wm_url
     * @param url the wm_url value
     */
    public void setUrl (String url) {
        this.url = url;
    }
 
 
 
    /**
     * Return the value associated with the column: wm_content
     */
    public String getContent () {
        return content;
    }
 
    /**
     * Set the value related to the column: wm_content
     * @param content the wm_content value
     */
    public void setContent (String content) {
        this.content = content;
    }
 
 
 
    /**
     * Return the value associated with the column: is_welcome
     */
    public Boolean isWelcome () {
        return welcome;
    }
 
    /**
     * Set the value related to the column: is_welcome
     * @param welcome the is_welcome value
     */
    public void setWelcome (Boolean welcome) {
        this.welcome = welcome;
    }
 
    public Integer getType() {
        return type;
    }
 
    public void setType(Integer type) {
        this.type = type;
    }
 
    /**
     * Return the value associated with the column: site_id
     */
 
    /**
     * Set the value related to the column: site_id
     */
 
 
 
 
    public boolean equals (Object obj) {
        if (null == obj) return false;
        if (!(obj instanceof WeixinMessage)) return false;
        else {
            WeixinMessage weixinMessage = (WeixinMessage) obj;
            if (null == this.getId() || null == weixinMessage.getId()) return false;
            else return (this.getId().equals(weixinMessage.getId()));
        }
    }
 
    public int hashCode () {
        if (Integer.MIN_VALUE == this.hashCode) {
            if (null == this.getId()) return super.hashCode();
            else {
                String hashStr = this.getClass().getName() + ":" + this.getId().hashCode();
                this.hashCode = hashStr.hashCode();
            }
        }
        return this.hashCode;
    }
 
 
    public String toString () {
        return super.toString();
    }
 
 
}

  

MessageAct.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
package com.test;
 
import org.apache.commons.codec.digest.DigestUtils;
import org.dom4j.Document;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
 
import javax.servlet.ServletInputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
 
@Controller
public class MessageAct<UnifiedUserMng> {
 
 
    /**
     * 微信开发者验证URL  需要在微信公众平台填写该接收地址
     *
     * @param signature
     * @param timestamp
     * @param nonce
     * @param echostr
     * @param request
     * @param response
     * @param model
     * @throws IOException
     */
    @RequestMapping(value = "/sendMessage")
    public void weixin(String signature, String timestamp, String nonce, String echostr,
                       HttpServletRequest request, HttpServletResponse response, ModelMap model) throws IOException {
        //开发者验证填写TOKEN值
        String token = ""//微信后台配置的开发者token
        Object[] tmpArr = new Object[]{token, timestamp, nonce};
        Arrays.sort(tmpArr);
        String str = tmpArr[0].toString() + tmpArr[1].toString() + tmpArr[2].toString();
        String tmpStr = DigestUtils.shaHex(str);
        if (tmpStr.equals(signature)) {
            // 调用核心业务类接收消息、处理消息
            processRequest(echostr, request, response);
        } else {
            System.out.println("fail");
        }
 
    }
 
 
 
    private String processRequest(String echostr, HttpServletRequest request, HttpServletResponse response) throws IOException {
        request.setCharacterEncoding("UTF-8");
        String postStr = readStreamParameter(request.getInputStream());
        Document document = null;
        try {
            if (postStr != null && !postStr.trim().equals("")) {
                document = DocumentHelper.parseText(postStr);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        if (null == document) {
            response.getWriter().write(echostr);
            return null;
        }
        Element root = document.getRootElement();
        String fromUsername = root.elementText("FromUserName");  //取得发送者
        String toUsername = root.elementText("ToUserName");  //取得接收者
        String userMsgType = root.elementText("MsgType");
 
        String keyword = root.elementTextTrim("Content");
        String time = new Date().getTime() + "";
 
        // 默认返回的文本消息内容
        String respContent = "no body";
        String welcome = "默认回复语";
        if (userMsgType.equals("event")) {
            // 事件类型
            String eventType = root.elementText("Event");
            // 订阅
            if (eventType.equals("subscribe")) {
                respContent = welcome;
                respContent = text(respContent, fromUsername, toUsername, time);
                send(respContent, response);
                //关注判断是否用户存在
 
                return null;
            }
            // 取消订阅
            else if (eventType.equals("unsubscribe")) {
                // TODO 取消订阅后用户再收不到公众号发送的消息,因此不须要回复消息
                //取消订阅后 修改用户状态
 
                return null;
            }else if (eventType.equals("LOCATION")) {
                //用户的位置坐标
                String latitude = root.elementText("Latitude");
                String longitude = root.elementText("Longitude");
 
 
            }
 
 
            // 自定义菜单点击事件
            // 事件KEY值,与创建自定义菜单时指定的KEY值对应
            String eventKey = root.elementText("EventKey");
            //返回自定义回复的定义
            if (!eventType.equals("LOCATION")) {
                autoReply(eventKey, fromUsername, toUsername, time, request, response);
            }
            return null;
        }
        //回复内容
        if (keyword != null) {
            keyword = keyword.trim();
        }
        if (keyword != null && userMsgType.equals("text")) {
            autoReply(keyword, fromUsername, toUsername, time, request, response);
        }
        return null;
    }
 
 
 
    private void autoReply(String keyword, String fromUsername, String toUsername, String time, HttpServletRequest request, HttpServletResponse response) throws IOException {
        WeixinMessage entity = weixinMessageMng.findByNumber(keyword);
        if (entity != null) {
            String text = contentWithImgUseMessage(entity, fromUsername, toUsername, time, request);
            send(text, response);
        } else {
            entity = weixinMessageMng.getWelcome();
            if (entity != null) {
                StringBuffer buffer = new StringBuffer();
                String textTpl = "";
                //内容+关键字 标题 提示
                if (entity.getType().equals(WeixinMessage.CONTENT_WITH_KEY)) {
                    buffer.append(entity.getContent()).append("\n");
                    List<WeixinMessage> lists = weixinMessageMng.getList(site.getId());
                    for (int i = 0; i < lists.size(); i++) {
                        buffer.append("  【" + lists.get(i).getNumber() + "】" + lists.get(i).getTitle()).append("\n");
                    }
                    textTpl = text(buffer.toString(), fromUsername, toUsername, time);
                } else if (entity.getType().equals(WeixinMessage.CONTENT_ONLY)) {
                    //仅限内容
                    buffer.append(entity.getContent()).append("\n");
                    textTpl = text(buffer.toString(), fromUsername, toUsername, time);
                } else if (entity.getType().equals(WeixinMessage.CONTENT_WITH_IMG)) {
                    //图文类型(图片 标题 文字 链接组成)
                    textTpl = contentWithImgUseMessage(entity, fromUsername, toUsername, time, request);
                }
                send(textTpl, response);
            }
        }
    }
 
    private String contentWithImgUseMessage(WeixinMessage entity, String fromUsername, String toUsername, String time, HttpServletRequest request) {
        String textTpls = text(fromUsername, toUsername, time, entity.getTitle(), entity.getContent(), "(图片地址)", entity.getUrl());
        return textTpls;
    }
 
 
    private void send(String textTpl, HttpServletResponse response) throws IOException {
        String type = "text/xml;charset=UTF-8";
        response.setContentType(type);
        response.setHeader("Pragma", "No-cache");
        response.setHeader("Cache-Control", "no-cache");
        response.setDateHeader("Expires", 0);
        response.getWriter().write(textTpl);
    }
 
 
    private String text(String fromUsername, String toUsername, String time, String title, String desc, String img, String url) {
        String textTpls = "<xml>" +
                "<ToUserName><![CDATA[" + fromUsername + "]]></ToUserName>" +
                "<FromUserName><![CDATA[" + toUsername + "]]></FromUserName>" +
                "<CreateTime>" + time + "</CreateTime>" +
                "<MsgType><![CDATA[news]]></MsgType>" +
                "<ArticleCount>1</ArticleCount>" +
                "<Articles>" +
                "<item>" +
                "<Title><![CDATA[" + title + "]]></Title>" +
                "<Description><![CDATA[" + desc + "]]></Description>" +
                "<PicUrl><![CDATA[" + img + "]]></PicUrl>" +
                "<Url><![CDATA[" + url + "]]></Url>" +
                "</item>" +
                "</Articles>" +
                "</xml>";
        return textTpls;
    }
 
    private String text(String str, String fromUsername, String toUsername, String time) {
        String textTpls = "<xml>" +
                "<ToUserName><![CDATA[" + fromUsername + "]]></ToUserName>" +
                "<FromUserName><![CDATA[" + toUsername + "]]></FromUserName>" +
                "<CreateTime>" + time + "</CreateTime>" +
                "<MsgType><![CDATA[text]]></MsgType>" +
                "<Content><![CDATA[" + str + "]]></Content>" +
                "</xml>";
 
        return textTpls;
    }
 
 
    //从输入流读取post参数
    private String readStreamParameter(ServletInputStream in) {
        StringBuilder buffer = new StringBuilder();
        BufferedReader reader = null;
        try {
            reader = new BufferedReader(new InputStreamReader(in, "UTF-8"));
            String line = null;
            while ((line = reader.readLine()) != null) {
                buffer.append(line);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (null != reader) {
                try {
                    reader.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return buffer.toString();
    }
 
}

  

 

posted @   yvioo  阅读(715)  评论(0编辑  收藏  举报
编辑推荐:
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
· 没有源码,如何修改代码逻辑?
阅读排行:
· 全程不用写代码,我用AI程序员写了一个飞机大战
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 记一次.NET内存居高不下排查解决与启示
· DeepSeek 开源周回顾「GitHub 热点速览」
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
点击右上角即可分享
微信分享提示