-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathserver.go
207 lines (177 loc) · 4.67 KB
/
server.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
package webhook
import (
"context"
"crypto/sha1" // #nosec
"encoding/hex"
"encoding/xml"
"errors"
"fmt"
"io"
"net/http"
"sort"
"strings"
"time"
)
// GetTokenFunc ...
type GetTokenFunc func() (string, error)
// MessageHandle ...
type MessageHandle func(ctx context.Context, msg *PlainMessage) (Messager, error)
// Server implements http.Handler. It validates incoming WeChat Public Platform webhooks and
// then dispatches them to the appropriate plugins.
type Server struct {
token string
appID string
aesKey string
crypto WXBizMsgCryptor
messageHandle MessageHandle
}
// Option ...
type Option func(*Server)
// WithPlainMode ...
func WithPlainMode(token string) Option {
return func(server *Server) {
server.token = token
}
}
// WithSafeMode ...
func WithSafeMode(token, encodingAESKey string) Option {
return func(server *Server) {
server.token = token
server.aesKey = encodingAESKey
}
}
// NewServer not implemented
func NewServer(appid string, opts ...Option) (*Server, error) {
s := &Server{
appID: appid,
}
for _, opt := range opts {
opt(s)
}
return s, s.init()
}
func (s *Server) init() error {
if len(s.aesKey) > 0 {
c, err := NewWXBizMsgCrypto(s.aesKey, s.appID, s.token)
if err != nil {
return err
}
s.crypto = c
}
return nil
}
type ctxKey struct{}
// ServeHTTP implements an http.Handler that answers callback requests.
func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) {
// this is the request for verification
if r.Method == http.MethodGet {
DefaultEchoHandle(s.token, w, r)
return
}
encryptMsg, payload, encrypted, err := ValidateWebhook(r, s.token)
if err != nil {
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
var msg = encryptMsg.PlainMessage
if encrypted {
err = s.crypto.DecryptMessage(payload, &msg)
if err != nil {
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
}
query := r.URL.Query()
ctx, cancel := context.WithCancel(r.Context())
defer cancel()
ctx = context.WithValue(ctx, ctxKey{}, query)
reply, err := s.messageHandle(ctx, &msg)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
replyMsg := &PlainMessage{
ToUserName: msg.FromUserName,
FromUserName: msg.ToUserName,
CreateTime: time.Now().Unix(),
}
switch t := reply.(type) {
case *TextMessage:
replyMsg.MsgType = "text"
replyMsg.Content = t.Content
case *ImageMessage:
case *VoiceMessage:
case *VideoMessage:
case *MusicMessage:
case *ArticleMessage:
}
replyPayload, err := xml.Marshal(replyMsg)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
if encrypted {
replyPayload, err = s.crypto.EncryptMessage(replyPayload, time.Now().Unix(), "")
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
}
_, _ = fmt.Fprint(w, replyPayload)
}
// DefaultEchoHandle This is the default Echo Handle, which will be used when WeChat Public sends an authentication request
func DefaultEchoHandle(token string, w http.ResponseWriter, r *http.Request) {
query := r.URL.Query()
signature := query.Get("signature")
timestamp := query.Get("timestamp")
nonce := query.Get("nonce")
hashcode := SHA1Sign(timestamp, nonce, token)
if signature != hashcode {
http.Error(w, ErrSignatureMismatch.Error(), http.StatusBadRequest)
return
}
echo := r.URL.Query().Get("echostr")
_, _ = fmt.Fprint(w, echo)
}
// ErrSignatureMismatch signature mismatch
var ErrSignatureMismatch = errors.New("signature mismatch")
// ErrEmptyBody ...
var ErrEmptyBody = errors.New("empty body")
// ValidateWebhook ...
func ValidateWebhook(r *http.Request, token string) (msg *EncryptMessage, payload []byte, encrypted bool, err error) {
fail := func(err error) (*EncryptMessage, []byte, bool, error) { return nil, nil, false, err }
query := r.URL.Query()
signature := query.Get("signature")
timestamp := query.Get("timestamp")
nonce := query.Get("nonce")
defer r.Body.Close() // nolint: errcheck
payload, err = io.ReadAll(r.Body)
if err != nil {
return fail(err)
}
if len(payload) == 0 {
return fail(ErrEmptyBody)
}
msg = &EncryptMessage{}
err = xml.Unmarshal(payload, msg)
if err != nil {
return fail(err)
}
if len(msg.Encrypt) > 0 {
encrypted = true
payload = []byte(msg.Encrypt)
}
hashcode := SHA1Sign(timestamp, nonce, token, msg.Encrypt)
if signature != hashcode {
return fail(ErrSignatureMismatch)
}
return msg, payload, encrypted, nil
}
// SHA1Sign Computing signatures using sha1
func SHA1Sign(args ...string) string {
sort.Strings(args)
h := sha1.New() // #nosec
h.Write([]byte(strings.Join(args, "")))
hashcode := hex.EncodeToString(h.Sum(nil))
return hashcode
}