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

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