package jobs import ( "context" "fmt" "time" "quyun/app/models" "quyun/database/fields" "quyun/providers/wepay" "github.com/pkg/errors" . "github.com/riverqueue/river" log "github.com/sirupsen/logrus" _ "go.ipao.vip/atom" "go.ipao.vip/atom/contracts" _ "go.ipao.vip/atom/contracts" ) var _ contracts.JobArgs = (*WechatPayNotify)(nil) type WechatPayNotify struct { PayNotify *wepay.PayNotify `json:"notify_req"` } func (s WechatPayNotify) InsertOpts() InsertOpts { return InsertOpts{ Queue: QueueDefault, Priority: PriorityDefault, } } func (WechatPayNotify) Kind() string { return "wechat_pay_notify" } func (a WechatPayNotify) UniqueID() string { return a.Kind() } var _ Worker[WechatPayNotify] = (*WechatPayNotifyWorker)(nil) // @provider(job) type WechatPayNotifyWorker struct { WorkerDefaults[WechatPayNotify] } func (w *WechatPayNotifyWorker) Work(ctx context.Context, job *Job[WechatPayNotify]) error { log := log.WithField("job", job.Args.Kind()) log.Infof("[Start] Working on job with strings: %+v", job.Args) defer log.Infof("[End] Finished %s", job.Args.Kind()) notify := job.Args.PayNotify if notify.TradeState != "SUCCESS" { log.Warnf("TradeState is not SUCCESS for order %s", notify.OutTradeNo) return JobCancel(errors.New("TradeState is not SUCCESS")) } order, err := models.Orders.GetByOrderNo(context.Background(), notify.OutTradeNo) if err != nil { log.Errorf("GetByOrderNo error:%v", err) return err } if order.Status != fields.OrderStatusPending { log.Infof("Order %s is paid, processing...", job.Args.PayNotify.OutTradeNo) return JobCancel(fmt.Errorf("Order already paid, currently status: %d", order.Status)) } needToPay := order.Price * int64(order.Discount) / 100 if notify.Amount.Total != needToPay { log.Errorf("Order %s amount mismatch: expected %d, got %d", job.Args.PayNotify.OutTradeNo, needToPay, notify.Amount.Total) return fmt.Errorf("amount mismatch for order %s", job.Args.PayNotify.OutTradeNo) } order.TransactionID = notify.TransactionID order.Currency = notify.Amount.Currency order.PaymentMethod = notify.TradeType order.Status = fields.OrderStatusCompleted order.Meta = fields.ToJson(fields.OrderMeta{ PayNotify: *notify, }) log.Infof("Updated order details: %+v", order) tx, err := models.Transaction(ctx) if err != nil { return errors.Wrap(err, "Transaction error") } defer tx.Rollback() if err := models.Users.BuyPosts(context.Background(), order.UserID, order.PostID, order.Price); err != nil { log.Errorf("BuyPosts error:%v", err) return errors.Wrap(err, "BuyPosts error") } if err := models.Orders.Update(context.Background(), order); err != nil { log.Errorf("Update order error:%v", err) return errors.Wrap(err, "Update order error") } if err := tx.Commit(); err != nil { log.Errorf("Commit error:%v", err) return errors.Wrap(err, "Commit error") } log.Infof("Successfully processed order %s", notify.OutTradeNo) return nil } func (w *WechatPayNotifyWorker) NextRetry(job *Job[WechatPayNotify]) time.Time { return time.Now().Add(30 * time.Second) }