forked from chanxuehong/wechat
-
Notifications
You must be signed in to change notification settings - Fork 0
/
helper.go
72 lines (61 loc) · 2.2 KB
/
helper.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
// @description wechat 是腾讯微信公众平台 api 的 golang 语言封装
// @link https://github.com/c77cc/wechat for the canonical source repository
// @license https://github.com/c77cc/wechat/blob/master/LICENSE
// @authors c77cc(c77cc@gmail.com)
package mp
import (
"encoding/base64"
"encoding/xml"
"errors"
"net/http"
"strconv"
"github.com/c77cc/wechat/util"
)
// 回复消息给微信服务器(明文模式).
// 要求 msg 是有效的消息数据结构(经过 encoding/xml marshal 后符合消息的格式);
// 如果有必要可以修改 Request 里面的某些值, 比如 Timestamp.
func WriteRawResponse(w http.ResponseWriter, r *Request, msg interface{}) (err error) {
if w == nil {
return errors.New("nil http.ResponseWriter")
}
if msg == nil {
return errors.New("nil message")
}
return xml.NewEncoder(w).Encode(msg)
}
// 安全模式回复消息的 http body
type ResponseHttpBody struct {
XMLName struct{} `xml:"xml" json:"-"`
EncryptedMsg string `xml:"Encrypt"`
MsgSignature string `xml:"MsgSignature"`
Timestamp int64 `xml:"TimeStamp"`
Nonce string `xml:"Nonce"`
}
// 回复消息给微信服务器(安全模式).
// 要求 msg 是有效的消息数据结构(经过 encoding/xml marshal 后符合消息的格式);
// 如果有必要可以修改 Request 里面的某些值, 比如 Timestamp.
func WriteAESResponse(w http.ResponseWriter, r *Request, msg interface{}) (err error) {
if w == nil {
return errors.New("nil http.ResponseWriter")
}
if r == nil {
return errors.New("nil Request")
}
if msg == nil {
return errors.New("nil message")
}
rawMsgXML, err := xml.Marshal(msg)
if err != nil {
return
}
encryptedMsg := util.AESEncryptMsg(r.Random, rawMsgXML, r.WechatAppId, r.AESKey)
base64EncryptedMsg := base64.StdEncoding.EncodeToString(encryptedMsg)
responseHttpBody := ResponseHttpBody{
EncryptedMsg: base64EncryptedMsg,
Timestamp: r.Timestamp,
Nonce: r.Nonce,
}
TimestampStr := strconv.FormatInt(responseHttpBody.Timestamp, 10)
responseHttpBody.MsgSignature = util.MsgSign(r.WechatToken, TimestampStr, responseHttpBody.Nonce, responseHttpBody.EncryptedMsg)
return xml.NewEncoder(w).Encode(&responseHttpBody)
}