-
Notifications
You must be signed in to change notification settings - Fork 48
/
Copy pathminiprogram.go
782 lines (661 loc) · 20.5 KB
/
miniprogram.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
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
package wechat
import (
"context"
"crypto"
"crypto/rsa"
"encoding/base64"
"encoding/json"
"errors"
"fmt"
"io"
"net/http"
"net/url"
"strconv"
"strings"
"sync/atomic"
"time"
"github.com/go-resty/resty/v2"
"github.com/tidwall/gjson"
"github.com/shenghui0779/sdk-go/lib"
"github.com/shenghui0779/sdk-go/lib/value"
"github.com/shenghui0779/sdk-go/lib/xcrypto"
)
// SafeMode 安全鉴权模式配置
type SafeMode struct {
aesSN string
aeskey string
prvKey *xcrypto.PrivateKey
pubSN string
pubKey *xcrypto.PublicKey
}
// MiniProgram 小程序
type MiniProgram struct {
host string
appid string
secret string
srvCfg *ServerConfig
sfMode *SafeMode
token atomic.Value
client *resty.Client
logger func(ctx context.Context, err error, data map[string]string)
}
// AppID 返回appid
func (mp *MiniProgram) AppID() string {
return mp.appid
}
// Secret 返回secret
func (mp *MiniProgram) Secret() string {
return mp.secret
}
func (mp *MiniProgram) url(path string, query url.Values) string {
var builder strings.Builder
builder.WriteString(mp.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 (mp *MiniProgram) do(ctx context.Context, method, path string, header http.Header, query url.Values, params lib.X) ([]byte, error) {
reqURL := mp.url(path, query)
log := lib.NewReqLog(method, reqURL)
defer log.Do(ctx, mp.logger)
var (
body []byte
err error
)
if params != nil {
body, err = json.Marshal(params)
if err != nil {
log.SetError(err)
return nil, err
}
log.SetReqBody(string(body))
}
resp, err := mp.client.R().
SetContext(ctx).
SetHeaderMultiValues(header).
SetBody(body).
Execute(method, reqURL)
if err != nil {
log.SetError(err)
return nil, err
}
log.SetRespHeader(resp.Header())
log.SetStatusCode(resp.StatusCode())
log.SetRespBody(string(resp.Body()))
if !resp.IsSuccess() {
return nil, fmt.Errorf("HTTP Request Error, StatusCode = %d", resp.StatusCode())
}
return resp.Body(), nil
}
func (mp *MiniProgram) doSafe(ctx context.Context, method, path string, query url.Values, params lib.X) ([]byte, error) {
reqURL := mp.url(path, query)
log := lib.NewReqLog(method, reqURL)
defer log.Do(ctx, mp.logger)
now := time.Now().Unix()
// 加密
params, err := mp.encrypt(log, path, query, params, now)
if err != nil {
log.SetError(err)
return nil, err
}
body, err := json.Marshal(params)
if err != nil {
log.SetError(err)
return nil, err
}
log.SetReqBody(string(body))
// 签名
sign, err := mp.sign(path, now, body)
if err != nil {
log.SetError(err)
return nil, err
}
reqHeader := http.Header{}
reqHeader.Set(lib.HeaderContentType, lib.ContentJSON)
reqHeader.Set(HeaderMPAppID, mp.appid)
reqHeader.Set(HeaderMPTimestamp, strconv.FormatInt(now, 10))
reqHeader.Set(HeaderMPSignature, sign)
log.SetReqHeader(reqHeader)
resp, err := mp.client.R().
SetContext(ctx).
SetHeaderMultiValues(reqHeader).
SetBody(body).
Execute(method, reqURL)
if err != nil {
log.SetError(err)
return nil, err
}
log.SetRespHeader(resp.Header())
log.SetStatusCode(resp.StatusCode())
log.SetRespBody(string(resp.Body()))
if !resp.IsSuccess() {
return nil, fmt.Errorf("HTTP Request Error, StatusCode = %d", resp.StatusCode())
}
// 验签
if err = mp.verify(path, resp.Header(), resp.Body()); err != nil {
log.SetError(err)
return nil, err
}
// 解密
data, err := mp.decrypt(path, resp.Header(), resp.Body())
if err != nil {
log.SetError(err)
return nil, err
}
log.Set("origin_response_body", string(data))
return data, nil
}
func (mp *MiniProgram) encrypt(log *lib.ReqLog, path string, query url.Values, params lib.X, timestamp int64) (lib.X, error) {
if len(mp.sfMode.aeskey) == 0 {
return nil, errors.New("aes-gcm key not found (forgotten configure?)")
}
if params == nil {
params = lib.X{}
}
params["_n"] = base64.StdEncoding.EncodeToString(lib.NonceByte(16))
params["_appid"] = mp.appid
params["_timestamp"] = timestamp
for k, v := range query {
if k != AccessToken && len(v) != 0 {
params[k] = v[0]
}
}
data, err := json.Marshal(params)
if err != nil {
log.SetError(err)
return nil, err
}
log.Set("origin_request_body", string(data))
key, err := base64.StdEncoding.DecodeString(mp.sfMode.aeskey)
if err != nil {
log.SetError(err)
return nil, err
}
iv := lib.NonceByte(12)
aad := fmt.Sprintf("%s|%s|%d|%s", mp.url(path, nil), mp.appid, timestamp, mp.sfMode.aesSN)
ct, err := xcrypto.AESEncryptGCM(key, iv, data, []byte(aad), nil)
if err != nil {
log.SetError(err)
return nil, err
}
body := lib.X{
"iv": base64.StdEncoding.EncodeToString(iv),
"data": base64.StdEncoding.EncodeToString(ct.Data()),
"authtag": base64.StdEncoding.EncodeToString(ct.Tag()),
}
return body, nil
}
func (mp *MiniProgram) sign(path string, timestamp int64, body []byte) (string, error) {
if mp.sfMode.prvKey == nil {
return "", errors.New("private key not found (forgotten configure?)")
}
var builder strings.Builder
builder.WriteString(mp.url(path, nil))
builder.WriteString("\n")
builder.WriteString(mp.appid)
builder.WriteString("\n")
builder.WriteString(strconv.FormatInt(timestamp, 10))
builder.WriteString("\n")
builder.Write(body)
b, err := mp.sfMode.prvKey.SignPSS(crypto.SHA256, []byte(builder.String()), &rsa.PSSOptions{SaltLength: rsa.PSSSaltLengthEqualsHash})
if err != nil {
return "", err
}
return base64.StdEncoding.EncodeToString(b), nil
}
func (mp *MiniProgram) verify(path string, header http.Header, body []byte) error {
if mp.sfMode.pubKey == nil {
return errors.New("public key not found (forgotten configure?)")
}
if appid := header.Get(HeaderMPAppID); appid != mp.appid {
return fmt.Errorf("header appid mismatch, expect = %s", mp.appid)
}
var sign string
if serial := header.Get(HeaderMPSerial); serial == mp.sfMode.pubSN {
sign = header.Get(HeaderMPSignature)
} else {
serialDeprecated := header.Get(HeaderMPSerialDeprecated)
if serialDeprecated != mp.sfMode.pubSN {
return fmt.Errorf("header serial mismatch, expect = %s", mp.sfMode.pubSN)
}
sign = header.Get(HeaderMPSignatureDeprecated)
}
b, err := base64.StdEncoding.DecodeString(sign)
if err != nil {
return err
}
var builder strings.Builder
builder.WriteString(mp.url(path, nil))
builder.WriteString("\n")
builder.WriteString(mp.appid)
builder.WriteString("\n")
builder.WriteString(header.Get(HeaderMPTimestamp))
builder.WriteString("\n")
builder.Write(body)
return mp.sfMode.pubKey.VerifyPSS(crypto.SHA256, []byte(builder.String()), b, &rsa.PSSOptions{SaltLength: rsa.PSSSaltLengthEqualsHash})
}
func (mp *MiniProgram) decrypt(path string, header http.Header, body []byte) ([]byte, error) {
if len(mp.sfMode.aeskey) == 0 {
return nil, errors.New("aes-gcm key not found (forgotten configure?)")
}
key, err := base64.StdEncoding.DecodeString(mp.sfMode.aeskey)
if err != nil {
return nil, err
}
ret := gjson.ParseBytes(body)
iv, err := base64.StdEncoding.DecodeString(ret.Get("iv").String())
if err != nil {
return nil, err
}
data, err := base64.StdEncoding.DecodeString(ret.Get("data").String())
if err != nil {
return nil, err
}
tag, err := base64.StdEncoding.DecodeString(ret.Get("authtag").String())
if err != nil {
return nil, err
}
aad := fmt.Sprintf("%s|%s|%s|%s", mp.url(path, nil), mp.appid, header.Get(HeaderMPTimestamp), mp.sfMode.aesSN)
return xcrypto.AESDecryptGCM(key, iv, append(data, tag...), []byte(aad), nil)
}
// Code2Session 通过临时登录凭证code完成登录流程
func (mp *MiniProgram) Code2Session(ctx context.Context, code string) (gjson.Result, error) {
query := url.Values{}
query.Set("appid", mp.appid)
query.Set("secret", mp.secret)
query.Set("js_code", code)
query.Set("grant_type", "authorization_code")
b, err := mp.do(ctx, http.MethodGet, "/sns/jscode2session", nil, 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
}
// AccessToken 获取接口调用凭据
func (mp *MiniProgram) AccessToken(ctx context.Context) (gjson.Result, error) {
query := url.Values{}
query.Set("appid", mp.appid)
query.Set("secret", mp.secret)
query.Set("grant_type", "client_credential")
b, err := mp.do(ctx, http.MethodGet, "/cgi-bin/token", nil, 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
}
// StableAccessToken 获取稳定版接口调用凭据,有两种调用模式:
// 1. 普通模式,access_token有效期内重复调用该接口不会更新access_token,绝大部分场景下使用该模式;
// 2. 强制刷新模式,会导致上次获取的access_token失效,并返回新的access_token
func (mp *MiniProgram) StableAccessToken(ctx context.Context, forceRefresh bool) (gjson.Result, error) {
params := lib.X{
"grant_type": "client_credential",
"appid": mp.appid,
"secret": mp.secret,
"force_refresh": forceRefresh,
}
header := http.Header{}
header.Set(lib.HeaderContentType, lib.ContentJSON)
b, err := mp.do(ctx, http.MethodPost, "/cgi-bin/stable_token", header, nil, params)
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
}
// AutoLoadAccessToken 自动加载AccessToken(使用StableAccessToken接口)
func (mp *MiniProgram) AutoLoadAccessToken(interval time.Duration) error {
ctx := context.Background()
// 初始化AccessToken
ret, err := mp.StableAccessToken(context.Background(), false)
if err != nil {
return err
}
mp.token.Store(ret.Get("access_token").String())
// 异步定时加载
go func(ctx context.Context) {
ticker := time.NewTicker(interval)
defer ticker.Stop()
for range ticker.C {
_ret, _ := mp.StableAccessToken(ctx, false)
if token := _ret.Get("access_token").String(); len(token) != 0 {
mp.token.Store(token)
}
}
}(ctx)
return nil
}
// CustomAccessTokenLoad 自定义加载AccessToken
func (mp *MiniProgram) CustomAccessTokenLoad(fn func(ctx context.Context, mp *MiniProgram) (string, error), interval time.Duration) error {
ctx := context.Background()
// 初始化AccessToken
token, err := fn(ctx, mp)
if err != nil {
return err
}
mp.token.Store(token)
// 异步定时加载
go func(ctx context.Context) {
ticker := time.NewTicker(interval)
defer ticker.Stop()
for range ticker.C {
_token, _ := fn(ctx, mp)
if len(token) != 0 {
mp.token.Store(_token)
}
}
}(ctx)
return nil
}
func (mp *MiniProgram) getToken() (string, error) {
v := mp.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
}
// GetJSON GET请求JSON数据
func (mp *MiniProgram) GetJSON(ctx context.Context, path string, query url.Values) (gjson.Result, error) {
token, err := mp.getToken()
if err != nil {
return lib.Fail(err)
}
if query == nil {
query = url.Values{}
}
query.Set(AccessToken, token)
b, err := mp.do(ctx, http.MethodGet, path, nil, 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
}
// GetBuffer GET请求获取buffer (如:获取媒体资源)
func (mp *MiniProgram) GetBuffer(ctx context.Context, path string, query url.Values) ([]byte, error) {
token, err := mp.getToken()
if err != nil {
return nil, err
}
if query == nil {
query = url.Values{}
}
query.Set(AccessToken, token)
b, err := mp.do(ctx, http.MethodGet, path, nil, 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
}
// PostJSON POST请求JSON数据
func (mp *MiniProgram) PostJSON(ctx context.Context, path string, params lib.X) (gjson.Result, error) {
token, err := mp.getToken()
if err != nil {
return lib.Fail(err)
}
query := url.Values{}
query.Set(AccessToken, token)
header := http.Header{}
header.Set(lib.HeaderContentType, lib.ContentJSON)
b, err := mp.do(ctx, http.MethodPost, path, header, query, params)
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
}
// PostBuffer POST请求获取buffer (如:获取二维码)
func (mp *MiniProgram) PostBuffer(ctx context.Context, path string, params lib.X) ([]byte, error) {
token, err := mp.getToken()
if err != nil {
return nil, err
}
query := url.Values{}
query.Set(AccessToken, token)
header := http.Header{}
header.Set(lib.HeaderContentType, lib.ContentJSON)
b, err := mp.do(ctx, http.MethodPost, path, header, query, params)
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
}
// SafePostJSON POST请求JSON数据
// 安全鉴权模式 https://developers.weixin.qq.com/miniprogram/dev/OpenApiDoc/getting_started/api_signature.html
// 支持的api可参考 https://developers.weixin.qq.com/miniprogram/dev/OpenApiDoc
func (mp *MiniProgram) SafePostJSON(ctx context.Context, path string, params lib.X) (gjson.Result, error) {
token, err := mp.getToken()
if err != nil {
return lib.Fail(err)
}
query := url.Values{}
query.Set(AccessToken, token)
b, err := mp.doSafe(ctx, http.MethodPost, path, query, params)
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
}
// SafePostBuffer POST请求获取buffer (如:获取二维码)
// 安全鉴权模式 https://developers.weixin.qq.com/miniprogram/dev/OpenApiDoc/getting_started/api_signature.html
// 支持的api可参考 https://developers.weixin.qq.com/miniprogram/dev/OpenApiDoc
func (mp *MiniProgram) SafePostBuffer(ctx context.Context, path string, params lib.X) ([]byte, error) {
token, err := mp.getToken()
if err != nil {
return nil, err
}
query := url.Values{}
query.Set(AccessToken, token)
b, err := mp.doSafe(ctx, http.MethodPost, path, query, params)
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 (mp *MiniProgram) Upload(ctx context.Context, reqPath, fieldName, filePath string, formData lib.Form, query url.Values) (gjson.Result, error) {
token, err := mp.getToken()
if err != nil {
return lib.Fail(err)
}
if query == nil {
query = url.Values{}
}
query.Set(AccessToken, token)
reqURL := mp.url(reqPath, query)
log := lib.NewReqLog(http.MethodPost, reqURL)
defer log.Do(ctx, mp.logger)
resp, err := mp.client.R().
SetContext(ctx).
SetFile(fieldName, filePath).
SetFormData(formData).
Post(reqURL)
if err != nil {
log.SetError(err)
return lib.Fail(err)
}
log.SetRespHeader(resp.Header())
log.SetStatusCode(resp.StatusCode())
log.SetRespBody(string(resp.Body()))
if !resp.IsSuccess() {
return lib.Fail(fmt.Errorf("HTTP Request Error, StatusCode = %d", resp.StatusCode()))
}
ret := gjson.ParseBytes(resp.Body())
if code := ret.Get("errcode").Int(); code != 0 {
return lib.Fail(fmt.Errorf("%d | %s", code, ret.Get("errmsg").String()))
}
return ret, nil
}
// UploadWithReader 上传媒体资源
func (mp *MiniProgram) UploadWithReader(ctx context.Context, reqPath, fieldName, fileName string, reader io.Reader, formData lib.Form, query url.Values) (gjson.Result, error) {
token, err := mp.getToken()
if err != nil {
return lib.Fail(err)
}
if query == nil {
query = url.Values{}
}
query.Set(AccessToken, token)
reqURL := mp.url(reqPath, query)
log := lib.NewReqLog(http.MethodPost, reqURL)
defer log.Do(ctx, mp.logger)
resp, err := mp.client.R().
SetContext(ctx).
SetMultipartField(fieldName, fileName, "", reader).
SetFormData(formData).
Post(reqURL)
if err != nil {
log.SetError(err)
return lib.Fail(err)
}
log.SetRespHeader(resp.Header())
log.SetStatusCode(resp.StatusCode())
log.SetRespBody(string(resp.Body()))
if !resp.IsSuccess() {
return lib.Fail(fmt.Errorf("HTTP Request Error, StatusCode = %d", resp.StatusCode()))
}
ret := gjson.ParseBytes(resp.Body())
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 (mp *MiniProgram) VerifyURL(signature, timestamp, nonce string) error {
if SignWithSHA1(mp.srvCfg.token, timestamp, nonce) != signature {
return errors.New("signature verified fail")
}
return nil
}
// DecodeEncryptData 解析加密数据,如:授权的用户信息和手机号
// [参考](https://developers.weixin.qq.com/miniprogram/dev/framework/open-ability/signature.html)
func (mp *MiniProgram) DecodeEncryptData(sessionKey, iv, encryptData string) ([]byte, error) {
keyBlock, err := base64.StdEncoding.DecodeString(sessionKey)
if err != nil {
return nil, fmt.Errorf("session_key base64.decode error: %w", err)
}
ivBlock, err := base64.StdEncoding.DecodeString(iv)
if err != nil {
return nil, fmt.Errorf("iv base64.decode error: %w", err)
}
data, err := base64.StdEncoding.DecodeString(encryptData)
if err != nil {
return nil, fmt.Errorf("encrypt_data base64.decode error: %w", err)
}
return xcrypto.AESDecryptCBC(keyBlock, ivBlock, data)
}
// DecodeEventMsg 解析事件消息,使用:msg_signature、timestamp、nonce、msg_encrypt
// [参考](https://developers.weixin.qq.com/miniprogram/dev/framework/server-ability/message-push.html)
func (mp *MiniProgram) DecodeEventMsg(signature, timestamp, nonce, encryptMsg string) (value.V, error) {
if SignWithSHA1(mp.srvCfg.token, timestamp, nonce, encryptMsg) != signature {
return nil, errors.New("signature verified fail")
}
b, err := EventDecrypt(mp.appid, mp.srvCfg.aeskey, encryptMsg)
if err != nil {
return nil, err
}
return XMLToValue(b)
}
// ReplyEventMsg 事件消息回复
func (mp *MiniProgram) ReplyEventMsg(msg value.V) (value.V, error) {
return EventReply(mp.appid, mp.srvCfg.token, mp.srvCfg.aeskey, msg)
}
// MPOption 小程序设置项
type MPOption func(mp *MiniProgram)
// WithMPSrvCfg 设置小程序服务器配置
// [参考](https://developers.weixin.qq.com/miniprogram/dev/framework/server-ability/message-push.html)
func WithMPSrvCfg(token, aeskey string) MPOption {
return func(mp *MiniProgram) {
mp.srvCfg.token = token
mp.srvCfg.aeskey = aeskey
}
}
// WithMPClient 设置小程序请求的 HTTP Client
func WithMPClient(cli *http.Client) MPOption {
return func(mp *MiniProgram) {
mp.client = resty.NewWithClient(cli)
}
}
// WithMPLogger 设置小程序日志记录
func WithMPLogger(fn func(ctx context.Context, err error, data map[string]string)) MPOption {
return func(mp *MiniProgram) {
mp.logger = fn
}
}
// WithMPAesKey 设置小程序 AES-GCM 加密Key
func WithMPAesKey(serialNO, key string) MPOption {
return func(mp *MiniProgram) {
mp.sfMode.aesSN = serialNO
mp.sfMode.aeskey = key
}
}
// WithMPPrivateKey 设置小程序RSA私钥
func WithMPPrivateKey(key *xcrypto.PrivateKey) MPOption {
return func(mp *MiniProgram) {
mp.sfMode.prvKey = key
}
}
// WithMPPublicKey 设置小程序平台RSA公钥
func WithMPPublicKey(serialNO string, key *xcrypto.PublicKey) MPOption {
return func(mp *MiniProgram) {
mp.sfMode.pubSN = serialNO
mp.sfMode.pubKey = key
}
}
// NewMiniProgram 生成一个小程序实例
func NewMiniProgram(appid, secret string, options ...MPOption) *MiniProgram {
mp := &MiniProgram{
host: "https://api.weixin.qq.com",
appid: appid,
secret: secret,
srvCfg: new(ServerConfig),
client: lib.NewClient(),
}
for _, f := range options {
f(mp)
}
return mp
}