/
client.go
262 lines (208 loc) · 6.07 KB
/
client.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
package ysepay
import (
"context"
"crypto"
"encoding/base64"
"encoding/json"
"errors"
"fmt"
"io"
"net/http"
"net/url"
"strings"
"github.com/google/uuid"
"github.com/tidwall/gjson"
"github.com/shenghui0779/sdk-go/lib"
lib_crypto "github.com/shenghui0779/sdk-go/lib/crypto"
"github.com/shenghui0779/sdk-go/lib/curl"
"github.com/shenghui0779/sdk-go/lib/value"
)
// Client 银盛支付客户端
type Client struct {
host string
mchNO string
desKey string
prvKey *lib_crypto.PrivateKey
pubKey *lib_crypto.PublicKey
httpCli curl.Client
logger func(ctx context.Context, data map[string]string)
}
// MchNO 返回商户号
func (c *Client) MchNO() string {
return c.mchNO
}
func (c *Client) url(api string) string {
var builder strings.Builder
builder.WriteString(c.host)
builder.WriteString("/api/")
builder.WriteString(api)
return builder.String()
}
// Encrypt 敏感数据DES加密
func (c *Client) Encrypt(plain string) (string, error) {
b, err := lib_crypto.DESEncryptECB([]byte(c.desKey), []byte(plain))
if err != nil {
return "", err
}
return base64.StdEncoding.EncodeToString(b), nil
}
// MustEncrypt 敏感数据DES加密;若发生错误,则Panic
func (c *Client) MustEncrypt(plain string) string {
b, err := lib_crypto.DESEncryptECB([]byte(c.desKey), []byte(plain))
if err != nil {
panic(err)
}
return base64.StdEncoding.EncodeToString(b)
}
// Decrypt 敏感数据DES解密
func (c *Client) Decrypt(cipher string) (string, error) {
b, err := base64.StdEncoding.DecodeString(cipher)
if err != nil {
return "", err
}
plain, err := lib_crypto.DESEncryptECB([]byte(c.desKey), b)
if err != nil {
return "", err
}
return string(plain), nil
}
// PostForm 发送POST表单请求
func (c *Client) PostForm(ctx context.Context, api, serviceNO string, bizData value.V) (gjson.Result, error) {
reqURL := c.url(api)
log := lib.NewReqLog(http.MethodPost, reqURL)
defer log.Do(ctx, c.logger)
form, err := c.reqForm(uuid.NewString(), serviceNO, bizData)
if err != nil {
return lib.Fail(err)
}
log.SetReqBody(form)
resp, err := c.httpCli.Do(ctx, http.MethodPost, reqURL, []byte(form), curl.WithHeader(curl.HeaderContentType, curl.ContentForm))
if err != nil {
return lib.Fail(err)
}
defer resp.Body.Close()
log.SetRespHeader(resp.Header)
log.SetStatusCode(resp.StatusCode)
if resp.StatusCode != http.StatusOK {
return lib.Fail(fmt.Errorf("HTTP Request Error, StatusCode = %d", resp.StatusCode))
}
b, err := io.ReadAll(resp.Body)
if err != nil {
return lib.Fail(err)
}
log.SetRespBody(string(b))
return c.verifyResp(b)
}
// reqForm 生成请求表单
func (c *Client) reqForm(reqID, serviceNO string, bizData value.V) (string, error) {
if c.prvKey == nil {
return "", errors.New("private key is nil (forgotten configure?)")
}
v := value.V{}
v.Set("requestId", reqID)
v.Set("srcMerchantNo", c.mchNO)
v.Set("version", "v2.0.0")
v.Set("charset", "UTF-8")
v.Set("serviceNo", serviceNO)
v.Set("signType", "RSA")
if len(bizData) != 0 {
bizByte, err := json.Marshal(bizData)
if err != nil {
return "", err
}
v.Set("bizReqJson", string(bizByte))
}
sign, err := c.prvKey.Sign(crypto.SHA1, []byte(v.Encode("=", "&", value.WithIgnoreKeys("sign"), value.WithEmptyMode(value.EmptyIgnore))))
if err != nil {
return "", err
}
v.Set("sign", base64.StdEncoding.EncodeToString(sign))
return v.Encode("=", "&", value.WithEmptyMode(value.EmptyIgnore), value.WithKVEscape()), nil
}
func (c *Client) verifyResp(body []byte) (gjson.Result, error) {
if c.pubKey == nil {
return lib.Fail(errors.New("public key is nil (forgotten configure?)"))
}
ret := gjson.ParseBytes(body)
sign, err := base64.StdEncoding.DecodeString(ret.Get("sign").String())
if err != nil {
return lib.Fail(err)
}
v := value.V{}
v.Set("requestId", ret.Get("requestId").String())
v.Set("code", ret.Get("code").String())
v.Set("msg", ret.Get("msg").String())
v.Set("bizResponseJson", ret.Get("bizResponseJson").String())
err = c.pubKey.Verify(crypto.SHA1, []byte(v.Encode("=", "&", value.WithEmptyMode(value.EmptyIgnore))), sign)
if err != nil {
return lib.Fail(err)
}
if code := ret.Get("code").String(); code != SysOK {
if code == SysAccepting {
return lib.Fail(ErrSysAccepting)
}
return lib.Fail(fmt.Errorf("%s | %s", code, ret.Get("msg").String()))
}
return ret.Get("bizResponseJson"), nil
}
// VerifyNotify 解析并验证异步回调通知,返回BizJSON数据
func (c *Client) VerifyNotify(form url.Values) (gjson.Result, error) {
if c.pubKey == nil {
return lib.Fail(errors.New("public key is nil (forgotten configure?)"))
}
sign, err := base64.StdEncoding.DecodeString(form.Get("sign"))
if err != nil {
return lib.Fail(err)
}
v := value.V{}
v.Set("requestId", form.Get("requestId"))
v.Set("version", form.Get("version"))
v.Set("charset", form.Get("charset"))
v.Set("serviceNo", form.Get("serviceNo"))
v.Set("signType", form.Get("signType"))
v.Set("bizResponseJson", form.Get("bizResponseJson"))
err = c.pubKey.Verify(crypto.SHA1, []byte(v.Encode("=", "&", value.WithEmptyMode(value.EmptyIgnore))), sign)
if err != nil {
return lib.Fail(err)
}
return gjson.Parse(form.Get("bizResponseJson")), nil
}
// Option 自定义设置项
type Option func(c *Client)
// WithHttpCli 设置自定义 HTTP Client
func WithHttpCli(cli *http.Client) Option {
return func(c *Client) {
c.httpCli = curl.NewHTTPClient(cli)
}
}
// WithPrivateKey 设置商户RSA私钥
func WithPrivateKey(key *lib_crypto.PrivateKey) Option {
return func(c *Client) {
c.prvKey = key
}
}
// WithPublicKey 设置平台RSA公钥
func WithPublicKey(key *lib_crypto.PublicKey) Option {
return func(c *Client) {
c.pubKey = key
}
}
// WithLogger 设置日志记录
func WithLogger(fn func(ctx context.Context, data map[string]string)) Option {
return func(c *Client) {
c.logger = fn
}
}
// NewClient 生成银盛支付客户端
func NewClient(mchNO, desKey string, options ...Option) *Client {
c := &Client{
host: "https://eqt.ysepay.com",
mchNO: mchNO,
desKey: desKey,
httpCli: curl.NewDefaultClient(),
}
for _, fn := range options {
fn(c)
}
return c
}