forked from l306287405/wechat3rd
-
Notifications
You must be signed in to change notification settings - Fork 0
/
wechat3rd.go
240 lines (209 loc) · 5.63 KB
/
wechat3rd.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
package wechat3rd
import (
"encoding/base64"
"encoding/xml"
"errors"
"github.com/l306287405/wechat3rd/util"
"io/ioutil"
"net/http"
"strings"
"sync"
)
// open api 配置
type Config struct {
AppID string
AppSecret string
AESKey string
Token string
//RedirectUrl string
}
func (c *Config) check() error {
if len(c.AESKey) != 43 {
//log.Fatalln("the length of base64AESKey must equal to 43")
return errors.New("the length of base64AESKey must equal to 43")
}
if len(c.Token) < 1 {
return errors.New("token was not set for Server, see NewServer function or Server.SetToken method")
}
if c.AppID == "" {
return errors.New("appid was not set for Server")
}
if c.AppSecret == "" {
return errors.New("app secret was not set for Server!")
}
return nil
}
//type Handler func(c *MixedMsg)
type Server struct {
sync.Mutex
cfg Config
//handlerMap map[string]Handler //方法处理
DecodeAesKey []byte
errorHandler WechatErrorer // 错误处理
TicketServer // ticket存储
// 获取token
AccessTokenServer
}
const (
WECHAT_API_URL = "https://api.weixin.qq.com"
WECHAT_MP_URL = "https://mp.weixin.qq.com"
CGIUrl = WECHAT_API_URL + "/cgi-bin"
)
func (s *Server) getAESKey() []byte {
return s.DecodeAesKey
}
func (s *Server) getToken() string {
return s.cfg.Token
}
type cipherRequestHttpBody struct {
XMLName struct{} `xml:"xml"`
ToUserName string `xml:"ToUserName"`
AppId string `xml:"AppId"` // openapi use
Base64EncryptedMsg []byte `xml:"Encrypt"`
}
func NewService(cfg Config, ticket TicketServer, tokenService AccessTokenServer, errHandler WechatErrorer) (s *Server, err error) {
err = cfg.check()
if err != nil {
return nil, err
}
if errHandler == nil {
errHandler = DefaultErrorHandler
}
if ticket == nil {
ticket = DefaultTicketServerHandler
}
if tokenService == nil {
tokenService = &DefaultAccessTokenServer{TicketServer: ticket, AppID: cfg.AppID, AppSecret: cfg.AppSecret}
}
s = &Server{
cfg: cfg,
errorHandler: errHandler,
//handlerMap: make(map[string]Handler),
TicketServer: ticket,
AccessTokenServer: tokenService,
}
s.DecodeAesKey, err = base64.StdEncoding.DecodeString(s.cfg.AESKey + "=")
if err != nil {
return nil, errors.New("Decode base64AESKey failed: " + err.Error())
}
return s, nil
}
func (s *Server) ServeHTTP(r *http.Request) (resp *MixedMsg, err error) {
var (
query = r.URL.Query()
wantSignature string
haveSignature = query.Get("signature")
timestamp = query.Get("timestamp")
nonce = query.Get("nonce")
//get
echostr = query.Get("echostr")
//post
wantMsgSignature string
haveMsgSignature = query.Get("msg_signature")
encryptType = query.Get("encrypt_type")
//handle vars
data []byte
requestHttpBody = &cipherRequestHttpBody{}
encryptedMsg []byte
encryptedMsgLen int
msgPlaintext, haveAppIdBytes []byte
//hand Handler
//exist bool
)
if haveSignature == "" {
err = errors.New("not found signature query parameter")
return
}
if timestamp == "" {
err = errors.New("not found timestamp query parameter")
return
}
if nonce == "" {
err = errors.New("not found nonce query parameter")
return
}
wantSignature = util.Sign(s.getToken(), timestamp, nonce)
if haveSignature != wantSignature {
return nil, errors.New("sign error")
}
//如果是验证url有效性 则echo即可
if r.Method == "GET" {
if echostr == "" {
err = errors.New("not found echostr query parameter")
return
}
resp = &MixedMsg{EchoStr: echostr}
return
}
//进入事件执行
if encryptType != "aes" {
err = errors.New("unknown encrypt_type: " + encryptType)
return
}
if haveMsgSignature == "" {
err = errors.New("not found msg_signature query parameter")
return
}
data, err = ioutil.ReadAll(r.Body)
if err != nil {
return
}
err = xml.Unmarshal(data, requestHttpBody)
if err != nil {
return
}
wantMsgSignature = util.MsgSign(s.getToken(), timestamp, nonce, string(requestHttpBody.Base64EncryptedMsg))
if haveMsgSignature != wantMsgSignature {
err = errors.New("check msg_signature failed, have: " + haveMsgSignature + ", want: " + wantMsgSignature)
return
}
encryptedMsg = make([]byte, base64.StdEncoding.DecodedLen(len(requestHttpBody.Base64EncryptedMsg)))
encryptedMsgLen, err = base64.StdEncoding.Decode(encryptedMsg, requestHttpBody.Base64EncryptedMsg)
if err != nil {
return
}
encryptedMsg = encryptedMsg[:encryptedMsgLen]
_, msgPlaintext, haveAppIdBytes, err = util.AESDecryptMsg(encryptedMsg, s.getAESKey())
if err != nil {
return
}
if string(haveAppIdBytes) != s.cfg.AppID {
err = errors.New("the message AppId mismatch, have: " + string(haveAppIdBytes) + ", want: " + s.cfg.AppID)
return
}
resp = &MixedMsg{}
if err = xml.Unmarshal(msgPlaintext, resp); err != nil {
return
}
// TODO 将在1.8版本重做推送结果处理
//hand, exist = s.handlerMap[resp.InfoType]
//if !exist {
// err = errors.New("match handler failed :" + resp.InfoType)
// return
//}
//hand(resp)
return
}
//用于解密数据
func (s *Server) AESDecryptData(cipherText, iv []byte) (rawData []byte, err error) {
return util.AESDecryptData(cipherText, s.getAESKey(), iv)
}
//url增加后缀
func (s *Server) AccessToken2url(u string) (string, error) {
token, err := s.Token()
if err != nil {
return "", err
}
if !strings.HasSuffix(u, "?") {
u += "?"
}
u += "access_token=" + token
return u, nil
}
func (s *Server) AuthToken2url(u string, authToken string) string {
if !strings.HasSuffix(u, "?") {
u += "?"
}
u += "access_token=" + authToken
return u
}