forked from shenghui0779/sdk-go
-
Notifications
You must be signed in to change notification settings - Fork 0
/
minip.go
223 lines (170 loc) · 4.9 KB
/
minip.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
package minip
import (
"context"
"encoding/base64"
"encoding/json"
"fmt"
"net/http"
"github.com/tidwall/gjson"
"github.com/liniu/gochat/event"
"github.com/liniu/gochat/urls"
"github.com/liniu/gochat/wx"
)
// Minip 微信小程序
type Minip struct {
appid string
appsecret string
token string
aeskey string
nonce func() string
client wx.HTTPClient
}
// AppID returns appid
func (mp *Minip) AppID() string {
return mp.appid
}
// AppSecret returns app secret
func (mp *Minip) AppSecret() string {
return mp.appsecret
}
// Code2Session 获取小程序授权的session_key
func (mp *Minip) Code2Session(ctx context.Context, code string, options ...wx.HTTPOption) (*AuthSession, error) {
resp, err := mp.client.Do(ctx, http.MethodGet, fmt.Sprintf("%s?appid=%s&secret=%s&js_code=%s&grant_type=authorization_code", urls.MinipCode2Session, mp.appid, mp.appsecret, code), nil, options...)
if err != nil {
return nil, err
}
r := gjson.ParseBytes(resp)
if code := r.Get("errcode").Int(); code != 0 {
return nil, fmt.Errorf("%d|%s", code, r.Get("errmsg").String())
}
session := new(AuthSession)
if err = json.Unmarshal(resp, session); err != nil {
return nil, err
}
return session, nil
}
// AccessToken 获取小程序的access_token
func (mp *Minip) AccessToken(ctx context.Context, options ...wx.HTTPOption) (*AccessToken, error) {
resp, err := mp.client.Do(ctx, http.MethodGet, fmt.Sprintf("%s?appid=%s&secret=%s&grant_type=client_credential", urls.MinipAccessToken, mp.appid, mp.appsecret), nil, options...)
if err != nil {
return nil, err
}
r := gjson.ParseBytes(resp)
if code := r.Get("errcode").Int(); code != 0 {
return nil, fmt.Errorf("%d|%s", code, r.Get("errmsg").String())
}
token := new(AccessToken)
if err = json.Unmarshal(resp, token); err != nil {
return nil, err
}
return token, nil
}
// DecryptAuthInfo 解密授权信息
func (mp *Minip) DecryptAuthInfo(sessionKey, iv, encryptedData string, result *AuthInfo) error {
key, err := base64.StdEncoding.DecodeString(sessionKey)
if err != nil {
return err
}
ivb, err := base64.StdEncoding.DecodeString(iv)
if err != nil {
return err
}
cipherText, err := base64.StdEncoding.DecodeString(encryptedData)
if err != nil {
return err
}
cbc := wx.NewCBCCrypto(key, ivb, wx.AES_PKCS7)
b, err := cbc.Decrypt(cipherText)
if err != nil {
return err
}
return json.Unmarshal(b, result)
}
// Do exec action
func (mp *Minip) Do(ctx context.Context, accessToken string, action wx.Action, options ...wx.HTTPOption) error {
var (
resp []byte
err error
)
if action.IsUpload() {
form, ferr := action.UploadForm()
if ferr != nil {
fmt.Println("[ERR]", ferr)
return ferr
}
resp, err = mp.client.Upload(ctx, action.URL(accessToken), form, options...)
} else {
body, berr := action.Body()
if berr != nil {
return err
}
resp, err = mp.client.Do(ctx, action.Method(), action.URL(accessToken), body, options...)
}
if err != nil {
return err
}
r := gjson.ParseBytes(resp)
if code := r.Get("errcode").Int(); code != 0 {
return fmt.Errorf("%d|%s", code, r.Get("errmsg").String())
}
return action.Decode(resp)
}
// VerifyEventSign 验证事件消息签名
// 验证消息来自微信服务器,使用:signature、timestamp、nonce(若验证成功,请原样返回echostr参数内容)
// 验证事件消息签名,使用:msg_signature、timestamp、nonce、msg_encrypt
// [参考](https://developers.weixin.qq.com/miniprogram/dev/framework/server-ability/message-push.html)
func (mp *Minip) VerifyEventSign(signature string, items ...string) bool {
signStr := event.SignWithSHA1(mp.token, items...)
return signStr == signature
}
// DecryptEventMessage 事件消息解密
func (mp *Minip) DecryptEventMessage(encrypt string) (wx.WXML, error) {
b, err := event.Decrypt(mp.appid, mp.aeskey, encrypt)
if err != nil {
return nil, err
}
return wx.ParseXML2Map(b)
}
// Option 小程序配置项
type Option func(mp *Minip)
// WithServerConfig 设置服务器配置
// [参考](https://developers.weixin.qq.com/doc/offiaccount/Basic_Information/Access_Overview.html)
func WithServerConfig(token, aeskey string) Option {
return func(mp *Minip) {
mp.token = token
mp.aeskey = aeskey
}
}
// WithNonce 设置 Nonce(加密随机串)
func WithNonce(f func() string) Option {
return func(mp *Minip) {
mp.nonce = f
}
}
// WithClient 设置 HTTP Client
func WithClient(c *http.Client) Option {
return func(mp *Minip) {
mp.client = wx.NewHTTPClient(c)
}
}
// WithMockClient 设置 Mock Client
func WithMockClient(c wx.HTTPClient) Option {
return func(mp *Minip) {
mp.client = c
}
}
// New returns new wechat mini program
func New(appid, appsecret string, options ...Option) *Minip {
mp := &Minip{
appid: appid,
appsecret: appsecret,
nonce: func() string {
return wx.Nonce(16)
},
client: wx.NewDefaultClient(),
}
for _, f := range options {
f(mp)
}
return mp
}