forked from chanxuehong/wechat
/
helper.go
73 lines (62 loc) · 2.23 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
73
// @description wechat 是腾讯微信公众平台 api 的 golang 语言封装
// @link https://github.com/chanxuehong/wechat for the canonical source repository
// @license https://github.com/chanxuehong/wechat/blob/master/LICENSE
// @authors chanxuehong(chanxuehong@gmail.com)
package mp
import (
"encoding/base64"
"encoding/xml"
"errors"
"net/http"
"strconv"
"github.com/chanxuehong/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")
}
MsgRawXML, err := xml.Marshal(msg)
if err != nil {
return
}
EncryptedMsg := util.AESEncryptMsg(r.Random, MsgRawXML, 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)
}