Files
wasm-go/tax_eval_api.go
lychang 5e3dac3020 init
2026-05-19 19:42:55 +08:00

352 lines
8.7 KiB
Go

package main
import (
"bytes"
"crypto/tls"
"encoding/base64"
"encoding/json"
"fmt"
"io/ioutil"
"math/rand"
"net/http"
"net/url"
"strconv"
"time"
"github.com/tjfoc/gmsm/sm2"
"github.com/tjfoc/gmsm/sm3"
)
const (
TaxEvalAPIURL = "https://api.cmdp.cn/v1/eval/tax-risk"
TaxEvalQueryURL = "https://api.cmdp.cn/v1/eval/order/%s"
CompanyInfoAPIURL = "https://a.cmdp.cn/cmds/v1/company/info-rest/custom"
)
type TaxEvalRequest struct {
ReqNo string `json:"req_no"`
Callback string `json:"callback,omitempty"`
Detail TaxEvalDetail `json:"detail"`
}
type TaxEvalDetail struct {
FileURL string `json:"file_url,omitempty"`
Data map[string]interface{} `json:"data,omitempty"`
CompanyName string `json:"company_name"`
Period string `json:"period"`
Year string `json:"year"`
IsVerify bool `json:"is_verify,omitempty"`
CIT float64 `json:"cit"`
VAT float64 `json:"vat"`
InputVAT float64 `json:"input_vat"`
OutputVAT float64 `json:"output_vat"`
PreCIT float64 `json:"pre_cit"`
PreVAT float64 `json:"pre_vat"`
PreInputVAT float64 `json:"pre_input_vat"`
PreOutputVAT float64 `json:"pre_output_vat"`
}
type TaxEvalResponse struct {
Code int `json:"code"`
Message string `json:"msg"`
Data struct {
ReqNo string `json:"req_no"`
OrderNo string `json:"order_no"`
} `json:"data"`
}
type TaxEvalQueryResponse struct {
Code int `json:"code"`
Message string `json:"msg"`
Data struct {
Status int `json:"status"`
Detail struct {
Files []string `json:"files"`
Error string `json:"error"`
} `json:"detail"`
} `json:"data"`
}
type APIRequest struct {
UserID string
PrivateKey string
Nonce string
Timestamp string
URI string
Body []byte
}
type APIResponse struct {
StatusCode int
Header http.Header
Body []byte
}
type TaxHealthClient struct {
client *http.Client
userID string
privateKey *sm2.PrivateKey
}
func NewTaxHealthClient(userID string, privateKeyHex string) (*TaxHealthClient, error) {
privateKey, err := sm2.PrivateKeyFromHex(privateKeyHex)
if err != nil {
return nil, fmt.Errorf("解析私钥失败: %v", err)
}
tr := &http.Transport{
TLSClientConfig: &tls.Config{
InsecureSkipVerify: true,
},
}
return &TaxHealthClient{
client: &http.Client{
Transport: tr,
Timeout: 30 * time.Second,
},
userID: userID,
privateKey: privateKey,
}, nil
}
func (c *TaxHealthClient) generateNonce() string {
return strconv.FormatInt(time.Now().UnixNano(), 36) + strconv.Itoa(rand.Intn(10000))
}
func (c *TaxHealthClient) generateTimestamp() string {
return strconv.FormatInt(time.Now().Unix(), 10)
}
func (c *TaxHealthClient) signData(data []byte) (string, error) {
digest := sm3.Sm3Sum(data)
signature, err := c.privateKey.Sign(nil, digest, nil)
if err != nil {
return "", fmt.Errorf("签名失败: %v", err)
}
return base64.StdEncoding.EncodeToString(signature), nil
}
func (c *TaxHealthClient) buildSignature(nonce, timestamp, uri string, body []byte) (string, error) {
signData := c.userID + timestamp + nonce + uri
if body != nil && len(body) > 0 {
signData += string(body)
}
return c.signData([]byte(signData))
}
func (c *TaxHealthClient) doRequest(method, url string, body []byte, headers map[string]string) (*APIResponse, error) {
req, err := http.NewRequest(method, url, bytes.NewBuffer(body))
if err != nil {
return nil, fmt.Errorf("创建请求失败: %v", err)
}
for key, value := range headers {
req.Header.Set(key, value)
}
resp, err := c.client.Do(req)
if err != nil {
return nil, fmt.Errorf("发送请求失败: %v", err)
}
defer resp.Body.Close()
respBody, err := ioutil.ReadAll(resp.Body)
if err != nil {
return nil, fmt.Errorf("读取响应失败: %v", err)
}
return &APIResponse{
StatusCode: resp.StatusCode,
Header: resp.Header,
Body: respBody,
}, nil
}
func (c *TaxHealthClient) TaxEval(request TaxEvalRequest) (*TaxEvalResponse, error) {
nonce := c.generateNonce()
timestamp := c.generateTimestamp()
jsonBody, err := json.Marshal(request)
if err != nil {
return nil, fmt.Errorf("序列化请求失败: %v", err)
}
signature, err := c.buildSignature(nonce, timestamp, TaxEvalAPIURL, jsonBody)
if err != nil {
return nil, fmt.Errorf("生成签名失败: %v", err)
}
headers := map[string]string{
"Content-Type": "application/json",
"Accept": "application/json",
"x-gi-user-id": c.userID,
"x-gi-user-sig": signature,
"x-gi-nonce": nonce,
"x-gi-timestamp": timestamp,
}
resp, err := c.doRequest("POST", TaxEvalAPIURL, jsonBody, headers)
if err != nil {
return nil, err
}
if resp.StatusCode != http.StatusOK {
return nil, fmt.Errorf("API返回状态码 %d: %s", resp.StatusCode, string(resp.Body))
}
var response TaxEvalResponse
err = json.Unmarshal(resp.Body, &response)
if err != nil {
return nil, fmt.Errorf("解析响应失败: %v", err)
}
if response.Code != 200 {
return nil, fmt.Errorf("API错误: %s", response.Message)
}
return &response, nil
}
func (c *TaxHealthClient) QueryResult(orderNo string) (*TaxEvalQueryResponse, error) {
nonce := c.generateNonce()
timestamp := c.generateTimestamp()
queryURL := fmt.Sprintf(TaxEvalQueryURL, orderNo)
signature, err := c.buildSignature(nonce, timestamp, queryURL, nil)
if err != nil {
return nil, fmt.Errorf("生成签名失败: %v", err)
}
headers := map[string]string{
"Accept": "application/json",
"x-gi-user-id": c.userID,
"x-gi-user-sig": signature,
"x-gi-nonce": nonce,
"x-gi-timestamp": timestamp,
}
resp, err := c.doRequest("GET", queryURL, nil, headers)
if err != nil {
return nil, err
}
if resp.StatusCode != http.StatusOK {
return nil, fmt.Errorf("API返回状态码 %d: %s", resp.StatusCode, string(resp.Body))
}
var response TaxEvalQueryResponse
err = json.Unmarshal(resp.Body, &response)
if err != nil {
return nil, fmt.Errorf("解析响应失败: %v", err)
}
if response.Code != 200 {
return nil, fmt.Errorf("API错误: %s", response.Message)
}
return &response, nil
}
func (c *TaxHealthClient) QueryCompanyInfo(companyName string, apiParams []string) (*CompanyInfoResponse, error) {
nonce := c.generateNonce()
timestamp := c.generateTimestamp()
params := url.Values{}
params.Set("name", companyName)
params.Set("api", joinAPIParams(apiParams))
queryURL := fmt.Sprintf("%s?%s", CompanyInfoAPIURL, params.Encode())
signature, err := c.buildSignature(nonce, timestamp, queryURL, nil)
if err != nil {
return nil, fmt.Errorf("生成签名失败: %v", err)
}
headers := map[string]string{
"Accept": "application/json",
"x-gi-user-id": c.userID,
"x-gi-user-sig": signature,
"x-gi-nonce": nonce,
"x-gi-timestamp": timestamp,
}
resp, err := c.doRequest("GET", queryURL, nil, headers)
if err != nil {
return nil, err
}
if resp.StatusCode != http.StatusOK {
return nil, fmt.Errorf("API返回状态码 %d: %s", resp.StatusCode, string(resp.Body))
}
var response CompanyInfoResponse
err = json.Unmarshal(resp.Body, &response)
if err != nil {
return nil, fmt.Errorf("解析响应失败: %v", err)
}
if response.Code != 0 {
return nil, fmt.Errorf("API错误: %s", response.Message)
}
return &response, nil
}
func (c *TaxHealthClient) DownloadFile(fileURL string, localPath string) error {
signature, err := c.buildSignature("", "", fileURL, nil)
if err != nil {
return fmt.Errorf("生成签名失败: %v", err)
}
headers := map[string]string{
"x-gi-user-id": c.userID,
"x-gi-user-sig": signature,
}
resp, err := c.doRequest("GET", fileURL, nil, headers)
if err != nil {
return err
}
if resp.StatusCode != http.StatusOK {
return fmt.Errorf("下载失败,状态码 %d", resp.StatusCode)
}
err = ioutil.WriteFile(localPath, resp.Body, 0644)
if err != nil {
return fmt.Errorf("保存文件失败: %v", err)
}
return nil
}
func joinAPIParams(params []string) string {
result := ""
for i, param := range params {
if i > 0 {
result += ","
}
result += param
}
return result
}
func ValidateTaxEvalRequest(request TaxEvalRequest) error {
if request.ReqNo == "" {
return fmt.Errorf("req_no不能为空")
}
if request.Detail.CompanyName == "" {
return fmt.Errorf("company_name不能为空")
}
if request.Detail.Period == "" {
return fmt.Errorf("period不能为空")
}
if request.Detail.Year == "" {
return fmt.Errorf("year不能为空")
}
if request.Detail.FileURL == "" && request.Detail.Data == nil {
return fmt.Errorf("file_url和data必须填写其中一个")
}
return nil
}