-
Notifications
You must be signed in to change notification settings - Fork 702
/
cert.go
312 lines (299 loc) · 9.92 KB
/
cert.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
package wechat
import (
"context"
"crypto"
"crypto/rand"
"crypto/rsa"
"crypto/sha256"
"encoding/base64"
"encoding/json"
"fmt"
"net/http"
"runtime"
"sort"
"sync"
"time"
"github.com/go-pay/gopay"
"github.com/go-pay/gopay/pkg/aes"
"github.com/go-pay/gopay/pkg/errgroup"
"github.com/go-pay/gopay/pkg/retry"
"github.com/go-pay/gopay/pkg/util"
"github.com/go-pay/gopay/pkg/xhttp"
"github.com/go-pay/gopay/pkg/xlog"
"github.com/go-pay/gopay/pkg/xpem"
"github.com/go-pay/gopay/pkg/xtime"
)
// 获取微信平台证书公钥(获取后自行保存使用,如需定期刷新功能,自行实现)
// 注意事项
// 如果自行实现验证平台签名逻辑的话,需要注意以下事项:
// - 程序实现定期更新平台证书的逻辑,不要硬编码验证应答消息签名的平台证书
// - 定期调用该接口,间隔时间小于12小时
// - 加密请求消息中的敏感信息时,使用最新的平台证书(即:证书启用时间较晚的证书)
//
// 文档说明:https://pay.weixin.qq.com/wiki/doc/apiv3/apis/wechatpay5_1.shtml
func GetPlatformCerts(ctx context.Context, mchid, apiV3Key, serialNo, privateKey string) (certs *PlatformCertRsp, err error) {
var (
eg = new(errgroup.Group)
mu sync.Mutex
jb = ""
)
// Prepare
priKey, err := xpem.DecodePrivateKey([]byte(privateKey))
if err != nil {
return nil, err
}
timestamp := time.Now().Unix()
nonceStr := util.RandomString(32)
ts := util.Int642String(timestamp)
_str := MethodGet + "\n" + v3GetCerts + "\n" + ts + "\n" + nonceStr + "\n" + jb + "\n"
// Sign
h := sha256.New()
h.Write([]byte(_str))
result, err := rsa.SignPKCS1v15(rand.Reader, priKey, crypto.SHA256, h.Sum(nil))
if err != nil {
return nil, fmt.Errorf("[%w]: %+v", gopay.SignatureErr, err)
}
sign := base64.StdEncoding.EncodeToString(result)
// Authorization
authorization := Authorization + ` mchid="` + mchid + `",nonce_str="` + nonceStr + `",timestamp="` + ts + `",serial_no="` + serialNo + `",signature="` + sign + `"`
// Request
var url = v3BaseUrlCh + v3GetCerts
httpClient := xhttp.NewClient()
httpClient.Header.Add(HeaderAuthorization, authorization)
httpClient.Header.Add(HeaderRequestID, fmt.Sprintf("%s-%d", util.RandomString(21), time.Now().Unix()))
httpClient.Header.Add(HeaderSerial, serialNo)
httpClient.Header.Add("Accept", "*/*")
res, bs, err := httpClient.Type(xhttp.TypeJSON).Get(url).EndBytes(ctx)
if err != nil {
return nil, err
}
certs = &PlatformCertRsp{Code: Success}
if res.StatusCode != http.StatusOK {
certs.Code = res.StatusCode
certs.Error = string(bs)
return certs, nil
}
// Parse
certRsp := new(PlatformCert)
if err = json.Unmarshal(bs, certRsp); err != nil {
return nil, fmt.Errorf("json.Unmarshal(%s):%+v", string(bs), err)
}
for _, v := range certRsp.Data {
cert := v
if cert.EncryptCertificate != nil {
ec := cert.EncryptCertificate
eg.Go(func(ctx context.Context) error {
cipherBytes, _ := base64.StdEncoding.DecodeString(ec.Ciphertext)
pubKeyBytes, err := aes.GCMDecrypt(cipherBytes, []byte(ec.Nonce), []byte(ec.AssociatedData), []byte(apiV3Key))
if err != nil {
return fmt.Errorf("aes.GCMDecrypt, err:%+v", err)
}
pci := &PlatformCertItem{
EffectiveTime: cert.EffectiveTime,
ExpireTime: cert.ExpireTime,
PublicKey: string(pubKeyBytes),
SerialNo: cert.SerialNo,
}
mu.Lock()
certs.Certs = append(certs.Certs, pci)
mu.Unlock()
return nil
})
}
}
if err = eg.Wait(); err != nil {
return nil, err
}
return certs, nil
}
// 设置 微信支付平台证书 和 证书序列号
//
// 注意1:如已开启自动验签功能 client.AutoVerifySign(),无需再调用此方法设置
// 注意2:请预先通过 wechat.GetPlatformCerts() 获取 微信平台公钥证书 和 证书序列号
// 部分接口请求参数中敏感信息加密,使用此 微信支付平台公钥 和 证书序列号
func (c *ClientV3) SetPlatformCert(wxPublicKeyContent []byte, wxSerialNo string) (client *ClientV3) {
pubKey, err := xpem.DecodePublicKey(wxPublicKeyContent)
if err != nil {
xlog.Errorf("SetPlatformCert(%s),err:%+v", wxPublicKeyContent, err)
}
if pubKey != nil {
c.wxPublicKey = pubKey
}
c.WxSerialNo = wxSerialNo
return c
}
// 获取最新的 微信平台证书
func (c *ClientV3) WxPublicKey() (wxPublicKey *rsa.PublicKey) {
return c.wxPublicKey
}
// 获取 微信平台证书 Map(readonly)
// wxPublicKeyMap: key:SerialNo, value:WxPublicKey
func (c *ClientV3) WxPublicKeyMap() (wxPublicKeyMap map[string]*rsa.PublicKey) {
wxPublicKeyMap = make(map[string]*rsa.PublicKey, len(c.SnCertMap))
for k, v := range c.SnCertMap {
wxPublicKeyMap[k] = v
}
return wxPublicKeyMap
}
// 获取证书Map集并选择最新的有效证书序列号
func (c *ClientV3) GetAndSelectNewestCert() (serialNo string, snCertMap map[string]string, err error) {
certs, err := c.getPlatformCerts()
if err != nil {
return gopay.NULL, nil, err
}
if certs.Code == Success && len(certs.Certs) > 0 {
snCertMap = make(map[string]string)
// only one
if len(certs.Certs) == 1 {
formatExpire := xtime.FormatDateTime(certs.Certs[0].ExpireTime)
expireTime, err := time.ParseInLocation(xtime.TimeLayout, formatExpire, time.Local)
if err != nil {
return gopay.NULL, nil, fmt.Errorf("time.ParseInLocation(%s, %s),err:%w", xtime.TimeLayout, formatExpire, err)
}
if time.Since(expireTime) > 0 {
return gopay.NULL, nil, fmt.Errorf("wechat platform API cert expired, expired time: %s", formatExpire)
}
serialNo = certs.Certs[0].SerialNo
snCertMap[serialNo] = certs.Certs[0].PublicKey
return serialNo, snCertMap, nil
}
// more one
var (
effectiveTs []int
certMap = make(map[int]*PlatformCertItem)
)
for _, v := range certs.Certs {
formatEffective := xtime.FormatDateTime(v.EffectiveTime)
formatExpire := xtime.FormatDateTime(v.ExpireTime)
effectiveTime, err := time.ParseInLocation(xtime.TimeLayout, formatEffective, time.Local)
if err != nil {
return gopay.NULL, nil, fmt.Errorf("time.ParseInLocation(%s, %s),err:%w", xtime.TimeLayout, formatEffective, err)
}
expireTime, err := time.ParseInLocation(xtime.TimeLayout, formatExpire, time.Local)
if err != nil {
return gopay.NULL, nil, fmt.Errorf("time.ParseInLocation(%s, %s),err:%w", xtime.TimeLayout, formatExpire, err)
}
if time.Since(expireTime) > 0 {
// expired
continue
}
eu := int(effectiveTime.Unix())
effectiveTs = append(effectiveTs, eu)
certMap[eu] = v
snCertMap[v.SerialNo] = v.PublicKey
}
sort.Ints(effectiveTs)
// newest cert
newestCert := certMap[effectiveTs[len(effectiveTs)-1]]
return newestCert.SerialNo, snCertMap, nil
}
// failed
return gopay.NULL, nil, fmt.Errorf("GetAndSelectNewestCert() failed or certs is nil: %+v", certs)
}
// 推荐直接使用 client.GetAndSelectNewestCert() 方法
// 获取微信平台证书公钥(获取后自行保存使用,如需定期刷新功能,自行实现)
// 注意事项
// 如果自行实现验证平台签名逻辑的话,需要注意以下事项:
// - 程序实现定期更新平台证书的逻辑,不要硬编码验证应答消息签名的平台证书
// - 定期调用该接口,间隔时间小于12小时
// - 加密请求消息中的敏感信息时,使用最新的平台证书(即:证书启用时间较晚的证书)
//
// 文档说明:https://pay.weixin.qq.com/wiki/doc/apiv3/apis/wechatpay5_1.shtml
func (c *ClientV3) getPlatformCerts() (certs *PlatformCertRsp, err error) {
var (
eg = new(errgroup.Group)
mu sync.Mutex
)
authorization, err := c.authorization(MethodGet, v3GetCerts, nil)
if err != nil {
return nil, err
}
res, _, bs, err := c.doProdGet(c.ctx, v3GetCerts, authorization)
if err != nil {
return nil, err
}
certs = &PlatformCertRsp{Code: Success}
if res.StatusCode != http.StatusOK {
certs.Code = res.StatusCode
certs.Error = string(bs)
return certs, nil
}
certRsp := new(PlatformCert)
if err = json.Unmarshal(bs, certRsp); err != nil {
return nil, fmt.Errorf("json.Unmarshal(%s):%+v", string(bs), err)
}
for _, v := range certRsp.Data {
cert := v
if cert.EncryptCertificate != nil {
ec := cert.EncryptCertificate
eg.Go(func(ctx context.Context) error {
pubKey, err := c.decryptCerts(ec.Ciphertext, ec.Nonce, ec.AssociatedData)
if err != nil {
return err
}
pci := &PlatformCertItem{
EffectiveTime: cert.EffectiveTime,
ExpireTime: cert.ExpireTime,
PublicKey: pubKey,
SerialNo: cert.SerialNo,
}
mu.Lock()
certs.Certs = append(certs.Certs, pci)
mu.Unlock()
return nil
})
}
}
if err = eg.Wait(); err != nil {
return nil, err
}
return certs, nil
}
// 解密加密的证书
func (c *ClientV3) decryptCerts(ciphertext, nonce, additional string) (wxCerts string, err error) {
cipherBytes, _ := base64.StdEncoding.DecodeString(ciphertext)
decrypt, err := aes.GCMDecrypt(cipherBytes, []byte(nonce), []byte(additional), c.ApiV3Key)
if err != nil {
return "", fmt.Errorf("aes.GCMDecrypt, err:%w", err)
}
return string(decrypt), nil
}
func (c *ClientV3) autoCheckCertProc() {
xlog.Info("auto refresh wechat platform public key")
defer func() {
if r := recover(); r != nil {
buf := make([]byte, 64<<10)
buf = buf[:runtime.Stack(buf, false)]
xlog.Errorf("autoCheckCertProc: panic recovered: %s\n%s", r, buf)
// 重启
c.autoCheckCertProc()
}
}()
for {
time.Sleep(time.Hour * 12)
err := retry.Retry(func() error {
serialNo, snCertMap, err := c.GetAndSelectNewestCert()
if err != nil {
return err
}
snPkMap := make(map[string]*rsa.PublicKey)
for sn, cert := range snCertMap {
pubKey, err := xpem.DecodePublicKey([]byte(cert))
if err != nil {
return err
}
snPkMap[sn] = pubKey
}
c.rwMu.Lock()
c.SnCertMap = snPkMap
c.WxSerialNo = serialNo
c.wxPublicKey = snPkMap[serialNo]
c.rwMu.Unlock()
return nil
}, 3, time.Second)
if err != nil {
xlog.Errorf("c.GetAndSelectNewestCert(),err:%+v", err)
continue
}
}
}