-
Notifications
You must be signed in to change notification settings - Fork 2
/
recvmsg.go
286 lines (251 loc) · 7.45 KB
/
recvmsg.go
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
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
// Package qy provides functions for handling the received messages.
package qy
import (
"encoding/xml"
"errors"
"fmt"
"github.com/bigwhite/gowechat/pb"
)
const (
// Msg type
TextMsg = "text"
ImageMsg = "image"
VoiceMsg = "voice"
VideoMsg = "video"
LocationMsg = "location"
EventMsg = "event"
// Event type
SubscribeEvent = "subscribe"
UnsubscribeEvent = "unsubscribe"
LocationEvent = "LOCATION"
MenuClickEvent = "click"
MenuViewEvent = "view"
ScanCodePushEvent = "scancode_push"
ScanCodeWaitEvent = "scancode_waitmsg"
PicSysPhotoEvent = "pic_sysphoto"
PicPhotoOrAlbumEvent = "pic_photo_or_album"
PicWeiXinEvent = "pic_weixin"
LocationSelectEvent = "location_select"
EnterAgentEvent = "enter_agent"
)
// RecvTextDataPkg is a Text Message received from wechat platform.
type RecvTextDataPkg struct {
pb.RecvBaseDataPkg
Content string
MsgID uint64 `xml:"MsgId"`
AgentID int
}
// RecvImageDataPkg is a Image Message received from wechat platform.
type RecvImageDataPkg struct {
pb.RecvBaseDataPkg
PicURL string `xml:"PicUrl"`
MediaID string `xml:"MediaId"`
MsgID uint64 `xml:"MsgId"`
AgentID int
}
// RecvVoiceDataPkg is a Voice Message received from wechat platform.
type RecvVoiceDataPkg struct {
pb.RecvBaseDataPkg
MediaID string `xml:"MediaId"`
Format string
MsgID uint64 `xml:"MsgId"`
AgentID int
}
// RecvVideoDataPkg is a Video Message received from wechat platform.
type RecvVideoDataPkg struct {
pb.RecvBaseDataPkg
MediaID string `xml:"MediaId"`
ThumbMediaID string `xml:"ThumbMediaId"`
MsgID uint64 `xml:"MsgId"`
AgentID int
}
// RecvLocationDataPkg is a Location Message received from wechat platform.
type RecvLocationDataPkg struct {
pb.RecvBaseDataPkg
LocX float64 `xml:"Location_X"`
LocY float64 `xml:"Location_Y"`
Scale int
Label string
MsgID uint64 `xml:"MsgId"`
AgentID int
}
// RecvSubscribeEventDataPkg is a Subscribe/Unsubscribe event
// Message received from wechat platform.
type RecvSubscribeEventDataPkg struct {
pb.RecvBaseDataPkg
Event string
AgentID int
}
// RecvLocationEventDataPkg is a Location event Message
// received from wechat platform.
type RecvLocationEventDataPkg struct {
pb.RecvBaseDataPkg
Event string
Latitude float64
Longitude float64
Precision float64
AgentID int
}
// RecvMenuEventDataPkg is a Menu Click event Message
// received from wechat platform.
type RecvMenuEventDataPkg struct {
pb.RecvBaseDataPkg
Event string
EventKey string
AgentID int
}
type RecvEnterAgentDataPkg struct {
pb.RecvBaseDataPkg
Event string
EventKey string
}
type RecvRespTextDataPkg struct {
pb.RecvRespBaseDataPkg
Content pb.CDATAText
}
type recvHandler struct {
corpID string
token string
encodingAESKey string
}
// RecvHTTPReqBody is a unmarshall result for below xml data:
// <xml>
// <ToUserName><![CDATA[toUser]]</ToUserName>
// <AgentID><![CDATA[toAgentID]]</AgentID>
// <Encrypt><![CDATA[msg_encrypt]]</Encrypt>
// </xml>
type RecvHTTPReqBody struct {
ToUserName string
AgentID string
Encrypt string
}
// RecvHTTPResqBody is a source for marshalling below xml data:
// <xml>
// <Encrypt><![CDATA[msg_encrypt]]></Encrypt>
// <MsgSignature><![CDATA[msg_signature]]></MsgSignature>
// <TimeStamp>timestamp</TimeStamp>
// <Nonce><![CDATA[nonce]]></Nonce>
// </xml>
type RecvHTTPRespBody struct {
XMLName xml.Name `xml:"xml"`
Encrypt pb.CDATAText
MsgSignature pb.CDATAText
TimeStamp int
Nonce pb.CDATAText
}
// NewRecvHandler creates an instance of recvHandler
// which implements pb.RecvHandler interface.
func NewRecvHandler(corpID, token, encodingAESKey string) pb.RecvHandler {
return &recvHandler{corpID: corpID,
token: token,
encodingAESKey: encodingAESKey}
}
// Parse used to parse the receive "post" data request.
// if Parse ok, it return one pkg struct of above; otherwise return error.
//
// Note: We suppose that r.ParseForm() has been invoked before entering this method.
// and we suppose that you have validate the URL in the post request.
func (h *recvHandler) Parse(bodyText []byte, signature, timestamp, nonce, encryptType string /* not used */) (interface{}, error) {
var err error
// XML decoding.
reqBody := &RecvHTTPReqBody{}
if err = xml.Unmarshal(bodyText, reqBody); err != nil {
return nil, err
}
// Validate signature.
if !ValidateSignature(signature, h.token, timestamp, nonce, reqBody.Encrypt) {
return nil, errors.New("validate signature error")
}
// Decrpyt the "Encrypt" field.
var origData []byte
var corpID string
origData, _, corpID, err = DecryptMsg(reqBody.Encrypt, h.encodingAESKey)
if err != nil {
return nil, err
}
if corpID != h.corpID {
return nil, fmt.Errorf("the request is from corp[%s], not from corp[%s]", corpID, h.corpID)
}
// Probe the type of message.
probePkg := &struct {
MsgType string
Event string
}{}
if err = xml.Unmarshal(origData, probePkg); err != nil {
return nil, err
}
var dataPkg interface{}
switch probePkg.MsgType {
case TextMsg:
dataPkg = &RecvTextDataPkg{}
case ImageMsg:
dataPkg = &RecvImageDataPkg{}
case VoiceMsg:
dataPkg = &RecvVoiceDataPkg{}
case VideoMsg:
dataPkg = &RecvVideoDataPkg{}
case LocationMsg:
dataPkg = &RecvLocationDataPkg{}
case EventMsg:
switch probePkg.Event {
case SubscribeEvent, UnsubscribeEvent:
dataPkg = &RecvSubscribeEventDataPkg{}
case LocationEvent:
dataPkg = &RecvLocationEventDataPkg{}
case MenuClickEvent, MenuViewEvent:
dataPkg = &RecvMenuEventDataPkg{}
case EnterAgentEvent:
dataPkg = &RecvEnterAgentDataPkg{}
case ScanCodePushEvent:
case ScanCodeWaitEvent:
case PicSysPhotoEvent:
case PicPhotoOrAlbumEvent:
case PicWeiXinEvent:
case LocationSelectEvent:
default:
return nil, fmt.Errorf("unknown event type: %s", probePkg.Event)
}
default:
return nil, fmt.Errorf("unknown msg type: %s", probePkg.MsgType)
}
if err = xml.Unmarshal(origData, dataPkg); err != nil {
return nil, err
}
return dataPkg, nil
}
// Response returns the response body data for the request from wechat qy platform.
func (h *recvHandler) Response(msg []byte, encryptType string /* not used */) ([]byte, error) {
msgEncrypt, err := EncryptMsg(msg, h.corpID, h.encodingAESKey)
if err != nil {
return nil, err
}
nonce := pb.GenNonce()
timestamp := pb.GenTimestamp()
signature := genSignature(h.token, fmt.Sprintf("%d", timestamp), nonce, msgEncrypt)
resp := &RecvHTTPRespBody{
Encrypt: pb.String2CDATA(msgEncrypt),
MsgSignature: pb.String2CDATA(signature),
TimeStamp: timestamp,
Nonce: pb.String2CDATA(nonce),
}
return xml.MarshalIndent(resp, " ", " ")
}
// ValidateSignature is used to validate the signature in request to figure out
// whether the http request come from wechat qy platform.
func ValidateSignature(signature, token, timestamp, nonce, msgEncrypt string) bool {
return signature == genSignature(token, timestamp, nonce, msgEncrypt)
}
// dev_msg_signature=sha1(sort(token、timestamp、nonce、msg_encrypt))
func genSignature(token, timestamp, nonce, msgEncrypt string) string {
return pb.GenSignature(token, timestamp, nonce, msgEncrypt)
}
func ValidateURL(signature, token, timestamp, nonce, cipherEchoStr, encodingAESKey string) (bool, []byte) {
if !ValidateSignature(signature, token, timestamp, nonce, cipherEchoStr) {
return false, nil
}
echostr, _, _, err := DecryptMsg(cipherEchoStr, encodingAESKey)
if err != nil {
return false, nil
}
return true, echostr
}