-
Notifications
You must be signed in to change notification settings - Fork 0
/
client.go
453 lines (382 loc) · 13.6 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
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
package piaotong
import (
"context"
"encoding/base64"
"encoding/json"
"errors"
"fmt"
"math/rand"
"strings"
"time"
"github.com/go-resty/resty/v2"
)
var ErrInvalidSignature = errors.New("invalid signature")
var timezoneBeijing = time.FixedZone("Beijing Time", int(8*time.Hour.Seconds()))
type Client struct {
platformCode string
platformName string
platformPrivateKey []byte
piaotongPublicKey []byte
tripleDESKey []byte
restyClient *resty.Client
rand *rand.Rand
}
type Config struct {
Host string
PlatformCode string
PlatformName string // 平台简称
PlatformPrivateKey string // PKCS #1, PEM form
PiaotongPublicKey string // PKCS #1, PEM form
TripleDESKey string
}
func New(config Config) *Client {
restyClient := resty.New().
SetBaseURL(config.Host)
return &Client{
platformCode: config.PlatformCode,
platformName: config.PlatformName,
platformPrivateKey: []byte(config.PlatformPrivateKey),
piaotongPublicKey: []byte(config.PiaotongPublicKey),
tripleDESKey: []byte(config.TripleDESKey),
restyClient: restyClient,
rand: rand.New(rand.NewSource(time.Now().UnixNano())), // nolint: gosec
}
}
func (c *Client) PlatformCode() string {
return c.platformCode
}
func (c *Client) PlatformName() string {
return c.platformName
}
// GenerateSerialNo returns a serialNo specified in the API doc.
func (c *Client) GenerateSerialNo() string {
ts := time.Now().In(timezoneBeijing).Format("20060102150405.000")
ts = strings.Replace(ts, ".", "", 1)
suffix := fmt.Sprintf("%05d", c.rand.Intn(100_000)) // nolint: gosec
return strings.Join([]string{c.platformName, ts, suffix}, "")
}
func (c *Client) GenerateInvoiceReqSerialNo() string {
ts := time.Now().In(timezoneBeijing).Format("20060102150405")
suffix := fmt.Sprintf("%02d", c.rand.Intn(100)) // nolint: gosec
return strings.Join([]string{c.platformName, ts, suffix}, "")
}
type (
OpenBlueInvoiceRequest struct {
TaxpayerNum string `json:"taxpayerNum"`
InvoiceReqSerialNo string `json:"invoiceReqSerialNo"`
BuyerName string `json:"buyerName"`
BuyerTaxpayerNum string `json:"buyerTaxpayerNum,omitempty"`
BuyerAddress string `json:"buyerAddress,omitempty"`
BuyerTel string `json:"buyerTel,omitempty"`
BuyerBankName string `json:"buyerBankName,omitempty"`
BuyerBankAccount string `json:"buyerBankAccount,omitempty"`
SellerAddress string `json:"sellerAddress,omitempty"`
SellerTel string `json:"sellerTel,omitempty"`
SellerBankName string `json:"sellerBankName,omitempty"`
SellerBankAccount string `json:"sellerBankAccount,omitempty"`
ItemName string `json:"itemName,omitempty"`
CasherName string `json:"casherName,omitempty"`
ReviewerName string `json:"reviewerName,omitempty"`
DrawerName string `json:"drawerName,omitempty"`
TakerName string `json:"takerName,omitempty"`
TakerTel string `json:"takerTel,omitempty"`
TakerEmail string `json:"takerEmail,omitempty"`
SpecialInvoiceKind string `json:"specialInvoiceKind,omitempty"`
Remark string `json:"remark,omitempty"`
DefinedData string `json:"definedData,omitempty"`
TradeNo string `json:"tradeNo,omitempty"`
ExtensionNum string `json:"extensionNum,omitempty"`
MachineCode string `json:"machineCode,omitempty"`
AgentInvoiceFlag string `json:"agentInvoiceFlag,omitempty"`
ShopNum string `json:"shopNum,omitempty"`
ItemList []*GoodsItem `json:"itemList"`
}
GoodsItem struct {
GoodsName string `json:"goodsName"`
TaxClassificationCode string `json:"taxClassificationCode"`
SpecificationModel string `json:"specificationModel,omitempty"`
MeteringUnit string `json:"meteringUnit,omitempty"`
Quantity string `json:"quantity,omitempty"`
IncludeTaxFlag string `json:"includeTaxFlag,omitempty"`
UnitPrice string `json:"unitPrice,omitempty"`
InvoiceAmount string `json:"invoiceAmount"`
TaxRateValue string `json:"taxRateValue"`
TaxRateAmount string `json:"taxRateAmount,omitempty"`
DiscountAmount string `json:"discountAmount,omitempty"`
DiscountTaxRateAmount string `json:"discountTaxRateAmount,omitempty"`
DeductionAmount string `json:"deductionAmount,omitempty"`
PreferentialPolicyFlag string `json:"preferentialPolicyFlag,omitempty"`
ZeroTaxFlag string `json:"zeroTaxFlag,omitempty"`
VatSpecialManage string `json:"vatSpecialManage,omitempty"`
}
OpenBlueInvoiceResponse struct {
InvoiceReqSerialNo string `json:"invoiceReqSerialNo"`
QRCodePath string `json:"qrCodePath"` // base64 decoded
QRCode string `json:"qrCode"` // base64 encoded
}
)
func (c *Client) OpenBlueInvoice(
ctx context.Context, req *OpenBlueInvoiceRequest,
) (*OpenBlueInvoiceResponse, error) {
resp := &OpenBlueInvoiceResponse{}
err := c.request(ctx, "/tp/openapi/invoiceBlue.pt", req, resp)
if err != nil {
return nil, err
}
qrcodePath, err := base64DecodeString(resp.QRCodePath)
if err != nil {
return nil, err
}
resp.QRCodePath = string(qrcodePath)
return resp, nil
}
type (
OpenRedInvoiceRequest struct {
TaxpayerNum string `json:"taxpayerNum"`
InvoiceReqSerialNo string `json:"invoiceReqSerialNo"`
InvoiceCode string `json:"invoiceCode"`
InvoiceNo string `json:"invoiceNo"`
RedReason string `json:"redReason"`
Amount string `json:"amount"`
DefinedData string `json:"definedData,omitempty"`
}
OpenRedInvoiceResponse struct {
InvoiceReqSerialNo string `json:"invoiceReqSerialNo"`
QRCodePath string `json:"qrCodePath"` // base64 decoded
QRCode string `json:"qrCode,omitempty"` // base64 encoded
}
)
func (c *Client) OpenRedInvoice(
ctx context.Context, req *OpenRedInvoiceRequest,
) (*OpenRedInvoiceResponse, error) {
resp := &OpenRedInvoiceResponse{}
err := c.request(ctx, "/tp/openapi/invoiceRed.pt", req, resp)
if err != nil {
return nil, err
}
qrcodePath, err := base64DecodeString(resp.QRCodePath)
if err != nil {
return nil, err
}
resp.QRCodePath = string(qrcodePath)
return resp, nil
}
type (
QueryInvoiceRequest struct {
TaxpayerNum string `json:"taxpayerNum"`
InvoiceReqSerialNo string `json:"invoiceReqSerialNo"`
}
QueryInvoiceResponse struct {
TaxpayerNum string `json:"taxpayerNum"`
InvoiceReqSerialNo string `json:"invoiceReqSerialNo"`
InvoiceType string `json:"invoiceType"`
Code string `json:"code"`
Msg string `json:"msg"`
TradeNo string `json:"tradeNo,omitempty"`
SecurityCode string `json:"securityCode,omitempty"`
QRCode string `json:"qrCode,omitempty"`
InvoiceCode string `json:"invoiceCode,omitempty"`
InvoiceNo string `json:"invoiceNo,omitempty"`
InvoiceDate string `json:"invoiceDate,omitempty"`
NoTaxAmount string `json:"noTaxAmount,omitempty"`
TaxAmount string `json:"taxAmount,omitempty"`
InvoiceLayoutFileType string `json:"invoiceLayoutFileType,omitempty"`
InvoicePdf string `json:"invoicePdf,omitempty"`
DownloadURL string `json:"downloadUrl,omitempty"` // base64 decoded
VatPlatformInvPreviewURL string `json:"vatPlatformInvPreviewUrl,omitempty"` // base64 decoded
ExtensionNum string `json:"extensionNum,omitempty"`
DiskNo string `json:"diskNo,omitempty"`
InvPreviewQrcodePath string `json:"invPreviewQrcodePath,omitempty"` // base64 decoded
InvPreviewQrcode string `json:"invPreviewQrcode,omitempty"` // base64 encoded
}
)
func (c *Client) QueryInvoice(
ctx context.Context, req *QueryInvoiceRequest,
) (*QueryInvoiceResponse, error) {
resp := &QueryInvoiceResponse{}
err := c.request(ctx, "/tp/openapi/queryInvoice.pt", req, resp)
if err != nil {
return nil, err
}
if resp.DownloadURL != "" {
downloadURL, err := base64DecodeString(resp.DownloadURL)
if err != nil {
return nil, err
}
resp.DownloadURL = string(downloadURL)
}
if resp.VatPlatformInvPreviewURL != "" {
vatPlatformInvPreviewURL, err := base64DecodeString(resp.VatPlatformInvPreviewURL)
if err != nil {
return nil, err
}
resp.VatPlatformInvPreviewURL = string(vatPlatformInvPreviewURL)
}
if resp.InvPreviewQrcodePath != "" {
invPreviewQrcodePath, err := base64DecodeString(resp.InvPreviewQrcodePath)
if err != nil {
return nil, err
}
resp.InvPreviewQrcodePath = string(invPreviewQrcodePath)
}
return resp, nil
}
type (
RegisterRequest struct {
TaxpayerNum string `json:"taxpayerNum"`
EnterpriseName string `json:"enterpriseName"`
LegalPersonName string `json:"legalPersonName"`
ContactsName string `json:"contactsName"`
ContactsEmail string `json:"contactsEmail"`
ContactsPhone string `json:"contactsPhone"`
RegionCode string `json:"regionCode"`
CityName string `json:"cityName"`
EnterpriseAddress string `json:"enterpriseAddress"`
TaxRegistrationCertificate string `json:"taxRegistrationCertificate"`
TaxControlDeviceType string `json:"taxControlDeviceType"`
}
RegisterResponse struct {
TaxpayerNum string `json:"taxpayerNum"`
EnterpriseName string `json:"enterpriseName"`
}
)
func (c *Client) Register(
ctx context.Context, req *RegisterRequest,
) (*RegisterResponse, error) {
resp := &RegisterResponse{}
err := c.request(ctx, "/tp/openapi/register.pt", req, resp)
if err != nil {
return nil, err
}
return resp, nil
}
type (
GetEnterpriseInfoRequest struct {
TaxpayerNum string `json:"taxpayerNum"`
EnterpriseName string `json:"enterpriseName"`
}
GetEnterpriseInfoResponse struct {
TaxpayerNum string `json:"taxpayerNum"`
EnterpriseName string `json:"enterpriseName"`
LegalPersonName string `json:"legalPersonName"`
ContactsName string `json:"contactsName"`
ContactsEmail string `json:"contactsEmail"`
ContactsPhone string `json:"contactsPhone"`
RegionCode string `json:"regionCode"`
CityName string `json:"cityName"`
EnterpriseAddress string `json:"enterpriseAddress"`
InvitationCode string `json:"invitationCode"`
ReviewStatus string `json:"reviewStatus"`
ReviewOpinion string `json:"reviewOpinion"`
TerminalType string `json:"terminalType"`
InvoiceKind string `json:"invoiceKind"`
InvoiceLayoutFileType string `json:"invoiceLayoutFileType"`
BlockchainInvSingleQuota string `json:"blockchainInvSingleQuota"`
BlockchainInvDailyQuota string `json:"blockchainInvDailyQuota"`
BlockchainInvMonthlyQuota string `json:"blockchainInvMonthlyQuota"`
ServiceStatus string `json:"serviceStatus"`
TerminalList []*TerminalItem `json:"terminalList"`
}
TerminalItem struct {
DiskType string `json:"diskType"`
ExtensionNum string `json:"extensionNum"`
MachineCode string `json:"machineCode"`
Available string `json:"available"`
ServiceStartTime string `json:"serviceStartTime"`
ServiceEndTime string `json:"serviceEndTime"`
}
)
func (c *Client) GetEnterpriseInfo(
ctx context.Context, req *GetEnterpriseInfoRequest,
) (*GetEnterpriseInfoResponse, error) {
resp := &GetEnterpriseInfoResponse{}
err := c.request(ctx, "/tp/openapi/getEnterpriseInfo.pt", req, resp)
if err != nil {
return nil, err
}
return resp, nil
}
func (c *Client) request(ctx context.Context, url string, reqContent, respPtr any) error {
reqBody, err := c.buildRequest(reqContent)
if err != nil {
return err
}
respBody := &Response{}
err = c.post(ctx, url, reqBody, respBody)
if err != nil {
return err
}
err = c.VerifyResponse(respBody)
if err != nil {
return err
}
if respBody.isError() {
return respBody.toError()
}
err = c.decryptAndUnmarshalResponse(respBody.Content, respPtr)
if err != nil {
return err
}
return nil
}
func (c *Client) buildRequest(content any) (*Request, error) {
data, err := json.Marshal(content)
if err != nil {
return nil, err
}
encrypted, err := c.Encrypt(data)
if err != nil {
return nil, err
}
req := &Request{
PlatformCode: c.platformCode,
SignType: "RSA",
Format: "JSON",
Timestamp: time.Now().In(timezoneBeijing).Format("2006-01-02 15:04:05"),
Version: "1.0",
SerialNo: c.GenerateSerialNo(),
Content: encrypted,
}
err = c.SignRequest(req)
if err != nil {
return nil, err
}
return req, nil
}
func (c *Client) decryptAndUnmarshalResponse(content string, v any) error {
data, err := c.Decrypt(content)
if err != nil {
return err
}
err = json.Unmarshal(data, v)
if err != nil {
return err
}
return nil
}
func (c *Client) post(ctx context.Context, url string, body, resultPtr any) error {
req := c.restyClient.R().
SetContext(ctx).
SetHeader("Content-Type", "application/json").
ForceContentType("application/json")
resp, err := req.SetBody(body).Post(url)
if err != nil {
return err
}
if resp.IsError() {
return fmt.Errorf("http status: %s, body: %s", resp.Status(), resp.Body())
}
if resultPtr != nil {
err = json.Unmarshal(resp.Body(), resultPtr)
if err != nil {
return err
}
}
return nil
}
func base64EncodeToString(data []byte) string {
return base64.StdEncoding.EncodeToString(data)
}
func base64DecodeString(s string) ([]byte, error) {
return base64.StdEncoding.DecodeString(s)
}