zjt_httpclient.go 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104
  1. package thirdparty
  2. import (
  3. "bytes"
  4. "crypto/sha1"
  5. "gd_management/common.in/config"
  6. "encoding/hex"
  7. "encoding/json"
  8. "fmt"
  9. "io/ioutil"
  10. "net/http"
  11. "strings"
  12. "time"
  13. "gd_management/common.in/utils"
  14. "go.uber.org/zap"
  15. )
  16. type ZjtHttpData struct {
  17. Status int `json:"status"`
  18. Message string `json:"message"`
  19. Data string `json:"data"`
  20. }
  21. func SHA1(data []byte) []byte {
  22. h := sha1.New()
  23. h.Write(data)
  24. return h.Sum(nil)
  25. }
  26. func AESSHA1PRNG(keyBytes []byte, encryptLength int) ([]byte, error) {
  27. hashs := SHA1(SHA1(keyBytes))
  28. maxLen := len(hashs)
  29. realLen := encryptLength / 8
  30. if realLen > maxLen {
  31. return nil, fmt.Errorf("%s", "error")
  32. }
  33. return hashs[0:realLen], nil
  34. }
  35. func ZjtHttpPost(api string, data map[string]string) (m ZjtHttpData, err error) {
  36. defer func() {
  37. l.Info("thirdparty",
  38. zap.String("api", api),
  39. zap.String("request", utils.MarshalJsonString(data)),
  40. zap.String("response", utils.MarshalJsonString(m)))
  41. }()
  42. data["authorizationCode"] = config.Conf.ThirdPart.ZjtAuthorizationCode
  43. jsonData, err := json.Marshal(data)
  44. if err != nil {
  45. return
  46. }
  47. key, _ := AESSHA1PRNG([]byte(config.Conf.ThirdPart.ZjtCryptoKey), 128)
  48. paramsByte, err := config.AesEncrypt(string(jsonData), string(key))
  49. if err != nil {
  50. return m, err
  51. }
  52. params := hex.EncodeToString(paramsByte)
  53. params = strings.ToUpper(params)
  54. var r http.Request
  55. r.ParseForm()
  56. r.Form.Add("userno", config.Conf.ThirdPart.ZjtUserNo)
  57. r.Form.Add("querydata", params)
  58. params = r.Form.Encode()
  59. client := &http.Client{}
  60. client.Timeout = 60 * time.Second
  61. req, err := http.NewRequest("POST", api, bytes.NewBuffer([]byte(params)))
  62. if err != nil {
  63. return m, err
  64. }
  65. req.Header.Add("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8")
  66. resp, err := client.Do(req)
  67. if err != nil {
  68. return m, err
  69. }
  70. if resp.StatusCode != http.StatusOK {
  71. return m, fmt.Errorf("wrong status code: %d", resp.StatusCode)
  72. }
  73. defer resp.Body.Close()
  74. result, err := ioutil.ReadAll(resp.Body)
  75. if err != nil {
  76. return m, err
  77. }
  78. json.Unmarshal(result, &m)
  79. if m.Status == 1 && m.Data != "" {
  80. r, err := hex.DecodeString(m.Data)
  81. if err != nil {
  82. return m, err
  83. }
  84. respData, err := config.AesDecrypt(r, key)
  85. m.Data = string(respData)
  86. return m, err
  87. }
  88. return m, err
  89. }