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

94 lines
2.2 KiB

package pay_service
import (
"hudongzhuanjia/logger"
"hudongzhuanjia/models"
"hudongzhuanjia/utils/define"
"math"
"time"
)
var orderDelayQueue = make(chan *models.UserOrder, math.MaxInt8)
func PutOrderDelayQueue(order *models.UserOrder) {
orderDelayQueue <- order
}
func loopOrder() {
orders, err := models.GetUserOrdersByStatus(0, 3)
if err != nil {
panic(err)
}
for _, order := range orders {
PutOrderDelayQueue(order)
}
defer func() {
if err := recover(); err != nil {
logger.Error("订单轮询查询: panic 恢复错误", err)
}
// 重启
time.Sleep(5 * time.Second)
loopOrder()
}()
for {
select {
case order, ok := <-orderDelayQueue:
if !ok {
panic("通道异常关闭")
}
if order.ExpireAt <= time.Now().Unix() { // 订单超时
if order.Status == 0 {
go HandleTimeout(order)
}
continue
}
if order.Status == 0 {
res, err := OrderQuery(order.OutTradeNo)
if err != nil {
logger.Error("查询订单出现错误: 错误原因-->", err.Error(), "交易订单号-->", order.OutTradeNo)
orderDelayQueue <- order // 重新进入队列
continue
}
if res["trade_state"] == define.CODE_TRADE_SUCCESS {
go HandleSuccess(order)
} else if res["trade_state"] == define.CODE_TRADE_REFUND {
order.Status = 3
orderDelayQueue <- order
continue
} else {
orderDelayQueue <- order
continue
}
} else if order.Status == 3 {
res, err := QueryRefund(order.OutTradeNo)
if err != nil {
logger.Error("退款订单查询错误: 错误原因-->", err.Error(), "交易订单号-->", order.OutTradeNo)
continue
}
order.RefundAccount = res.RefundList[0].RefundAccount
order.RefundRecvAccount = res.RefundList[0].RefundRecvAccout
order.Status = 4
_, err = models.Update(order.Id, order, "refund_account", "refund_recv_account", "status")
if err != nil {
logger.Error("退款状态改变错误: 错误原因-->", err, "交易订单号-->", order.OutTradeNo)
continue
}
}
}
}
}
func HandleTimeout(order *models.UserOrder) error {
// 退还库存
if order.GoodType == 4 {
err := HandleCancelOrder(order.OutTradeNo)
if err != nil {
logger.Error(err)
}
}
return nil
}