forked from panjjo/ppp
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathwxpay.go
871 lines (822 loc) · 25.7 KB
/
wxpay.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
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
package ppp
import (
"bytes"
"encoding/xml"
"fmt"
"time"
"gopkg.in/mgo.v2/bson"
)
var (
wxPayUrl string //微信支付请求地址
wxPayAppId string //微信公众号ID
wxPayMchId string //微信支付商户号
wxPayNotifyUrl string //异步通知地址
)
const (
FC_WXPAY_BARCODEPAY string = "WXPay.BarCodePay" //条码支付
FC_WXPAY_CANCEL string = "WXPay.Cancel" //取消交易
FC_WXPAY_REFUND string = "WXPay.Refund" //退款
FC_WXPAY_AUTHSIGNED string = "WXPay.AuthSigned" //签约接口
FC_WXPAY_TRADEINFO string = "WXPay.TradeInfo" //订单详情
FC_WXPAY_SBKEY string = "WXPay.SandboxSignKey" //订单详情
FC_WXPAY_WAPTRADEPARAMS string = "WXPay.WapPayParams" //网站支付参数组装
)
type WXPayInit struct {
AppId string
Url string
MchId string
ApiKey string
ConfigPath string
NotifyUrl string
}
func (w *WXPayInit) Init() {
wxPayUrl = w.Url
wxPayAppId = w.AppId
wxPayMchId = w.MchId
wxPaySecretKey = w.ApiKey
wxPayNotifyUrl = w.NotifyUrl
loadWXPayCertKey(w.ConfigPath)
}
//微信支付接口主体
type WXPay struct {
}
type wxPaySandboxSignKey struct {
XMLName xml.Name `xml:"xml"`
MchId string `xml:"mch_id"` // 商户号
NonceStr string `xml:"nonce_str"` // 随机字符串
Sign string `xml:"sign"` // 签名
}
type wxPaySandboxSignKeyResult struct {
XMLName xml.Name `xml:"xml"`
ReturnCode string `xml:"return_code"` // 返回状态码
ReturnMsg string `xml:"return_msg"` // 返回信息
SandboxSignKey string `xml:"sandbox_signkey"` //key
}
// 微信验收获取沙箱key
func (W *WXPay) SandboxSignKey(mchid string, resp *Response) error {
Log.DEBUG.Printf("WXPay api:SandboxSignKey,request:%+v", mchid)
defer Log.DEBUG.Printf("WXPay api:SandboxSignKey,response:%+v", resp)
params := wxPaySandboxSignKey{
MchId: mchid,
NonceStr: randomString(32),
}
params.Sign = WXPaySigner(structToMap(params, "xml"))
postBody, err := xml.Marshal(params)
if err != nil {
resp.Code = SysErrParams
resp.SourceData = err.Error()
}
result, _, err := W.request(wxPayUrl+"/pay/getsignkey", postBody)
if err == nil {
//成功
tmp := wxPaySandboxSignKeyResult{}
xml.Unmarshal(result.([]byte), &tmp)
resp.SourceData = tmp.SandboxSignKey
} else {
resp.Code = SysErrVerify
resp.SourceData = err.Error()
}
return nil
}
type wxPayRequest struct {
XMLName xml.Name `xml:"xml"`
// required
AppId string `xml:"appid"` // 公众账号ID
MchId string `xml:"mch_id"` // 商户号
SubMchId string `xml:"sub_mch_id"` // 子商户ID
SubAppId string `xml:"sub_appid"` //子商户公众号ID
NonceStr string `xml:"nonce_str"` // 随机字符串
Body string `xml:"body"` // 商品描述
OutTradeId string `xml:"out_trade_no"` // 商户订单号
Amount int64 `xml:"total_fee"` // 订单金额
AuthCode string `xml:"auth_code"` // 授权码
SpbillCreateIp string `xml:"spbill_create_ip"` // 终端IP
Sign string `xml:"sign"` // 签名
}
type wxTradeResult struct {
XMLName xml.Name `xml:"xml"`
ReturnCode string `xml:"return_code"` // 返回状态码
ReturnMsg string `xml:"return_msg"` // 返回信息
// when return_code == SUCCESS
AppId string `xml:"appid"` // 公众账号ID
MchId string `xml:"mch_id"` // 商户号
DeviceInfo string `xml:"device_info"` // 设备号
NonceStr string `xml:"nonce_str"` // 随机字符串
Sign string `xml:"sign"` // 签名
ResultCode string `xml:"result_code"` // 业务结果
ErrCode string `xml:"err_code"` // 错误代码
ErrCodeDes string `xml:"err_code_des"` // 错误代码描述
// when return_code == result_code == SUCCESS
OpenId string `xml:"openid"` // 用户标识
TradeType string `xml:"trade_type"` // 交易类型
Amount int64 `xml:"total_fee"` // 订单金额
Status string `xml:"trade_state"`
SettlementTotalFee int64 `xml:"settlement_total_fee"` // 应结订单金额
CouponFee int64 `xml:"coupon_fee"` // 代金券金额
CashFeeType string `xml:"cash_fee_type"` // 现金支付货币类型
CashFee int64 `xml:"cash_fee"` // 现金支付金额
TradeId string `xml:"transaction_id"` // 微信支付订单号
OutTradeId string `xml:"out_trade_no"` // 用户订单号
Attach string `xml:"attach"` // 商家数据包
TimeEnd string `xml:"time_end"` // 支付完成时间
}
// 统一收单支付接口
// DOC:https://pay.weixin.qq.com/wiki/doc/api/micropay_sl.php?chapter=9_10&index=1
// 传入参数为 BarCodePayRequest格式
// 返回参数为 TradeResult
// userid 为收款方自定义id,应存在签约授权成功后保存的对应关系
func (W *WXPay) BarCodePay(request *BarCodePayRequest, resp *TradeResult) error {
Log.DEBUG.Printf("WXPay api:BarCodePay,request:%+v", request)
defer Log.DEBUG.Printf("WXPay api:BarCodePay,response:%+v", resp)
if request.r.time == 0 {
request.r.time = getNowSec()
}
params := wxPayRequest{
AppId: wxPayAppId,
MchId: wxPayMchId,
NonceStr: randomString(32),
Body: request.TradeName,
OutTradeId: request.OutTradeId,
Amount: request.Amount,
AuthCode: request.AuthCode,
SpbillCreateIp: request.IPAddr,
}
auth := W.token(request.UserId, request.r.mchid)
if auth.Status != AuthStatusSucc {
resp.Code = AuthErrNotSigned
return nil
}
request.r.mchid = auth.MchId
params.SubMchId = request.r.mchid
params.SubAppId = auth.AppId
params.Sign = WXPaySigner(structToMap(params, "xml"))
postBody, err := xml.Marshal(params)
if err != nil {
resp.Code = SysErrParams
resp.SourceData = err.Error()
return nil
}
//请求并除错
var result interface{}
var next int
var needCancel, paySucc bool
var trade TradeResult
for getNowSec()-request.r.time < 30 {
result, next, err = W.request(wxPayUrl+"/pay/micropay", postBody)
resp.SourceData = string(jsonEncode(result))
if err != nil {
if v, ok := wxErrMap[err.Error()]; ok {
resp.Code = v
} else {
resp.Code = PayErr
}
if next == 2 {
//系统支付异常
W.TradeInfo(&TradeRequest{OutTradeId: request.OutTradeId, r: request.r}, &trade)
if trade.Code == TradeErrNotFound {
//订单不存在,重试
time.Sleep(1 * time.Second)
} else if trade.Data.Status == 1 {
paySucc = true
//存在支付成功
break
} else {
//其他情况撤销
needCancel = true
}
} else if next == 3 {
needCancel = true
//等待用户输入密码
//循环
//获取一次一直到成功
for getNowSec()-request.r.time < 30 {
W.TradeInfo(&TradeRequest{OutTradeId: request.OutTradeId, r: request.r}, &trade)
if trade.Code == 0 && trade.Data.Status == TradeStatusSucc {
//订单存在且支付
//取消撤销
needCancel = false
paySucc = true
break
}
time.Sleep(5 * time.Second)
}
break
} else if next == 0 {
//其他错误,直接返回
break
}
// -1
//网络异常 1s后重试
time.Sleep(1 * time.Second)
} else {
//支付成功返回
paySucc = true
break
}
}
//支付成功
if paySucc {
//支付成功确认
W.TradeInfo(&TradeRequest{OutTradeId: request.OutTradeId, r: request.r}, &trade)
if trade.Data.Status == TradeStatusSucc {
resp.Data = Trade{
Id: randomTimeString(),
Amount: trade.Data.Amount,
OutTradeId: request.OutTradeId,
Source: PAYTYPE_WXPAY,
PayTime: request.r.time,
UpTime: request.r.time,
Type: 1,
Status: TradeStatusSucc,
TradeId: trade.Data.TradeId,
}
resp.Code = Succ
saveTrade(resp.Data)
} else {
needCancel = true
resp.Code = PayErr
}
}
//撤销
if needCancel {
response := Response{}
W.Cancel(&TradeRequest{OutTradeId: request.OutTradeId, r: request.r}, &response)
}
return nil
}
type wxRefundRequest struct {
XMLName xml.Name `xml:"xml"`
AppId string `xml:"appid"` // 公众账号ID
MchId string `xml:"mch_id"` // 商户号
SubMchId string `xml:"sub_mch_id"` // 子商户ID
SubAppId string `xml:"sub_appid"` //子商户公众账号ID
NonceStr string `xml:"nonce_str"` // 随机字符串
OutTradeId string `xml:"out_trade_no"` // 商户订单号
Amount int64 `xml:"total_fee"` // 订单金额
Sign string `xml:"sign"` // 签名
RefundId string `xml:"refund_id"` //商户退款单号
RefundAmount int64 `xml:"refund_fee"` // 退款金额
RefundDesc string `xml:"refund_desc"` //退款备注
TradeId string `xml:"transaction_id"` //微信订单号
OutRefundId string `xml:"out_refund_no"`
}
type wxRefundResult struct {
XMLName xml.Name `xml:"xml"`
ReturnCode string `xml:"return_code"` // 返回状态码
ReturnMsg string `xml:"return_msg"` // 返回信息
// when return_code == SUCCESS
AppId string `xml:"appid"` // 公众账号ID
MchId string `xml:"mch_id"` // 商户号
DeviceInfo string `xml:"device_info"` // 设备号
NonceStr string `xml:"nonce_str"` // 随机字符串
Sign string `xml:"sign"` // 签名
ResultCode string `xml:"result_code"` // 业务结果
ErrCode string `xml:"err_code"` // 错误代码
ErrCodeDes string `xml:"err_code_des"` // 错误代码描述
TradeId string `xml:"transaction_id"`
OutTradeId string `xml:"out_trade_no"`
OutRefundId string `xml:"out_refund_no"`
RefundId string `xml:"refund_id"`
RefundAmount int64 `xml:"refund_fee"`
}
// 交易退款
// DOC:https://pay.weixin.qq.com/wiki/doc/api/micropay_sl.php?chapter=9_4
func (W *WXPay) Refund(request *RefundRequest, resp *TradeResult) error {
Log.DEBUG.Printf("WXPay api:Refund,request:%+v", request)
defer Log.DEBUG.Printf("WXPay api:Refund,response:%+v", resp)
if request.r.time == 0 {
request.r.time = getNowSec()
}
if request.OutRefundId == "" {
resp.Code = SysErrParams
resp.SourceData = "out_refund_id"
return nil
}
params := wxRefundRequest{
AppId: wxPayAppId,
MchId: wxPayMchId,
NonceStr: randomString(32),
OutTradeId: request.OutTradeId,
OutRefundId: request.OutRefundId,
RefundAmount: request.Amount,
RefundDesc: request.Memo,
}
trade := TradeResult{}
W.TradeInfo(&TradeRequest{r: request.r, UserId: request.UserId, OutTradeId: request.OutTradeId}, &trade)
if trade.Code != 0 {
resp.Code = trade.Code
resp.SourceData = trade.SourceData
return nil
}
if trade.Data.Id == "" {
resp.Code = TradeErrNotFound
return nil
}
params.TradeId = trade.Data.TradeId
params.Amount = trade.Data.Amount
auth := W.token(request.UserId, request.r.mchid)
if auth.Status != AuthStatusSucc {
resp.Code = AuthErrNotSigned
return nil
}
request.r.mchid = auth.MchId
params.SubMchId = request.r.mchid
params.SubAppId = auth.AppId
params.Sign = WXPaySigner(structToMap(params, "xml"))
postBody, err := xml.Marshal(params)
if err != nil {
resp.Code = SysErrParams
resp.SourceData = err.Error()
return nil
}
var result interface{}
var next int
for getNowSec()-request.r.time < 30 {
result, next, err = W.requestTls(wxPayUrl+"/secapi/pay/refund", postBody)
resp.SourceData = string(jsonEncode(result))
if err != nil {
if v, ok := aliErrMap[err.Error()]; ok {
resp.Code = v
} else {
resp.Code = RefundErr
}
switch next {
case 2, -1:
//网络异常 1s后重试
time.Sleep(1 * time.Second)
default:
//其他错误,直接返回
return nil
}
} else {
//成功返回
tmpresult := wxRefundResult{}
xml.Unmarshal(result.([]byte), &tmpresult)
resp.Data = Trade{
Id: randomTimeString(),
Amount: tmpresult.RefundAmount,
OutTradeId: request.OutRefundId,
Source: PAYTYPE_WXPAY,
Type: -1,
PayTime: request.r.time,
UpTime: request.r.time,
Memo: request.Memo,
Status: TradeStatusSucc,
TradeId: tmpresult.RefundId,
ParentId: trade.Data.Id,
}
saveTrade(resp.Data)
return nil
}
}
return nil
}
type wxCancelRequest struct {
XMLName xml.Name `xml:"xml"`
// required
AppId string `xml:"appid"` // 公众账号ID
MchId string `xml:"mch_id"` // 商户号
SubMchId string `xml:"sub_mch_id"` // 子商户ID
SubAppId string `xml:"sub_appid"`
NonceStr string `xml:"nonce_str"` // 随机字符串
Body string `xml:"body"` // 商品描述
OutTradeId string `xml:"out_trade_no"` // 商户订单号
TradeId string `xml:"transaction_id"`
Sign string `xml:"sign"` // 签名
}
// 交易撤销
// DOC:https://pay.weixin.qq.com/wiki/doc/api/micropay_sl.php?chapter=9_11&index=3
// 入参 TradeRequest
// 出参 Response
func (W *WXPay) Cancel(request *TradeRequest, resp *Response) error {
Log.DEBUG.Printf("WXPay api:Cancel,request:%+v", request)
defer Log.DEBUG.Printf("WXPay api:Cancel,response:%+v", resp)
if request.r.time == 0 {
request.r.time = getNowSec()
}
params := wxCancelRequest{
AppId: wxPayAppId,
MchId: wxPayMchId,
NonceStr: randomString(32),
OutTradeId: request.OutTradeId,
TradeId: request.TradeId,
}
auth := W.token(request.UserId, request.r.mchid)
if auth.Status != AuthStatusSucc {
resp.Code = AuthErrNotSigned
return nil
}
request.r.mchid = auth.MchId
params.SubMchId = request.r.mchid
params.SubAppId = auth.AppId
params.Sign = WXPaySigner(structToMap(params, "xml"))
postBody, err := xml.Marshal(params)
if err != nil {
resp.Code = SysErrParams
resp.SourceData = err.Error()
return nil
}
var result interface{}
var next int
result, next, err = W.requestTls(wxPayUrl+"/secapi/pay/reverse", postBody)
resp.SourceData = string(jsonEncode(result))
if err != nil {
if v, ok := wxErrMap[err.Error()]; ok {
resp.Code = v
} else {
resp.Code = TradeErr
}
switch next {
case 2, -1:
//网络异常 1s后重试
time.Sleep(1 * time.Second)
default:
//其他错误,直接返回
return nil
}
} else {
//成功返回
return nil
}
return nil
}
type wxTradeInfoRequest struct {
XMLName xml.Name `xml:"xml"`
// required
AppId string `xml:"appid"` // 公众账号ID
MchId string `xml:"mch_id"` // 商户号
SubMchId string `xml:"sub_mch_id"` // 子商户ID
SubAppId string `xml:"sub_appid"`
NonceStr string `xml:"nonce_str"` // 随机字符串
Body string `xml:"body"` // 商品描述
OutTradeId string `xml:"out_trade_no"` // 商户订单号
TradeId string `xml:"transaction_id"`
Sign string `xml:"sign"` // 签名
}
// 获取支付单详情
// DOC:https://pay.weixin.qq.com/wiki/doc/api/micropay_sl.php?chapter=9_2
// 传入参数TradeRequest
// 返回参数TradeResult
func (W *WXPay) TradeInfo(request *TradeRequest, resp *TradeResult) error {
Log.DEBUG.Printf("WXPay api:TradeInfo,request:%+v", request)
defer Log.DEBUG.Printf("WXPay api:TradeInfo,response:%+v", resp)
if request.r.time == 0 {
request.r.time = getNowSec()
}
auth := W.token(request.UserId, request.r.mchid)
if auth.Status != AuthStatusSucc {
resp.Code = AuthErrNotSigned
return nil
}
request.r.mchid = auth.MchId
q := bson.M{"source": PAYTYPE_WXPAY}
if request.TradeId != "" {
q["tradeid"] = request.TradeId
}
if request.OutTradeId != "" {
q["outtradeid"] = request.OutTradeId
}
trade := getTrade(q)
if request.DisSync {
if trade.Id == "" {
resp.Code = TradeErrNotFound
}
resp.Data = trade
return nil
}
params := wxTradeInfoRequest{
AppId: wxPayAppId,
MchId: wxPayMchId,
NonceStr: randomString(32),
OutTradeId: request.OutTradeId,
TradeId: request.TradeId,
}
params.SubMchId = request.r.mchid
params.SubAppId = auth.AppId
params.Sign = WXPaySigner(structToMap(params, "xml"))
postBody, err := xml.Marshal(params)
if err != nil {
resp.Code = SysErrParams
resp.SourceData = err.Error()
return nil
}
var result interface{}
var next int
for getNowSec()-request.r.time < 30 {
result, next, err = W.request(wxPayUrl+"/pay/orderquery", postBody)
resp.SourceData = string(jsonEncode(result))
if err != nil {
if v, ok := wxErrMap[err.Error()]; ok {
resp.Code = v
} else {
resp.Code = TradeErr
}
switch next {
case 2, -1:
//网络异常 1s后重试
time.Sleep(1 * time.Second)
default:
//其他错误,直接返回
return nil
}
} else {
//成功返回
tmpresult := wxTradeResult{}
xml.Unmarshal(result.([]byte), &tmpresult)
resp.Data = Trade{
OutTradeId: tmpresult.OutTradeId,
TradeId: tmpresult.TradeId,
Status: wxTradeStatusMap[tmpresult.Status],
Amount: tmpresult.Amount,
PayTime: str2Sec("20060102150405", tmpresult.TimeEnd),
Id: trade.Id,
}
if trade.Id != "" {
updateTrade(bson.M{"id": trade.Id}, bson.M{"$set": bson.M{"status": resp.Data.Status, "uptime": getNowSec(), "paytime": resp.Data.PayTime}})
}
return nil
}
}
return nil
}
type wxWapPayRequest struct {
XMLName xml.Name `xml:"xml"`
// required
AppId string `xml:"appid"` // 公众账号ID
MchId string `xml:"mch_id"` // 商户号
SubMchId string `xml:"sub_mch_id"` // 子商户ID
SubAppId string `xml:"sub_appid"`
NonceStr string `xml:"nonce_str"` // 随机字符串
Body string `xml:"body"` // 商品描述
OutTradeId string `xml:"out_trade_no"` // 商户订单号
Amount string `xml:"total_fee"`
IPAddr string `xml:"spbill_create_ip"`
NotifyUrl string `xml:"notify_url"`
TradeType string `xml:"trade_type"`
SceneInfo string `xml:"scene_info"`
Sign string `xml:"sign"` // 签名
OpenId string `xml:"openid"` //与sub_openid二选一 公众号支付必传,openid为在服务商公众号的id
SubOpenId string `xml:"sub_openid" ` //与openid 二选一 公众号支付必传,sub_openid为在子商户公众号的id
}
type wxWapPayResult struct {
XMLName xml.Name `xml:"xml"`
ReturnCode string `xml:"return_code"` // 返回状态码
ReturnMsg string `xml:"return_msg"` // 返回信息
// when return_code == SUCCESS
AppId string `xml:"appid"` // 公众账号ID
MchId string `xml:"mch_id"` // 商户号
DeviceInfo string `xml:"device_info"` // 设备号
NonceStr string `xml:"nonce_str"` // 随机字符串
Sign string `xml:"sign"` // 签名
ResultCode string `xml:"result_code"` // 业务结果
ErrCode string `xml:"err_code"` // 错误代码
ErrCodeDes string `xml:"err_code_des"` // 错误代码描述
TradeType string `xml:"trade_type"`
PrePayId string `xml:"prepay_id"`
MWEBURL string `xml:"mweb_url"`
CodeUrl string `xml:"code_url"`
}
//网页支付
//子商户模式
func (W *WXPay) WapPayParams(request *WapPayRequest, resp *Response) error {
Log.DEBUG.Printf("WXPay api:WapPayParams,request:%+v", request)
defer Log.DEBUG.Printf("WXPay api:WapPayParams,response:%+v", resp)
var tradeType string
switch request.TradeType {
case APPPAYPARAMS:
tradeType = "APP"
}
if request.r.time == 0 {
request.r.time = getNowSec()
}
auth := W.token(request.UserId, "")
if auth.Status != AuthStatusSucc {
resp.Code = AuthErrNotSigned
return nil
}
params := wxWapPayRequest{
AppId: wxPayAppId,
MchId: wxPayMchId,
SubMchId: auth.MchId,
SubAppId: auth.AppId,
NonceStr: randomString(32),
Body: request.ItemDes,
OutTradeId: request.OutTradeId,
Amount: fmt.Sprintf("%d", request.Amount),
IPAddr: request.IPAddr,
NotifyUrl: wxPayNotifyUrl,
TradeType: tradeType,
OpenId: request.OpenId,
SubOpenId: request.SubOpenId,
SceneInfo: string(jsonEncode(map[string]interface{}{
"h5_info": map[string]interface{}{"type": "Wap", "wap_url": request.Scene.Url, "wap_name": request.Scene.Name},
})),
}
if params.TradeType == JSPAYPARAMS {
if params.OpenId == "" && params.SubOpenId == "" {
resp.Code = SysErrParams
resp.SourceData = fmt.Sprintf("trade type:%s,openid or sub_openid must have one", params.TradeType)
}
}
params.Sign = WXPaySigner(structToMap(params, "xml"))
Log.ERROR.Printf("wxpay params:%+v", params)
postBody, err := xml.Marshal(params)
if err != nil {
resp.Code = SysErrParams
resp.SourceData = err.Error()
return nil
}
var result interface{}
var next int
for getNowSec()-request.r.time < 30 {
result, next, err = W.request(wxPayUrl+"/pay/unifiedorder", postBody)
resp.SourceData = string(jsonEncode(result))
if err != nil {
if v, ok := wxErrMap[err.Error()]; ok {
resp.Code = v
} else {
resp.Code = TradeErr
}
switch next {
case 2, -1:
//网络异常 1s后重试
time.Sleep(1 * time.Second)
default:
//其他错误,直接返回
return nil
}
} else {
//成功返回
tmpresult := wxWapPayResult{}
xml.Unmarshal(result.([]byte), &tmpresult)
if params.TradeType == JSPAYPARAMS {
jsParams := map[string]string{
"appId": wxPayAppId,
"timeStamp": fmt.Sprintf("%d", getNowSec()),
"nonceStr": randomString(32),
"package": "prepay_id=" + tmpresult.PrePayId,
"signType": "MD5",
}
jsParams["paySign"] = WXPaySigner(jsParams)
resp.SourceData = string(jsonEncode(jsParams))
} else {
resp.SourceData = string(jsonEncode(map[string]string{
"perpay_id": tmpresult.PrePayId,
"mweb_url": tmpresult.MWEBURL,
}))
}
//save tradeinfo
saveTrade(Trade{
OutTradeId: request.OutTradeId,
Status: 0,
Type: 1,
Amount: request.Amount,
Source: PAYTYPE_WXPAY,
UpTime: getNowSec(),
Ex: request.Ex,
Id: randomTimeString(), // PPPID
})
return nil
}
}
return nil
}
// 增加授权
// 刷新/获取授权
// 传入参数为Token格式,微信传入MchId:子商户ID
// 返回为 AuthResult
func (W *WXPay) AuthSigned(request *AuthRequest, resp *AuthResult) error {
Log.DEBUG.Printf("WXPay api:AuthSigned,request:%+v", request)
defer Log.DEBUG.Printf("WXPay api:AuthSigned,response:%+v", resp)
if request.MchId == "" {
resp.Code = SysErrParams
return nil
}
auth := getToken(request.MchId, PAYTYPE_WXPAY)
auth.Account = request.Account
if auth.MchId != "" {
//已存在授权直接返回
return nil
} else {
auth.Id = randomString(15)
auth.MchId = request.MchId
auth.Type = PAYTYPE_WXPAY
auth.Status = AuthStatusSucc
auth.AppId = request.AppId
saveToken(auth)
}
resp.Data = Auth{
MchId: auth.MchId,
Id: auth.Id,
Type: auth.Type,
Status: auth.Status,
}
//校验mchid是否为服务商子商户
trade := TradeResult{}
W.TradeInfo(&TradeRequest{r: rsys{mchid: auth.MchId}, TradeId: "test123"}, &trade)
if trade.Code == AuthErr {
//授权错误,删除授权
resp.Code = AuthErr
deleteToken(auth.MchId, auth.Type)
}
return nil
}
type wxResult struct {
XMLName xml.Name `xml:"xml"`
ReturnCode string `xml:"return_code"` // 返回状态码
ReturnMsg string `xml:"return_msg"` // 返回信息
// when return_code == SUCCESS
AppId string `xml:"appid"` // 公众账号ID
MchId string `xml:"mch_id"` // 商户号
DeviceInfo string `xml:"device_info"` // 设备号
NonceStr string `xml:"nonce_str"` // 随机字符串
Sign string `xml:"sign"` // 签名
ResultCode string `xml:"result_code"` // 业务结果
ErrCode string `xml:"err_code"` // 错误代码
ErrCodeDes string `xml:"err_code_des"` // 错误代码描述
}
func (w *WXPay) requestTls(url string, data []byte) (interface{}, int, error) {
body, err := postRequestTls(url, "text/xml", bytes.NewBuffer(data), wxPayCertTlsConfig)
if err != nil {
//网络发起请求失败
//需重试
return nil, -1, err
}
result := wxResult{}
Log.DEBUG.Printf("wxpay request url:%s,body:%s", url, string(body))
if err := xml.Unmarshal(body, &result); err != nil {
return nil, 0, err
}
if result.ReturnCode != "SUCCESS" {
return nil, -1, newError(result.ReturnCode + result.ReturnMsg)
}
next, err := w.errorCheck(result)
return body, next, err
}
func (w *WXPay) request(url string, data []byte) (interface{}, int, error) {
body, err := postRequest(url, "text/xml", bytes.NewBuffer(data))
if err != nil {
//网络发起请求失败
//需重试
return nil, -1, err
}
result := wxResult{}
Log.DEBUG.Printf("wxpay request url:%s,body:%s", url, string(body))
if err := xml.Unmarshal(body, &result); err != nil {
return nil, 0, err
}
if result.ReturnCode != "SUCCESS" {
return nil, 0, newError("NOAUTH")
}
next, err := w.errorCheck(result)
return body, next, err
}
func (w *WXPay) errorCheck(result wxResult) (int, error) {
if result.ResultCode == "SUCCESS" {
//成功
return 0, nil
}
var code int
switch result.ErrCode {
case "SYSTEMERROR", "BANKERROR":
//需确认
code = 2
case "USERPAYING":
//需循环确认
code = 3
default:
}
return code, newError(result.ErrCode)
}
func (w *WXPay) token(userid, mchid string) authBase {
auth := authBase{}
if mchid == "" {
user := getUser(userid, PAYTYPE_WXPAY)
if user.Status != UserSucc {
return auth
}
mchid = user.MchId
}
return getToken(mchid, PAYTYPE_WXPAY)
}
var wxErrMap = map[string]int{
"ORDERPAID": PayErrPayed,
"NOAUTH": AuthErr,
"AUTHCODEEXPIRE": PayErrCode,
"NOTENOUGH": UserErrBalance,
"ORDERCLODES": TradeErrStatus,
"ORDERREVERSED": TradeErrStatus,
"OUT_TRADE_NO_USED": TradeErrStatus,
"AUTH_CODE_ERROR": PayErrCode,
"AUTH_CODE_INVALID": PayErrCode,
"ORDERNOTEXIST": TradeErrNotFound,
"REVERSE_EXPIRE": RefundErrExpire,
}
var wxTradeStatusMap = map[string]Status{
"SUCCESS": TradeStatusSucc,
"REFUND": TradeStatusRefund,
"NOTPAY": TradeStatusWaitPay,
"CLOSED": TradeStatusClose,
"REVOKED": TradeStatusClose,
"USERPAYING": TradeStatusWaitPay,
}