蛋蛋星球RabbitMq消费项目
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 
 

263 lines
8.3 KiB

  1. package consume
  2. import (
  3. "applet/app/cfg"
  4. "applet/app/db"
  5. utils2 "applet/app/utils"
  6. "applet/app/utils/logx"
  7. "applet/consume/md"
  8. "code.fnuoos.com/EggPlanet/egg_models.git/src/implement"
  9. "code.fnuoos.com/EggPlanet/egg_models.git/src/model"
  10. "code.fnuoos.com/EggPlanet/egg_system_rules.git"
  11. "code.fnuoos.com/EggPlanet/egg_system_rules.git/enum"
  12. md3 "code.fnuoos.com/EggPlanet/egg_system_rules.git/md"
  13. "code.fnuoos.com/EggPlanet/egg_system_rules.git/rule"
  14. md2 "code.fnuoos.com/EggPlanet/egg_system_rules.git/rule/egg_energy/md"
  15. "code.fnuoos.com/EggPlanet/egg_system_rules.git/svc/sys_cfg"
  16. "code.fnuoos.com/go_rely_warehouse/zyos_go_mq.git/rabbit"
  17. "context"
  18. "encoding/json"
  19. "errors"
  20. "fmt"
  21. "github.com/go-pay/gopay"
  22. "github.com/go-pay/gopay/alipay"
  23. "github.com/go-pay/xlog"
  24. "github.com/streadway/amqp"
  25. "time"
  26. )
  27. func EggFinWithdrawApplyDataConsume(queue md.MqQueue) {
  28. fmt.Println(">>>>>>>>>>>>EggFinWithdrawApplyDataConsume>>>>>>>>>>>>")
  29. ch, err := rabbit.Cfg.Pool.GetChannel()
  30. if err != nil {
  31. logx.Error(err)
  32. return
  33. }
  34. defer ch.Release()
  35. //1、将自己绑定到交换机上
  36. ch.Bind(queue.Name, queue.ExchangeName, queue.RoutKey)
  37. //2、取出数据进行消费
  38. ch.Qos(1)
  39. delivery := ch.Consume(queue.Name, false)
  40. egg_system_rules.Init(cfg.RedisAddr)
  41. var alipayStruct *InitAlipayStruct
  42. client, err := InitAlipay(alipayStruct)
  43. if err != nil {
  44. fmt.Println("EggFinWithdrawApplyDataConsume:::::", err.Error())
  45. utils2.FilePutContents("EggFinWithdrawApplyDataConsume", utils2.SerializeStr(map[string]interface{}{
  46. "err": err.Error(),
  47. }))
  48. return
  49. }
  50. var res amqp.Delivery
  51. var ok bool
  52. for {
  53. res, ok = <-delivery
  54. if ok == true {
  55. err = handleEggFinWithdrawApplyDataConsume(res.Body, client, ch)
  56. if err != nil {
  57. fmt.Println("EggFinWithdrawApplyDataConsume:::::", err.Error())
  58. utils2.FilePutContents("EggFinWithdrawApplyDataConsume", utils2.SerializeStr(map[string]interface{}{
  59. "body": res.Body,
  60. "err": err.Error(),
  61. }))
  62. var data md2.EggFinWithdrawApplyErrorData
  63. data.ErrorInfo = err.Error()
  64. // 尝试解析数据结构体
  65. var msg *md2.EggFinWithdrawApplyData
  66. err1 := json.Unmarshal(res.Body, &msg)
  67. if err1 != nil {
  68. // 无法解析 直接将[]byte推进队列
  69. data.Ext = res.Body
  70. } else {
  71. // 解析成功
  72. data.EggFinWithdrawApplyData = *msg
  73. }
  74. ch.Publish(md2.EggAppExchange, data, md2.EggFinWithdrawApplyError)
  75. }
  76. //_ = res.Reject(false)
  77. err = res.Ack(true)
  78. fmt.Println("err ::: ", err)
  79. } else {
  80. panic(errors.New("error getting message"))
  81. }
  82. }
  83. }
  84. func handleEggFinWithdrawApplyDataConsume(msgData []byte, client *alipay.Client, ch *rabbit.Channel) error {
  85. time.Sleep(time.Duration(100) * time.Millisecond) //休眠100毫秒
  86. // 1.解析mq中queue的数据结构体
  87. var msg *md2.EggFinWithdrawApplyData
  88. err := json.Unmarshal(msgData, &msg)
  89. if err != nil {
  90. return err
  91. }
  92. applyDb := implement.NewFinWithdrawApplyDb(db.Db)
  93. apply, err := applyDb.FinWithdrawApplyGet(msg.Id)
  94. if err != nil {
  95. return err
  96. }
  97. if apply == nil {
  98. return errors.New("提现记录不存在~")
  99. }
  100. // 如果不在队列处理阶段或不是自动处理订单,直接返回
  101. if apply.State != 4 && apply.Type != 2 {
  102. return errors.New("提现记录无需处理~")
  103. }
  104. session := db.Db.NewSession()
  105. defer func() {
  106. session.Close()
  107. if err := recover(); err != nil {
  108. _ = logx.Error(err)
  109. }
  110. }()
  111. session.Begin()
  112. // 2.3 更新 apply 信息
  113. apply.State = 2
  114. affected, err2 := applyDb.UpdateFinWithdrawApplyBySession(session, apply, "state")
  115. if err2 != nil {
  116. return err2
  117. }
  118. if affected == 0 {
  119. return errors.New("更新 apply 状态失败")
  120. }
  121. if msg.WithdrawKind == 1 {
  122. // 3.支付宝提现
  123. alipayUserInfoDb := implement.NewAlipayUserInfoDb(db.Db)
  124. userInfo, err1 := alipayUserInfoDb.GetAlipayUserInfo(msg.Uid)
  125. if err != nil {
  126. return err1
  127. }
  128. bm := make(gopay.BodyMap)
  129. bm.Set("out_biz_no", msg.Id).
  130. Set("trans_amount", msg.Amount).
  131. Set("biz_scene", "DIRECT_TRANSFER").
  132. Set("product_code", "TRANS_ACCOUNT_NO_PWD").
  133. SetBodyMap("payee_info", func(bm gopay.BodyMap) {
  134. bm.Set("identity", userInfo.OpenId)
  135. bm.Set("identity_type", "ALIPAY_OPEN_ID")
  136. })
  137. _, err = client.FundTransUniTransfer(context.Background(), bm)
  138. if err != nil {
  139. // 如果需要重试 推回队尾
  140. if err.Error() == "Lock wait timeout exceeded; try restarting transaction" {
  141. ch.Publish(md2.EggAppExchange, msg, md2.EggFinWithdrawApply)
  142. return nil
  143. }
  144. //TODO::处理提现失败
  145. err = dealFinWithdrawApplyStateForBad(apply)
  146. if err != nil {
  147. return err
  148. }
  149. session.Rollback()
  150. return err
  151. }
  152. } else if msg.WithdrawKind == 2 {
  153. }
  154. return session.Commit()
  155. }
  156. func dealFinWithdrawApplyStateForBad(finWithdrawApply *model.FinWithdrawApply) error {
  157. session := db.Db.NewSession()
  158. defer session.Close()
  159. session.Begin()
  160. finWithdrawApplyDb := implement.NewFinWithdrawApplyDb(db.Db)
  161. finWithdrawApply.State = int(enum.FinWithdrawApplyStateForBad)
  162. updateAffected, err1 := finWithdrawApplyDb.UpdateFinWithdrawApplyBySession(session, finWithdrawApply, "state")
  163. if err1 != nil {
  164. return err1
  165. }
  166. if updateAffected <= 0 {
  167. return errors.New("更新提现单状态失败")
  168. }
  169. dealUserWalletReq := md3.DealUserWalletReq{
  170. Direction: "sub",
  171. Kind: int(enum.UserWithdrawBad),
  172. Title: enum.UserWithdrawBad.String(),
  173. Uid: finWithdrawApply.Uid,
  174. Amount: utils2.StrToFloat64(finWithdrawApply.Amount),
  175. }
  176. err := rule.DealUserWallet(session, dealUserWalletReq)
  177. if err != nil {
  178. session.Rollback()
  179. return err
  180. }
  181. err = session.Commit()
  182. if err != nil {
  183. _ = session.Rollback()
  184. }
  185. return err
  186. }
  187. type InitAlipayStruct struct {
  188. IsProd bool `json:"is_prod" label:"是否生产环境"`
  189. AlipayAppId string `json:"alipay_app_id" label:"支付宝商家应用appid"`
  190. AlipayPrivateKey string `json:"alipay_private_key" label:"支付宝商家应用私钥"`
  191. AlipayPublicKey string `json:"alipay_public_key" label:"支付宝商家应用公钥"`
  192. AlipayPublicContentRSA2 []byte `json:"alipay_public_content_rsa_2" label:"支付宝公钥证书"`
  193. AlipayRootContent []byte `json:"alipay_root_content" label:"支付宝根证书"`
  194. AppPublicContent []byte `json:"app_public_content" label:"应用公钥证书"`
  195. }
  196. // InitAlipay 初始化支付宝客户端
  197. // appid:应用ID
  198. // privateKey:应用私钥,支持PKCS1和PKCS8
  199. // isProd:是否是正式环境,沙箱环境请选择新版沙箱应用。
  200. func InitAlipay(initData *InitAlipayStruct) (client *alipay.Client, err error) {
  201. if initData == nil {
  202. sysCfgDb := sys_cfg.NewSysCfgDb(db.Db)
  203. sysCfgMap := sysCfgDb.SysCfgFindWithDb(enum.AlipayAppId, enum.AlipayPrivateKey, enum.AlipayPublicKey, enum.AlipayPublicContentRSA2, enum.AlipayRootContent, enum.AppPublicContent)
  204. initData = &InitAlipayStruct{
  205. IsProd: true,
  206. AlipayAppId: sysCfgMap[enum.AlipayAppId],
  207. AlipayPrivateKey: sysCfgMap[enum.AlipayPrivateKey],
  208. AlipayPublicKey: sysCfgMap[enum.AlipayPublicKey],
  209. AlipayPublicContentRSA2: []byte(sysCfgMap[enum.AlipayPublicContentRSA2]),
  210. AlipayRootContent: []byte(sysCfgMap[enum.AlipayRootContent]),
  211. AppPublicContent: []byte(sysCfgMap[enum.AppPublicContent]),
  212. }
  213. }
  214. client, err = alipay.NewClient(initData.AlipayAppId, initData.AlipayPrivateKey, initData.IsProd)
  215. if err != nil {
  216. xlog.Error(err)
  217. return
  218. }
  219. // 自定义配置http请求接收返回结果body大小,默认 10MB
  220. client.SetBodySize(10) // 没有特殊需求,可忽略此配置
  221. // 打开Debug开关,输出日志,默认关闭
  222. client.DebugSwitch = gopay.DebugOn
  223. client.SetLocation(alipay.LocationShanghai). // 设置时区,不设置或出错均为默认服务器时间
  224. SetCharset(alipay.UTF8). // 设置字符编码,不设置默认 utf-8
  225. SetSignType(alipay.RSA2) // 设置签名类型,不设置默认 RSA2
  226. // SetAppAuthToken("") //授权token
  227. //SetReturnUrl("https://www.fmm.ink"). // 设置返回URL
  228. // SetNotifyUrl("https://www.fmm.ink"). // 设置异步通知URL
  229. // 传入 支付宝公钥证书 alipayPublicCert.crt 内容
  230. client.AutoVerifySign(initData.AlipayPublicContentRSA2)
  231. // 传入证书内容
  232. err = client.SetCertSnByContent(initData.AppPublicContent, initData.AlipayRootContent, initData.AlipayPublicContentRSA2)
  233. if err != nil {
  234. xlog.Debug("SetCertSn:", err)
  235. return
  236. }
  237. return
  238. }