-
Notifications
You must be signed in to change notification settings - Fork 46
/
official_account.go
427 lines (360 loc) · 11.5 KB
/
official_account.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
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
package wechat
import (
"context"
"encoding/json"
"errors"
"fmt"
"io"
"net/http"
"net/url"
"strings"
"sync/atomic"
"time"
"github.com/tidwall/gjson"
"github.com/shenghui0779/sdk-go/lib"
"github.com/shenghui0779/sdk-go/lib/curl"
"github.com/shenghui0779/sdk-go/lib/value"
)
// ServerConfig 服务器配置
type ServerConfig struct {
token string
aeskey string
}
// OfficialAccount 微信公众号
type OfficialAccount struct {
host string
appid string
secret string
srvCfg *ServerConfig
token atomic.Value
httpCli curl.Client
logger func(ctx context.Context, data map[string]string)
}
// AppID returns appid
func (oa *OfficialAccount) AppID() string {
return oa.appid
}
// Secret returns app secret
func (oa *OfficialAccount) Secret() string {
return oa.secret
}
// URL 生成请求URL
func (oa *OfficialAccount) url(path string, query url.Values) string {
var builder strings.Builder
builder.WriteString(oa.host)
if len(path) != 0 && path[0] != '/' {
builder.WriteString("/")
}
builder.WriteString(path)
if len(query) != 0 {
builder.WriteString("?")
builder.WriteString(query.Encode())
}
return builder.String()
}
func (oa *OfficialAccount) do(ctx context.Context, method, path string, query url.Values, params lib.X, options ...curl.Option) ([]byte, error) {
reqURL := oa.url(path, query)
log := lib.NewReqLog(method, reqURL)
defer log.Do(ctx, oa.logger)
var (
body []byte
err error
)
if params != nil {
body, err = json.Marshal(params)
if err != nil {
log.Set("error", err.Error())
return nil, err
}
log.SetReqBody(string(body))
}
resp, err := oa.httpCli.Do(ctx, method, reqURL, body, options...)
if err != nil {
log.Set("error", err.Error())
return nil, err
}
defer resp.Body.Close()
log.SetRespHeader(resp.Header)
log.SetStatusCode(resp.StatusCode)
if resp.StatusCode != http.StatusOK {
return nil, fmt.Errorf("HTTP Request Error, StatusCode = %d", resp.StatusCode)
}
b, err := io.ReadAll(resp.Body)
if err != nil {
log.Set("error", err.Error())
return nil, err
}
log.SetRespBody(string(b))
return b, nil
}
// OAuth2URL 生成网页授权URL
// [参考](https://developers.weixin.qq.com/doc/offiaccount/OA_Web_Apps/Wechat_webpage_authorization.html)
func (oa *OfficialAccount) OAuth2URL(scope AuthScope, redirectURI, state string) string {
query := url.Values{}
query.Set("appid", oa.appid)
query.Set("redirect_uri", redirectURI)
query.Set("response_type", "code")
query.Set("scope", string(scope))
query.Set("state", state)
return fmt.Sprintf("https://open.weixin.qq.com/connect/oauth2/authorize?%s#wechat_redirect", query.Encode())
}
// SubscribeMsgAuthURL 公众号一次性订阅消息授权URL
// [参考](https://developers.weixin.qq.com/doc/offiaccount/Message_Management/One-time_subscription_info.html)
func (oa *OfficialAccount) SubscribeMsgAuthURL(scene, templateID, redirectURL, reserved string) string {
query := url.Values{}
query.Set("appid", oa.appid)
query.Set("action", "get_confirm")
query.Set("template_id", templateID)
query.Set("redirect_url", redirectURL)
query.Set("reserved", reserved)
return fmt.Sprintf("https://oa.weixin.qq.com/oa/subscribemsg?%s#wechat_redirect", query.Encode())
}
// Code2OAuthToken 获取网页授权Token
func (oa *OfficialAccount) Code2OAuthToken(ctx context.Context, code string) (gjson.Result, error) {
query := url.Values{}
query.Set("appid", oa.appid)
query.Set("secret", oa.secret)
query.Set("code", code)
query.Set("grant_type", "authorization_code")
b, err := oa.do(ctx, http.MethodGet, "/sns/oauth2/access_token", query, nil)
if err != nil {
return lib.Fail(err)
}
ret := gjson.ParseBytes(b)
if code := ret.Get("errcode").Int(); code != 0 {
return lib.Fail(fmt.Errorf("%d | %s", code, ret.Get("errmsg").String()))
}
return ret, nil
}
// RefreshOAuthToken 刷新网页授权Token
func (oa *OfficialAccount) RefreshOAuthToken(ctx context.Context, refreshToken string) (gjson.Result, error) {
query := url.Values{}
query.Set("appid", oa.appid)
query.Set("grant_type", "refresh_token")
query.Set("refresh_token", refreshToken)
b, err := oa.do(ctx, http.MethodGet, "/sns/oauth2/refresh_token", query, nil)
if err != nil {
return lib.Fail(err)
}
ret := gjson.ParseBytes(b)
if code := ret.Get("errcode").Int(); code != 0 {
return lib.Fail(fmt.Errorf("%d | %s", code, ret.Get("errmsg").String()))
}
return ret, nil
}
// reloadAccessToken 获取稳定版接口调用凭据,有两种调用模式:
// 1. 普通模式,access_token 有效期内重复调用该接口不会更新 access_token,绝大部分场景下使用该模式;
// 2. 强制刷新模式,会导致上次获取的 access_token 失效,并返回新的 access_token
func (oa *OfficialAccount) reloadAccessToken() error {
params := lib.X{
"grant_type": "client_credential",
"appid": oa.appid,
"secret": oa.secret,
"force_refresh": false,
}
b, err := oa.do(context.Background(), http.MethodPost, "/cgi-bin/stable_token", nil, params, curl.WithHeader(curl.HeaderContentType, curl.ContentJSON))
if err != nil {
return err
}
ret := gjson.ParseBytes(b)
if code := ret.Get("errcode").Int(); code != 0 {
return fmt.Errorf("%d | %s", code, ret.Get("errmsg").String())
}
oa.token.Store(ret.Get("access_token").String())
return nil
}
func (oa *OfficialAccount) getAccessToken() (string, error) {
v := oa.token.Load()
if v == nil {
return "", errors.New("access_token is empty (forgotten auto load?)")
}
token, ok := v.(string)
if !ok {
return "", errors.New("access_token is not a string")
}
return token, nil
}
// AutoLoadAccessToken 自动加载AccessToken
func (oa *OfficialAccount) AutoLoadAccessToken() error {
if err := oa.reloadAccessToken(); err != nil {
return err
}
go func() {
ticker := time.NewTicker(time.Minute * 5)
defer ticker.Stop()
for range ticker.C {
oa.reloadAccessToken()
}
}()
return nil
}
// GetJSON GET请求JSON数据
func (oa *OfficialAccount) GetJSON(ctx context.Context, path string, query url.Values) (gjson.Result, error) {
accessToken, err := oa.getAccessToken()
if err != nil {
return lib.Fail(err)
}
if query == nil {
query = url.Values{}
}
query.Set(AccessToken, accessToken)
b, err := oa.do(ctx, http.MethodGet, path, query, nil)
if err != nil {
return lib.Fail(err)
}
ret := gjson.ParseBytes(b)
if code := ret.Get("errcode").Int(); code != 0 {
return lib.Fail(fmt.Errorf("%d | %s", code, ret.Get("errmsg").String()))
}
return ret, nil
}
// PostJSON POST请求JSON数据
func (oa *OfficialAccount) PostJSON(ctx context.Context, path string, params lib.X) (gjson.Result, error) {
accessToken, err := oa.getAccessToken()
if err != nil {
return lib.Fail(err)
}
query := url.Values{}
query.Set(AccessToken, accessToken)
b, err := oa.do(ctx, http.MethodPost, path, query, params, curl.WithHeader(curl.HeaderContentType, curl.ContentJSON))
if err != nil {
return lib.Fail(err)
}
ret := gjson.ParseBytes(b)
if code := ret.Get("errcode").Int(); code != 0 {
return lib.Fail(fmt.Errorf("%d | %s", code, ret.Get("errmsg").String()))
}
return ret, nil
}
// GetBuffer GET请求获取buffer (如:获取媒体资源)
func (oa *OfficialAccount) GetBuffer(ctx context.Context, path string, query url.Values) ([]byte, error) {
accessToken, err := oa.getAccessToken()
if err != nil {
return nil, err
}
if query == nil {
query = url.Values{}
}
query.Set(AccessToken, accessToken)
b, err := oa.do(ctx, http.MethodGet, path, query, nil)
if err != nil {
return nil, err
}
ret := gjson.ParseBytes(b)
if code := ret.Get("errcode").Int(); code != 0 {
return nil, fmt.Errorf("%d | %s", code, ret.Get("errmsg").String())
}
return b, nil
}
// PostBuffer POST请求获取buffer (如:获取二维码)
func (oa *OfficialAccount) PostBuffer(ctx context.Context, path string, params lib.X) ([]byte, error) {
accessToken, err := oa.getAccessToken()
if err != nil {
return nil, err
}
query := url.Values{}
query.Set(AccessToken, accessToken)
b, err := oa.do(ctx, http.MethodPost, path, query, params, curl.WithHeader(curl.HeaderContentType, curl.ContentJSON))
if err != nil {
return nil, err
}
ret := gjson.ParseBytes(b)
if code := ret.Get("errcode").Int(); code != 0 {
return nil, fmt.Errorf("%d | %s", code, ret.Get("errmsg").String())
}
return b, nil
}
// Upload 上传媒体资源
func (oa *OfficialAccount) Upload(ctx context.Context, path string, form curl.UploadForm) (gjson.Result, error) {
accessToken, err := oa.getAccessToken()
if err != nil {
return lib.Fail(err)
}
query := url.Values{}
query.Set(AccessToken, accessToken)
reqURL := oa.url(path, query)
log := lib.NewReqLog(http.MethodPost, reqURL)
defer log.Do(ctx, oa.logger)
resp, err := oa.httpCli.Upload(ctx, reqURL, form)
if err != nil {
log.Set("error", err.Error())
return lib.Fail(err)
}
defer resp.Body.Close()
log.SetRespHeader(resp.Header)
log.SetStatusCode(resp.StatusCode)
if resp.StatusCode != http.StatusOK {
return lib.Fail(fmt.Errorf("HTTP Request Error, StatusCode = %d", resp.StatusCode))
}
b, err := io.ReadAll(resp.Body)
if err != nil {
log.Set("error", err.Error())
return lib.Fail(err)
}
log.SetRespBody(string(b))
ret := gjson.ParseBytes(b)
if code := ret.Get("errcode").Int(); code != 0 {
return lib.Fail(fmt.Errorf("%d | %s", code, ret.Get("errmsg").String()))
}
return ret, nil
}
// VerifyURL 服务器URL验证,使用:signature、timestamp、nonce(若验证成功,请原样返回echostr参数内容)
// [参考](https://developers.weixin.qq.com/miniprogram/dev/framework/server-ability/message-push.html)
func (oa *OfficialAccount) VerifyURL(signature, timestamp, nonce string) error {
if SignWithSHA1(oa.srvCfg.token, timestamp, nonce) != signature {
return errors.New("signature verified fail")
}
return nil
}
// DecodeEventMsg 解析事件消息,使用:msg_signature、timestamp、nonce、msg_encrypt
// [参考](https://developers.weixin.qq.com/miniprogram/dev/framework/server-ability/message-push.html)
func (oa *OfficialAccount) DecodeEventMsg(signature, timestamp, nonce, encryptMsg string) (value.V, error) {
if SignWithSHA1(oa.srvCfg.token, timestamp, nonce, encryptMsg) != signature {
return nil, errors.New("signature verified fail")
}
b, err := EventDecrypt(oa.appid, oa.srvCfg.aeskey, encryptMsg)
if err != nil {
return nil, err
}
return ParseXMLToV(b)
}
// ReplyEventMsg 事件消息回复
func (oa *OfficialAccount) ReplyEventMsg(msg value.V) (value.V, error) {
return EventReply(oa.appid, oa.srvCfg.token, oa.srvCfg.aeskey, msg)
}
// OAOption 公众号设置项
type OAOption func(oa *OfficialAccount)
// WithOASrvCfg 设置公众号服务器配置
// [参考](https://developers.weixin.qq.com/doc/offiaccount/Basic_Information/Access_Overview.html)
func WithOASrvCfg(token, aeskey string) OAOption {
return func(oa *OfficialAccount) {
oa.srvCfg.token = token
oa.srvCfg.aeskey = aeskey
}
}
// WithOAHttpCli 设置公众号请求的 HTTP Client
func WithOAHttpCli(c *http.Client) OAOption {
return func(oa *OfficialAccount) {
oa.httpCli = curl.NewHTTPClient(c)
}
}
// WithOALogger 设置公众号日志记录
func WithOALogger(fn func(ctx context.Context, data map[string]string)) OAOption {
return func(oa *OfficialAccount) {
oa.logger = fn
}
}
// NewOfficialAccount 生成一个公众号实例
func NewOfficialAccount(appid, secret string, options ...OAOption) *OfficialAccount {
oa := &OfficialAccount{
host: "https://api.weixin.qq.com",
appid: appid,
secret: secret,
srvCfg: new(ServerConfig),
httpCli: curl.NewDefaultClient(),
}
for _, fn := range options {
fn(oa)
}
return oa
}