互动
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.

448 lines
13 KiB

5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
  1. package pay_service
  2. import (
  3. "encoding/xml"
  4. "fmt"
  5. core2 "github.com/chanxuehong/wechat/mch/core"
  6. "github.com/chanxuehong/wechat/mch/pay"
  7. "github.com/pkg/errors"
  8. "go.uber.org/zap"
  9. "hudongzhuanjia/logger"
  10. "hudongzhuanjia/models"
  11. "hudongzhuanjia/utils"
  12. "io"
  13. "math"
  14. "strconv"
  15. "time"
  16. )
  17. func init() {
  18. go loopUnifiedOrder()
  19. }
  20. var orderDelayQueue = make(chan *orderDelayQueueParam, math.MaxInt8)
  21. type orderDelayQueueParam struct {
  22. First bool `json:"first"`
  23. Expires int64 `json:"expires"`
  24. Delay int `json:"delay"`
  25. OutTradeNo string `json:"out_trade_no"`
  26. Body string `json:"body"`
  27. Amount int `json:"amount"` // 金额
  28. Status int `json:"status"` // 0 订单 3 退款
  29. OpenId string `json:"open_id"` // 被操作人
  30. }
  31. func PutOrderDelayQueue(body, outTradeNo, openId string, amount, status int, expires int64, delay int) {
  32. if expires == 0 {
  33. expires = time.Now().Add(2 * time.Hour).Unix() // 2 个小时
  34. }
  35. if delay == 0 {
  36. delay = 100
  37. }
  38. orderDelayQueue <- &orderDelayQueueParam{
  39. First: true,
  40. Expires: expires,
  41. Delay: delay,
  42. OutTradeNo: outTradeNo,
  43. Body: body,
  44. Amount: amount,
  45. Status: status,
  46. OpenId: openId,
  47. }
  48. }
  49. func loopUnifiedOrder() {
  50. orders, err := models.GetUserOrdersByStatus(0, 3)
  51. if err != nil {
  52. panic(err)
  53. }
  54. for _, order := range orders {
  55. PutOrderDelayQueue(order.Body, order.OutTradeNo, order.OpenId, int(order.TotalFee), order.Status, 0, 0)
  56. }
  57. defer func() {
  58. if err := recover(); err != nil {
  59. logger.Error("订单轮询查询", zap.Any("panic 恢复错误", err))
  60. }
  61. // 重启
  62. time.Sleep(5 * time.Second)
  63. loopUnifiedOrder()
  64. }()
  65. for {
  66. select {
  67. case param, ok := <-orderDelayQueue:
  68. if !ok {
  69. panic("通道异常关闭")
  70. }
  71. if param.Expires <= time.Now().Unix() {
  72. //if param.Status == 0 {
  73. // Close(param.OutTradeNo) // 超时关闭订单
  74. //}
  75. continue // 超时
  76. }
  77. // 首次进入不延迟
  78. if !param.First {
  79. time.Sleep(time.Duration(param.Delay) * time.Millisecond)
  80. }
  81. param.First = false
  82. if param.Status == 0 {
  83. res, err := OrderQuery(param.OutTradeNo)
  84. // 出现错误
  85. if err != nil {
  86. logger.Error("查询订单出现错误", zap.String("错误原因", err.Error()),
  87. zap.String("交易订单号", param.OutTradeNo))
  88. orderDelayQueue <- param // 重新进入队列
  89. continue
  90. }
  91. if res.Query.TradeState == CODE_TRADE_SUCCESS {
  92. go Handle(res.Order)
  93. } else if res.Query.TradeState == CODE_TRADE_REFUND {
  94. param.Status = 3
  95. orderDelayQueue <- param
  96. continue
  97. } else if res.Query.TradeState == CODE_TRADE_NOTPAY || res.Query.TradeState == CODE_TRADE_USERPAYING {
  98. orderDelayQueue <- param
  99. continue
  100. }
  101. } else if param.Status == 3 {
  102. _, err = QueryRefund(param.OutTradeNo)
  103. if err != nil {
  104. logger.Error("退款订单查询错误", zap.String("错误原因", err.Error()),
  105. zap.String("交易订单号", param.OutTradeNo))
  106. continue
  107. }
  108. } else {
  109. continue
  110. }
  111. }
  112. }
  113. }
  114. const CallbackOrderUrl = "https://api.ouxuanhudong.com/PcClient/common/WeChatOauthCtl/callbackOrder"
  115. func UnifiedOrder(body, openid string, fee, goodType, userId, activityId int64) (map[string]interface{}, error) {
  116. client, err := Client()
  117. if err != nil {
  118. return nil, err
  119. }
  120. now := time.Now()
  121. timeStart := core2.FormatTime(now)
  122. timeExpire := core2.FormatTime(now.Add(2 * time.Hour))
  123. outTradeNo := utils.RandomStr(32)
  124. nonceStr := utils.RandomStr(32)
  125. resp, err := pay.UnifiedOrder2(client, &pay.UnifiedOrderRequest{
  126. Body: body,
  127. OutTradeNo: outTradeNo,
  128. TotalFee: fee,
  129. NotifyURL: CallbackOrderUrl,
  130. TradeType: "JSAPI",
  131. DeviceInfo: "WEB",
  132. NonceStr: nonceStr,
  133. SignType: core2.SignType_MD5,
  134. TimeStart: now,
  135. OpenId: openid,
  136. })
  137. if err != nil {
  138. return nil, err
  139. }
  140. // 记录这次订单
  141. userOrder := new(models.UserOrder)
  142. userOrder.DeviceInfo = "WEB"
  143. userOrder.Body = body
  144. userOrder.UserId = userId
  145. userOrder.ActivityId = activityId
  146. userOrder.FeeType = "CNY"
  147. userOrder.GoodType = goodType
  148. userOrder.OpenId = openid
  149. userOrder.OutTradeNo = outTradeNo
  150. userOrder.TimeStart = timeStart
  151. userOrder.TimeExpire = timeExpire
  152. userOrder.TotalFee = fee
  153. userOrder.TradeType = "JSAPI"
  154. userOrder.PrepayId = resp.PrepayId
  155. userOrder.Status = 0
  156. userOrder.IsDelete = false
  157. userOrder.CreatedAt = time.Now()
  158. userOrder.UpdatedAt = time.Now()
  159. if _, err = userOrder.AddUserOrder(); err != nil {
  160. return nil, err
  161. }
  162. timestamp := strconv.FormatInt(time.Now().Unix(), 10)
  163. //获取H5支付需要的paySign
  164. pac := "prepay_id=" + resp.PrepayId
  165. paySign := core2.JsapiSign(client.AppId(), timestamp, nonceStr, pac, core2.SignType_MD5, ApiKey)
  166. go PutOrderDelayQueue(userOrder.Body, userOrder.OutTradeNo, userOrder.OpenId, int(userOrder.TotalFee), userOrder.Status, 0, 0)
  167. return map[string]interface{}{
  168. "appid": Appid,
  169. "timestamp": timestamp,
  170. "nonce_str": nonceStr,
  171. "package": pac,
  172. "sign_type": core2.SignType_MD5,
  173. "pay_sign": paySign,
  174. "out_trade_no": outTradeNo,
  175. "user_order_id": userOrder.Id,
  176. }, nil
  177. }
  178. func ReOrder(outTradeNo string) (map[string]interface{}, error) {
  179. userOrder := new(models.UserOrder)
  180. exist, err := userOrder.GetByOutTradeNo(outTradeNo)
  181. if err != nil {
  182. return nil, err
  183. }
  184. if !exist {
  185. return nil, errors.New("订单不存在")
  186. }
  187. timestamp := strconv.FormatInt(time.Now().Unix(), 10)
  188. nonceStr := utils.RandomStr(32)
  189. //获取H5支付需要的paySign
  190. pac := "prepay_id=" + userOrder.PrepayId
  191. paySign := core2.JsapiSign(Appid, timestamp, nonceStr, pac, core2.SignType_MD5, ApiKey)
  192. if userOrder.TimeExpire <= core2.FormatTime(time.Now()) {
  193. go PutOrderDelayQueue(userOrder.Body, userOrder.OutTradeNo, userOrder.OpenId, int(userOrder.TotalFee), userOrder.Status, 0, 0)
  194. }
  195. return map[string]interface{}{
  196. "appid": Appid,
  197. "timestamp": timestamp,
  198. "nonce_str": nonceStr,
  199. "package": pac,
  200. "sign_type": core2.SignType_MD5,
  201. "pay_sign": paySign,
  202. "out_trade_no": outTradeNo,
  203. "user_order_id": userOrder.Id,
  204. }, nil
  205. }
  206. // Notify
  207. type NotifyRequest struct {
  208. ReturnCode string `xml:"return_code,omitempty" json:"return_code,omitempty"`
  209. ReturnMsg string `xml:"return_msg,omitempty" json:"return_msg,omitempty"`
  210. ResultCode string `xml:"result_code,omitempty" json:"result_code,omitempty"`
  211. ErrCode string `xml:"err_code,omitempty" json:"err_code,omitempty"`
  212. ErrCodeDes string `xml:"err_code_des,omitempty" json:"err_code_des,omitempty"`
  213. Appid string `xml:"appid,omitempty" json:"appid,omitempty"`
  214. MchId string `xml:"mch_id,omitempty" json:"mch_id,omitempty"`
  215. DeviceInfo string `xml:"device_info,omitempty" json:"device_info,omitempty"`
  216. NonceStr string `xml:"nonce_str,omitempty" json:"nonce_str,omitempty"`
  217. Sign string `xml:"sign,omitempty" json:"sign,omitempty"`
  218. SignType string `xml:"sign_type,omitempty" json:"sign_type,omitempty"`
  219. Openid string `xml:"openid,omitempty" json:"openid,omitempty"`
  220. IsSubscribe string `xml:"is_subscribe,omitempty" json:"is_subscribe,omitempty"`
  221. TradeType string `xml:"trade_type,omitempty" json:"trade_type,omitempty"`
  222. BankType string `xml:"bank_type,omitempty" json:"bank_type,omitempty"`
  223. TotalFee int `xml:"total_fee,omitempty" json:"total_fee,omitempty"`
  224. SettlementTotalFee int `xml:"settlement_total_fee,omitempty" json:"settlement_total_fee,omitempty"`
  225. FeeType string `xml:"fee_type,omitempty" json:"fee_type,omitempty"`
  226. CashFee int `xml:"cash_fee,omitempty" json:"cash_fee,omitempty"`
  227. CashFeeType string `xml:"cash_fee_type,omitempty" json:"cash_fee_type,omitempty"`
  228. CouponFee int `xml:"coupon_fee,omitempty" json:"coupon_fee,omitempty"`
  229. CouponCount int `xml:"coupon_count,omitempty" json:"coupon_count,omitempty"`
  230. CouponType0 string `xml:"coupon_type_0,omitempty" json:"coupon_type_0,omitempty"`
  231. CouponType1 string `xml:"coupon_type_1,omitempty" json:"coupon_type_1,omitempty"`
  232. CouponId0 string `xml:"coupon_id_0,omitempty" json:"coupon_id_0,omitempty"`
  233. CouponId1 string `xml:"coupon_id_1,omitempty" json:"coupon_id_1,omitempty"`
  234. CouponFee0 int `xml:"coupon_fee_0,omitempty" json:"coupon_fee_0,omitempty"`
  235. CouponFee1 int `xml:"coupon_fee_1,omitempty" json:"coupon_fee_1,omitempty"`
  236. TransactionId string `xml:"transaction_id,omitempty" json:"transaction_id,omitempty"`
  237. OutTradeNo string `xml:"out_trade_no,omitempty" json:"out_trade_no,omitempty"`
  238. Attach string `xml:"attach,omitempty" json:"attach,omitempty"`
  239. TimeEnd string `xml:"time_end,omitempty" json:"time_end,omitempty"`
  240. }
  241. func NotifyOrder(w io.Reader) (*models.UserOrder, error) {
  242. res := new(NotifyRequest)
  243. if err := xml.NewDecoder(w).Decode(res); err != nil {
  244. return nil, fmt.Errorf("xml.NewDecoder.Decode:%w", err)
  245. }
  246. if res.ReturnCode != CODE_SUCCESS {
  247. return nil, fmt.Errorf("network error, retrun_code: %v and return_msg: %v", res.ReturnCode, res.ReturnMsg)
  248. }
  249. if res.ResultCode == CODE_SUCCESS && res.TradeType == CODE_TRADE_SUCCESS {
  250. userOrder := new(models.UserOrder)
  251. userOrder.TimeEnd = res.TimeEnd
  252. userOrder.TransactionId = res.TransactionId
  253. userOrder.Status = 1
  254. if _, err := userOrder.UpdateStatusByOutTradeNo(res.OutTradeNo, 1); err != nil {
  255. return nil, err
  256. }
  257. return userOrder, nil
  258. } else {
  259. return nil, fmt.Errorf("trade error, err_code: %v and err_code_des: %v", res.ErrCode, res.ErrCodeDes)
  260. }
  261. }
  262. type OrderQueryResult struct {
  263. Order *models.UserOrder
  264. Query *pay.OrderQueryResponse
  265. }
  266. func OrderQuery(outTradeNo string) (*OrderQueryResult, error) {
  267. client, err := Client()
  268. if err != nil {
  269. return nil, err
  270. }
  271. // 请求订单查询,成功后得到结果
  272. userOrder := new(models.UserOrder)
  273. exist, err := userOrder.GetByOutTradeNo(outTradeNo)
  274. if err != nil {
  275. return nil, err
  276. }
  277. if !exist {
  278. return nil, errors.New("订单不存在")
  279. }
  280. res, err := pay.OrderQuery2(client, &pay.OrderQueryRequest{
  281. OutTradeNo: outTradeNo,
  282. NonceStr: utils.RandomStr(32),
  283. SignType: core2.SignType_MD5,
  284. })
  285. if err != nil {
  286. userOrder.ErrMsg = err.Error()
  287. userOrder.UpdateErrByOutTradeNo(outTradeNo)
  288. return nil, err
  289. }
  290. userOrder.TransactionId = res.TransactionId
  291. userOrder.TimeEnd = core2.FormatTime(res.TimeEnd)
  292. switch res.TradeState {
  293. case CODE_TRADE_SUCCESS:
  294. userOrder.Status = 1
  295. case CODE_TRADE_REVOKED:
  296. userOrder.Status = 2
  297. case CODE_TRADE_REFUND:
  298. userOrder.Status = 3
  299. case CODE_TRADE_PAYERROR:
  300. userOrder.Status = 5
  301. case CODE_TRADE_CLOSED:
  302. userOrder.Status = 6
  303. case CODE_TRADE_NOTPAY: // 超过期限,就关闭
  304. userOrder.Status = 0
  305. }
  306. if _, err = userOrder.UpdateStatusByOutTradeNo(outTradeNo, userOrder.Status); err != nil {
  307. return nil, err
  308. }
  309. return &OrderQueryResult{
  310. Order: userOrder,
  311. Query: res,
  312. }, nil
  313. }
  314. func Close(outTradeNo string) error {
  315. client, err := Client()
  316. if err != nil {
  317. return err
  318. }
  319. err = pay.CloseOrder2(client, &pay.CloseOrderRequest{
  320. OutTradeNo: outTradeNo,
  321. NonceStr: utils.RandomStr(32),
  322. SignType: core2.SignType_MD5,
  323. })
  324. // 请求关闭订单,成功后得到结果
  325. if err != nil {
  326. return err
  327. }
  328. return nil
  329. }
  330. //const CALLBACK_REFUND_URL = "https://api.ouxuanhudong.com/PcClient/common/WeChatOauthCtl/callbackRefund"
  331. func Refund(reason, outTradeNo string) (*pay.RefundResponse, error) {
  332. userOrder := new(models.UserOrder)
  333. exist, err := userOrder.GetByOutTradeNo(outTradeNo)
  334. if err != nil {
  335. return nil, err
  336. }
  337. if !exist {
  338. return nil, errors.New("订单不存在")
  339. }
  340. client, err := Client()
  341. outRefundNo := utils.RandomStr(64)
  342. nonceStr := utils.RandomStr(32)
  343. res, err := pay.Refund2(client, &pay.RefundRequest{
  344. TransactionId: "",
  345. OutTradeNo: outTradeNo,
  346. OutRefundNo: outRefundNo,
  347. TotalFee: userOrder.TotalFee,
  348. RefundFee: userOrder.TotalFee,
  349. NonceStr: nonceStr,
  350. SignType: core2.SignType_MD5,
  351. RefundFeeType: "CNY",
  352. RefundDesc: reason,
  353. })
  354. //
  355. if err != nil {
  356. userOrder.ErrMsg = err.Error()
  357. userOrder.UpdateErrByOutTradeNo(outTradeNo)
  358. return nil, err
  359. }
  360. userOrder.Status = 3
  361. _, err = userOrder.UpdateStatusByOutTradeNo(outTradeNo, userOrder.Status)
  362. if err != nil {
  363. return nil, err
  364. }
  365. PutOrderDelayQueue(userOrder.Body, userOrder.OutTradeNo, userOrder.OpenId, int(userOrder.TotalFee), userOrder.Status, 0, 0) // 退款查询
  366. return res, nil
  367. }
  368. type QueryRefundResult struct {
  369. Order *models.UserOrder
  370. Query *pay.RefundQueryResponse
  371. }
  372. func QueryRefund(outTradeNo string) (*QueryRefundResult, error) {
  373. userOrder := new(models.UserOrder)
  374. exist, err := userOrder.GetByOutTradeNo(outTradeNo)
  375. if err != nil {
  376. return nil, err
  377. }
  378. if !exist {
  379. return nil, errors.New("不存在改笔退款")
  380. }
  381. client, err := Client()
  382. res, err := pay.RefundQuery2(client, &pay.RefundQueryRequest{
  383. OutTradeNo: outTradeNo,
  384. NonceStr: utils.RandomStr(32),
  385. SignType: core2.SignType_MD5,
  386. })
  387. //请求申请退款
  388. if err != nil {
  389. userOrder.ErrMsg = err.Error()
  390. userOrder.UpdateErrByOutTradeNo(outTradeNo)
  391. return nil, err
  392. }
  393. userOrder.RefundAccount = res.RefundList[0].RefundAccount
  394. userOrder.RefundRecvAccount = res.RefundList[0].RefundRecvAccout
  395. userOrder.SuccessTime = res.RefundList[0].RefundSuccessTime
  396. userOrder.Status = 4
  397. _, err = userOrder.UpdateRefundByOutTradeNo(outTradeNo)
  398. if err != nil {
  399. return nil, err
  400. }
  401. return &QueryRefundResult{
  402. Order: userOrder,
  403. Query: res,
  404. }, nil
  405. }