ht_api.go 7.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272
  1. package api
  2. import (
  3. "encoding/base64"
  4. "encoding/json"
  5. "eta/eta_mini_ht_api/common/component/cache"
  6. "eta/eta_mini_ht_api/common/component/config"
  7. logger "eta/eta_mini_ht_api/common/component/log"
  8. "eta/eta_mini_ht_api/common/contants"
  9. "eta/eta_mini_ht_api/common/exception"
  10. "eta/eta_mini_ht_api/common/utils/auth"
  11. "eta/eta_mini_ht_api/common/utils/client"
  12. "eta/eta_mini_ht_api/common/utils/redis"
  13. "fmt"
  14. "io"
  15. "sync"
  16. "time"
  17. )
  18. const (
  19. clientSuitInfoUrl = "/wt/front/api/open/api/getClientSuitInfo"
  20. accessTokenUrl = "/api/openapi/authless/token"
  21. )
  22. var (
  23. htFacadeOnce sync.Once
  24. htFacade *HTApi
  25. )
  26. type HTApi struct {
  27. htConfig *config.HTBizConfig
  28. // HTTP请求客户端
  29. client *client.HttpClient
  30. redisUtils *cache.RedisCache
  31. }
  32. func GetInstance() *HTApi {
  33. htFacadeOnce.Do(func() {
  34. htFacade = &HTApi{
  35. htConfig: config.GetConfig(contants.HT).(*config.HTBizConfig),
  36. client: client.DefaultClient(),
  37. redisUtils: cache.GetInstance()}
  38. })
  39. return htFacade
  40. }
  41. type ClientSuitInfoReq struct {
  42. ClientName string `json:"client_name"`
  43. IdKind int `json:"id_kind"`
  44. IdNo string `json:"id_no"`
  45. }
  46. type CustomerRiskReq struct {
  47. MobileTel string `json:"mobile_tel"`
  48. ClientName string `json:"client_name"`
  49. IdKind int `json:"id_kind"`
  50. IdNo string `json:"id_no"`
  51. CreateTime string `json:"create_time"`
  52. LoginType string `json:"login_type"`
  53. }
  54. func (f *HTApi) EnCodeData(req CustomerRiskReq) (token string, err error) {
  55. publicKey, err := auth.ParsePublicKey(f.htConfig.GetWebhookPublicKey())
  56. if err != nil {
  57. logger.Error("解析公钥失败:%v", err)
  58. err = exception.New(exception.SysError)
  59. return
  60. }
  61. str, err := json.Marshal(req)
  62. if err != nil {
  63. logger.Error("json序列化失败:%v", err)
  64. err = exception.New(exception.SysError)
  65. return
  66. }
  67. rsa, err := auth.EncryptWithRSA(publicKey, str)
  68. if err != nil {
  69. logger.Error("公钥加密失败:%v", err)
  70. err = exception.New(exception.SysError)
  71. return
  72. }
  73. token = base64.StdEncoding.EncodeToString(rsa)
  74. return
  75. }
  76. type EncodeReq struct {
  77. Param string `json:"param"`
  78. }
  79. func (f *HTApi) getToken() (token string, err error) {
  80. accessToken := redis.GenerateCAPAccessTokenKey()
  81. token = f.redisUtils.GetString(accessToken)
  82. var tokenInfo TokenInfo
  83. if token == "" {
  84. tokenInfo, err = f.GetAccessToken()
  85. if err != nil {
  86. logger.Error("获取token失败%v", err)
  87. return
  88. }
  89. var parseErr error
  90. expireTime, parseErr := time.Parse(time.DateTime, tokenInfo.ExpiresAt)
  91. if parseErr != nil {
  92. logger.Error("解析过期时间失败:%v", parseErr)
  93. err = parseErr
  94. return
  95. }
  96. duration := expireTime.Sub(time.Now()).Seconds()
  97. token = tokenInfo.AccessToken
  98. _ = f.redisUtils.SetString(accessToken, tokenInfo.AccessToken, int(duration)-5)
  99. }
  100. return
  101. }
  102. func (f *HTApi) GetCustomerRiskLevelInfo(req ClientSuitInfoReq) (info CustomerAccountInfo, err error) {
  103. url := f.htConfig.GetAccountApiUrl() + clientSuitInfoUrl
  104. token, err := f.getToken()
  105. if err != nil {
  106. return
  107. }
  108. publicKey, err := auth.ParsePublicKey(f.htConfig.GetWebhookPublicKey())
  109. if err != nil {
  110. logger.Error("解析公钥失败:%v", err)
  111. }
  112. reqStr, err := json.Marshal(req)
  113. encodeData, _ := auth.EncryptWithRSA(publicKey, reqStr)
  114. resp, err := f.client.PostWithAuth(url, EncodeReq{
  115. Param: base64.StdEncoding.EncodeToString(encodeData),
  116. }, token)
  117. if err != nil {
  118. logger.Error("调用CAP customerRiskInfo接口失败:[%v]", err)
  119. return
  120. }
  121. defer func(Body io.ReadCloser) {
  122. closeErr := Body.Close()
  123. if closeErr != nil {
  124. logger.Error("关闭Response失败:%v", closeErr)
  125. }
  126. }(resp.Body)
  127. body, _ := io.ReadAll(resp.Body)
  128. return decodeResponse(body)
  129. }
  130. type AccessTokenReq struct {
  131. AppId string `json:"app_id"`
  132. SecretKey string `json:"secret_key"`
  133. }
  134. func (f *HTApi) GetAccessToken() (token TokenInfo, err error) {
  135. url := f.htConfig.GetAccountApiUrl() + accessTokenUrl
  136. req := AccessTokenReq{
  137. AppId: f.htConfig.GetAppId(),
  138. SecretKey: f.htConfig.GetSecretKey(),
  139. }
  140. resp, err := f.client.Post(url, req)
  141. if err != nil {
  142. logger.Error("调用CAP accessToken接口失败:[%v]", err)
  143. return
  144. }
  145. defer func(Body io.ReadCloser) {
  146. closeErr := Body.Close()
  147. if closeErr != nil {
  148. logger.Error("关闭Response失败:%v", closeErr)
  149. }
  150. }(resp.Body)
  151. body, _ := io.ReadAll(resp.Body)
  152. var tokenResp AccessTokenResp
  153. err = json.Unmarshal(body, &tokenResp)
  154. if err != nil {
  155. logger.Warn("[cap 接口调用]解析cap token接口应答失败:%v", err)
  156. err = exception.New(exception.GetCapTokenFailed)
  157. return
  158. }
  159. if tokenResp.Error.ErrorNo != "0" {
  160. logger.Warn("[cap 接口调用] 获取token失败:[code:%v, msg:%v, path:%v]", tokenResp.Error.ErrorNo, tokenResp.Error.ErrorInfo, tokenResp.Error.ErrorPathInfo)
  161. err = exception.NewWithException(exception.GetCapTokenFailed, tokenResp.Error.ErrorInfo)
  162. return
  163. }
  164. token = TokenInfo{
  165. AccessToken: tokenResp.Data.AccessToken,
  166. ExpiresAt: tokenResp.Data.ExpiresAt,
  167. }
  168. return
  169. }
  170. type AccessTokenResp struct {
  171. Error Error `json:"error"`
  172. Data AccessTokenData `json:"data"`
  173. }
  174. type Error struct {
  175. ErrorNo string `json:"error_no"`
  176. ErrorInfo string `json:"error_info"`
  177. ErrorPathInfo string `json:"error_path_info"`
  178. }
  179. type AccessTokenData struct {
  180. AccessToken string `json:"accessToken"`
  181. ExpiresAt string `json:"expiresAt"`
  182. }
  183. type TokenInfo struct {
  184. AccessToken string
  185. ExpiresAt string
  186. }
  187. type CustomerRiskInfoResp struct {
  188. Error Error `json:"error"`
  189. Data string `json:"data"`
  190. }
  191. type SyncCustomerRiskLevelReq struct {
  192. CustInfo CustInfo `json:"custInfo"`
  193. RiskInfo RiskInfo `json:"riskInfo"`
  194. }
  195. type CustInfo struct {
  196. MobileTel string `json:"mobile_tel"`
  197. ClientName string `json:"client_name"`
  198. IdKind string `json:"id_kind"`
  199. IdNo string `json:"id_no"`
  200. IdBeginDate string `json:"id_begindate"`
  201. IdEndDate string `json:"id_enddate"`
  202. }
  203. type RiskInfo struct {
  204. CorpBeginDate string `json:"corp_begin_date"`
  205. CorpEndDate string `json:"corp_end_date"`
  206. UserInvestTerm string `json:"user_invest_term"`
  207. UserInvestKind string `json:"user_invest_kind"`
  208. CorpRiskLevel string `json:"corp_risk_level"`
  209. }
  210. type CustomerAccountInfo struct {
  211. CustInfo CustInfo `json:"custInfo"`
  212. RiskInfo RiskInfo `json:"riskInfo"`
  213. }
  214. func decodeResponse(resp []byte) (info CustomerAccountInfo, err error) {
  215. customerRiskInfoResp := new(CustomerRiskInfoResp)
  216. err = json.Unmarshal(resp, &customerRiskInfoResp)
  217. if err != nil {
  218. logger.Error("customerRiskInfoResp解析失败: %v", err)
  219. return
  220. }
  221. if err != nil {
  222. logger.Warn("[cap 接口调用]解析客户风险信息接口应答失败:%v", err)
  223. err = exception.New(exception.GetCapTokenFailed)
  224. return
  225. }
  226. if customerRiskInfoResp.Error.ErrorNo != "0" {
  227. logger.Warn("[cap 接口调用] 获取客户风险信息失败:[code:%v, msg:%v, path:%v]", customerRiskInfoResp.Error.ErrorNo, customerRiskInfoResp.Error.ErrorInfo, customerRiskInfoResp.Error.ErrorPathInfo)
  228. err = exception.NewWithException(exception.GetCustomerRiskInfoFailed, customerRiskInfoResp.Error.ErrorInfo)
  229. return
  230. }
  231. privateKey, err := auth.ParsePrivateKey(htFacade.htConfig.GetWebhookPrivateKey())
  232. if err != nil {
  233. logger.Error("解析私钥失败: %v", err)
  234. return
  235. }
  236. decodeData, err := auth.DecryptWithRSA(privateKey, customerRiskInfoResp.Data)
  237. if err != nil {
  238. logger.Error("解密请求体失败: %v", err)
  239. return
  240. }
  241. fmt.Printf("解密后的请求: %v", string(decodeData))
  242. err = json.Unmarshal(decodeData, &info)
  243. if err != nil {
  244. logger.Error("customerInfo解析失败: %v", err)
  245. return
  246. }
  247. return
  248. }