-
Notifications
You must be signed in to change notification settings - Fork 152
/
baseClient.go
401 lines (327 loc) · 10.2 KB
/
baseClient.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
package kernel
import (
"crypto/sha1"
"encoding/xml"
"errors"
"fmt"
fmt2 "github.com/ArtisanCloud/PowerLibs/v2/fmt"
"github.com/ArtisanCloud/PowerLibs/v2/http/request"
"github.com/ArtisanCloud/PowerLibs/v2/object"
"github.com/ArtisanCloud/PowerWeChat/v2/src/kernel"
"github.com/ArtisanCloud/PowerWeChat/v2/src/kernel/power"
response2 "github.com/ArtisanCloud/PowerWeChat/v2/src/kernel/response"
"github.com/ArtisanCloud/PowerWeChat/v2/src/kernel/support"
"io"
"log"
http2 "net/http"
"os"
)
type BaseClient struct {
kernel.BaseClient
App *ApplicationPaymentInterface
}
func NewBaseClient(app *ApplicationPaymentInterface) (*BaseClient, error) {
config := (*app).GetContainer().GetConfig()
httpRequest, err := request.NewHttpRequest(config)
if err != nil {
return nil, err
}
client := &BaseClient{
BaseClient: kernel.BaseClient{
HttpRequest: httpRequest,
Signer: &support.SHA256WithRSASigner{
MchID: (*config)["mch_id"].(string),
CertificateSerialNo: (*config)["serial_no"].(string),
PrivateKeyPath: (*config)["key_path"].(string),
},
},
App: app,
}
return client, nil
}
func (client *BaseClient) prepends() *object.HashMap {
return &object.HashMap{}
}
func (client *BaseClient) PlainRequest(endpoint string, params *object.StringMap, method string, options *object.HashMap,
returnRaw bool, outHeader interface{}, outBody interface{},
) (response interface{}, err error) {
//config := (*client.App).GetConfig()
base := &object.HashMap{}
// init options
if options == nil {
options = &object.HashMap{}
}
options = object.MergeHashMap(base, client.prepends(), options)
options = object.FilterEmptyHashMap(options)
// check need sign body or not
signBody := ""
if "get" != object.Lower(method) {
signBody, err = object.JsonEncode(options)
if err != nil {
return nil, err
}
}
authorization, err := client.Signer.GenerateRequestSign(&support.RequestSignChain{
Method: method,
CanonicalURL: endpoint,
SignBody: signBody,
})
if err != nil {
return nil, err
}
options = object.MergeHashMap(&object.HashMap{
"headers": &object.HashMap{
"Authorization": authorization,
},
"body": signBody,
}, options)
// to be setup middleware here
//client.PushMiddleware(client.logMiddleware(), "access_token")
// http client request
returnResponse, err := client.PerformRequest(endpoint, method, options, returnRaw, outHeader, outBody)
if err != nil {
return nil, err
}
if returnRaw {
return returnResponse, nil
} else {
var rs http2.Response = http2.Response{
StatusCode: 200,
Header: nil,
}
rs.Body = returnResponse.GetBody()
result, _ := client.CastResponseToType(&rs, response2.TYPE_RAW)
return result, nil
}
}
func (client *BaseClient) RequestV2(endpoint string, params *object.HashMap, method string, option *object.HashMap,
returnRaw bool, outHeader interface{}, outBody interface{},
) (response interface{}, err error) {
//config := (*client.App).GetConfig()
base := &object.HashMap{
// 微信的接口如果传入接口以外的参数,签名会失败所以这里需要区分对待参数
"nonce_str": object.RandStringBytesMask(32),
//"mch_id": config.GetString("mch_id", ""),
//"sub_mch_id": config.GetString("sub_mch_id", ""),
//"sub_appid": config.GetString("sub_appid", ""),
}
params = object.MergeHashMap(params, base)
params = object.FilterEmptyHashMap(params)
options, err := client.AuthSignRequestV2(endpoint, method, params, option)
if err != nil {
return nil, err
}
// to be setup middleware here
//client.PushMiddleware(client.logMiddleware(), "access_token")
// http client request
returnResponse, err := client.PerformRequest(endpoint, method, options, returnRaw, outHeader, outBody)
if err != nil {
return nil, err
}
if returnRaw {
return returnResponse, nil
} else {
var rs http2.Response = http2.Response{
StatusCode: 200,
Header: nil,
}
rs.Body = returnResponse.GetBody()
result, _ := client.CastResponseToType(&rs, response2.TYPE_MAP)
return result, nil
}
}
func (client *BaseClient) Request(endpoint string, params *object.StringMap, method string, options *object.HashMap,
returnRaw bool, outHeader interface{}, outBody interface{},
) (response interface{}, err error) {
config := (*client.App).GetConfig()
// 签名访问的URL,请确保url后面不要跟参数,因为签名的参数,不包含?参数
// 比如需要在请求的时候,把debug=false,这样url后面就不会多出 "?debug=true"
options, err = client.AuthSignRequest(config, endpoint, method, params, options)
if err != nil {
return nil, err
}
// to be setup middleware here
//client.PushMiddleware(client.logMiddleware(), "access_token")
// http client request
returnResponse, err := client.PerformRequest(endpoint, method, options, returnRaw, outHeader, outBody)
if err != nil {
return nil, err
}
if returnRaw {
return returnResponse, nil
} else {
var rs http2.Response = http2.Response{
StatusCode: 200,
Header: nil,
}
rs.Body = returnResponse.GetBody()
result, _ := client.CastResponseToType(&rs, response2.TYPE_MAP)
return result, nil
}
}
func (client *BaseClient) RequestRaw(url string, params *object.StringMap, method string, options *object.HashMap, outHeader interface{}, outBody interface{}) (interface{}, error) {
return client.Request(url, params, method, options, true, outHeader, outBody)
}
func (client *BaseClient) StreamDownload(requestDownload *power.RequestDownload, filePath string) (int64, error) {
fileHandler, err := os.Create(filePath)
if err != nil {
return 0, err
}
defer fileHandler.Close()
config := (*client.App).GetConfig()
method := "GET"
options, err := client.AuthSignRequest(config, requestDownload.DownloadURL, method, nil, nil)
if err != nil {
return 0, err
}
_, err = client.PerformRequest(requestDownload.DownloadURL, method, options, true, nil, fileHandler)
if err != nil {
return 0, err
}
// 校验下载文件
downloadedHandler, err := os.Open(filePath)
if err != nil {
return 0, err
}
defer downloadedHandler.Close()
fileMd5 := sha1.New()
totalSize, err := io.Copy(fileMd5, downloadedHandler)
if err != nil {
return 0, err
}
//fmt2.Dump(totalSize)
if requestDownload.HashValue != "" {
fmt2.Dump(fileMd5.Sum(nil), requestDownload.HashValue)
if fmt.Sprintf("%x", fileMd5.Sum(nil)) != requestDownload.HashValue {
return 0, errors.New("文件损坏")
} else {
log.Println("文件SHA-256校验成功")
}
}
return totalSize, err
}
func (client *BaseClient) RequestArray(url string, method string, options *object.HashMap, outHeader interface{}, outBody interface{}) (*object.HashMap, error) {
returnResponse, err := client.RequestRaw(url, nil, method, options, outHeader, outBody)
if err != nil {
return nil, err
}
result, err := client.CastResponseToType(returnResponse.(*http2.Response), response2.TYPE_RAW)
return result.(*object.HashMap), err
}
func (client *BaseClient) SafeRequest(url string, params *object.HashMap, method string, option *object.HashMap, outHeader interface{}, outBody interface{}) (interface{}, error) {
config := (*client.App).GetConfig()
option = object.MergeHashMap(option, &object.HashMap{
"cert": config.GetString("cert_path", ""),
"ssl_key": config.GetString("key_path", ""),
})
strOutBody := ""
// get xml string result from return raw as true
_, err := client.RequestV2(
url,
params,
method,
option,
true,
outHeader,
&strOutBody,
)
if err != nil {
return nil, err
}
// get out result
err = xml.Unmarshal([]byte(strOutBody), outBody)
return outBody, err
}
func (client *BaseClient) Wrap(endpoint string) string {
if (*client.App).InSandbox() {
return "sandboxnew/" + endpoint
} else {
return endpoint
}
}
func (client *BaseClient) AuthSignRequest(config *kernel.Config, endpoint string, method string, params *object.StringMap, options *object.HashMap) (*object.HashMap, error) {
var err error
base := &object.HashMap{
"appid": config.GetString("app_id", ""),
"mchid": config.GetString("mch_id", ""),
}
// init options
if options == nil {
options = &object.HashMap{}
}
// init query parameters into body
if params != nil {
endpoint += "?" + object.GetJoinedWithKSort(params)
(*options)["query"] = params
} else {
(*options)["query"] = nil
}
options = object.MergeHashMap(base, client.prepends(), options)
options = object.FilterEmptyHashMap(options)
// check need sign body or not
signBody := ""
if "get" != object.Lower(method) {
signBody, err = object.JsonEncode(options)
if err != nil {
return nil, err
}
}
authorization, err := client.Signer.GenerateRequestSign(&support.RequestSignChain{
Method: method,
CanonicalURL: endpoint,
SignBody: signBody,
})
if err != nil {
return nil, err
}
options = object.MergeHashMap(&object.HashMap{
"headers": &object.HashMap{
"Authorization": authorization,
"Wechatpay-Serial": config.GetString("serial_no", ""),
},
"body": signBody,
}, options)
return options, err
}
func (client *BaseClient) AuthSignRequestV2(endpoint string, method string, params *object.HashMap, options *object.HashMap) (*object.HashMap, error) {
var err error
secretKey, err := (*client.App).GetKey(endpoint)
if err != nil {
return nil, err
}
strMapParams, err := object.HashMapToStringMap(params)
if err != nil {
return nil, err
}
// convert StringMap to Power StringMap
powerStrMapParams, err := power.StringMapToPower(strMapParams)
if err != nil {
return nil, err
}
// generate md5 signature with power StringMap
(*powerStrMapParams)["sign"] = support.GenerateSignMD5(powerStrMapParams, secretKey)
// convert signature to xml content
var signBody = ""
if "get" != object.Lower(method) {
// check need sign body or not
objPara, err := power.PowerStringMapToObjectStringMap(powerStrMapParams)
if err != nil {
return nil, err
}
signBody = object.StringMap2Xml(objPara)
}
// set body content
options = object.MergeHashMap(&object.HashMap{
"body": signBody,
}, options)
return options, err
}
// ----------------------------------------------------------------------
type MiddlewareLogMiddleware struct {
*BaseClient
}
func (client *BaseClient) logMiddleware() interface{} {
return &MiddlewareLogMiddleware{
client,
}
}