feat: add refund statuses

This commit is contained in:
Rogee
2025-05-06 20:23:06 +08:00
parent b7ebdf1ce6
commit 41cdc821da
13 changed files with 266 additions and 114 deletions

View File

@@ -61,9 +61,11 @@ func (ctl *orders) Refund(ctx fiber.Ctx, id int64) error {
meta.RefundResp = resp
order.Meta = fields.ToJson(meta)
order.RefundTransactionID = resp.RefundId
order.Status = fields.OrderStatusRefundProcessing
if err := models.Orders.Update(ctx.Context(), order); err != nil {
return err
}
return nil
}

View File

@@ -5,6 +5,7 @@ import (
"quyun/providers/app"
"quyun/providers/job"
"quyun/providers/jwt"
"quyun/providers/wepay"
"go.ipao.vip/atom"
"go.ipao.vip/atom/container"
@@ -35,8 +36,12 @@ func Provide(opts ...opt.Option) error {
}); err != nil {
return err
}
if err := container.Container.Provide(func() (*orders, error) {
obj := &orders{}
if err := container.Container.Provide(func(
wepay *wepay.Client,
) (*orders, error) {
obj := &orders{
wepay: wepay,
}
return obj, nil
}); err != nil {

View File

@@ -7,7 +7,6 @@ import (
"quyun/providers/job"
"quyun/providers/wepay"
"github.com/go-pay/gopay"
"github.com/go-pay/gopay/wechat/v3"
"github.com/gofiber/fiber/v3"
log "github.com/sirupsen/logrus"
@@ -25,20 +24,21 @@ type pays struct {
// @Bind channel path
func (ctl *pays) Callback(ctx fiber.Ctx, channel string) error {
log := log.WithField("method", "pays.Callback")
notify, err := ctl.wepay.ParseNotify(ctx)
if err != nil {
log.Errorf("ParseNotify error:%v", err)
return ctx.Status(http.StatusBadRequest).JSON(fiber.Map{"error": "Failed to parse notify"})
}
if err := ctl.job.Add(&jobs.WechatPayNotify{PayNotify: notify}); err != nil {
log.Errorf("add job error:%v", err)
return ctx.Status(http.StatusInternalServerError).JSON(fiber.Map{"error": "Failed to add job"})
}
return ctx.Status(http.StatusOK).JSON(&wechat.V3NotifyRsp{
Code: gopay.SUCCESS,
Message: "成功",
})
return ctl.wepay.ParseNotify(
ctx,
func(ctx fiber.Ctx, notify *wechat.V3DecryptPayResult) error {
if err := ctl.job.Add(&jobs.WechatPayNotify{Notify: notify}); err != nil {
log.Errorf("add job error:%v", err)
return ctx.Status(http.StatusInternalServerError).JSON(fiber.Map{"error": "Failed to add job"})
}
return nil
},
func(c fiber.Ctx, notify *wechat.V3DecryptRefundResult) error {
if err := ctl.job.Add(&jobs.WechatRefundNotify{Notify: notify}); err != nil {
log.Errorf("add job error:%v", err)
return c.Status(http.StatusInternalServerError).JSON(fiber.Map{"error": "Failed to add job"})
}
return nil
},
)
}

View File

@@ -156,5 +156,17 @@ func Provide(opts ...opt.Option) error {
}, atom.GroupInitial); err != nil {
return err
}
if err := container.Container.Provide(func(
__job *job.Job,
) (contracts.Initial, error) {
obj := &WechatRefundNotifyWorker{}
if err := river.AddWorkerSafely(__job.Workers, obj); err != nil {
return nil, err
}
return obj, nil
}, atom.GroupInitial); err != nil {
return err
}
return nil
}

View File

@@ -7,8 +7,8 @@ import (
"quyun/app/models"
"quyun/database/fields"
"quyun/providers/wepay"
"github.com/go-pay/gopay/wechat/v3"
"github.com/pkg/errors"
. "github.com/riverqueue/river"
log "github.com/sirupsen/logrus"
@@ -20,7 +20,7 @@ import (
var _ contracts.JobArgs = (*WechatPayNotify)(nil)
type WechatPayNotify struct {
PayNotify *wepay.PayNotify `json:"notify_req"`
Notify *wechat.V3DecryptPayResult `json:"notify"`
}
func (s WechatPayNotify) InsertOpts() InsertOpts {
@@ -46,7 +46,7 @@ func (w *WechatPayNotifyWorker) Work(ctx context.Context, job *Job[WechatPayNoti
log.Infof("[Start] Working on job with strings: %+v", job.Args)
defer log.Infof("[End] Finished %s", job.Args.Kind())
notify := job.Args.PayNotify
notify := job.Args.Notify
if notify.TradeState != "SUCCESS" {
log.Warnf("TradeState is not SUCCESS for order %s", notify.OutTradeNo)
@@ -60,23 +60,23 @@ func (w *WechatPayNotifyWorker) Work(ctx context.Context, job *Job[WechatPayNoti
}
if order.Status != fields.OrderStatusPending {
log.Infof("Order %s is paid, processing...", job.Args.PayNotify.OutTradeNo)
log.Infof("Order %s is paid, processing...", job.Args.Notify.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)
if int64(notify.Amount.Total) != needToPay {
log.Errorf("Order %s amount mismatch: expected %d, got %d", job.Args.Notify.OutTradeNo, needToPay, notify.Amount.Total)
return fmt.Errorf("amount mismatch for order %s", job.Args.Notify.OutTradeNo)
}
order.TransactionID = notify.TransactionID
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,
PayNotify: notify,
})
log.Infof("Updated order details: %+v", order)

View File

@@ -7,8 +7,8 @@ import (
"quyun/app/models"
"quyun/app/service/testx"
"quyun/providers/wepay"
"github.com/go-pay/gopay/wechat/v3"
. "github.com/riverqueue/river"
. "github.com/smartystreets/goconvey/convey"
"github.com/stretchr/testify/suite"
@@ -42,13 +42,13 @@ func (t *WechatPayNotifySuite) Test_Work() {
Convey("step 1", func() {
notify := `{ "mchid": "1702644947", "appid": "wx47649361b6eba174", "out_trade_no": "20250430192543", "transaction_id": "4200002602202504300651871941", "trade_type": "JSAPI", "trade_state": "SUCCESS", "trade_state_desc": "支付成功", "bank_type": "OTHERS", "attach": "", "success_time": "2025-04-30T19:25:51+08:00", "payer": { "openid": "o5Bzk644x3LOMJsKSZRlqWin74IU" }, "amount": { "total": 1, "payer_total": 1, "currency": "CNY", "payer_currency": "CNY" } }`
var payNotify wepay.PayNotify
var payNotify wechat.V3DecryptPayResult
err := json.Unmarshal([]byte(notify), &payNotify)
So(err, ShouldBeNil)
job := &Job[WechatPayNotify]{
Args: WechatPayNotify{
PayNotify: &payNotify,
Notify: &payNotify,
},
}

View File

@@ -0,0 +1,100 @@
package jobs
import (
"context"
"time"
"quyun/app/models"
"quyun/database/fields"
"github.com/go-pay/gopay/wechat/v3"
"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 = (*WechatRefundNotify)(nil)
type WechatRefundNotify struct {
Notify *wechat.V3DecryptRefundResult `json:"notify"`
}
func (s WechatRefundNotify) InsertOpts() InsertOpts {
return InsertOpts{
Queue: QueueDefault,
Priority: PriorityDefault,
}
}
func (WechatRefundNotify) Kind() string { return "wechat_refund_notify" }
func (a WechatRefundNotify) UniqueID() string { return a.Kind() }
var _ Worker[WechatRefundNotify] = (*WechatRefundNotifyWorker)(nil)
// @provider(job)
type WechatRefundNotifyWorker struct {
WorkerDefaults[WechatRefundNotify]
}
func (w *WechatRefundNotifyWorker) Work(ctx context.Context, job *Job[WechatRefundNotify]) 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.Notify
order, err := models.Orders.GetByOrderNo(context.Background(), notify.OutTradeNo)
if err != nil {
log.Errorf("GetByOrderNo error:%v", err)
return err
}
meta := order.Meta.Data
meta.RefundNotify = notify
order.Status = fields.OrderStatusRefundProcessing
switch notify.RefundStatus {
case "SUCCESS":
order.Status = fields.OrderStatusRefundSuccess
case "CLOSED":
order.Status = fields.OrderStatusRefundClosed
case "PROCESSING":
order.Status = fields.OrderStatusRefundProcessing
case "ABNORMAL":
order.Status = fields.OrderStatusRefundAbnormal
}
order.Meta = fields.ToJson(meta)
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 order.Status == fields.OrderStatusRefundSuccess {
if err := models.Users.RevokePosts(context.Background(), order.UserID, order.PostID); err != nil {
log.Errorf("RevokePosts error:%v", err)
return errors.Wrap(err, "RevokePosts 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 *WechatRefundNotifyWorker) NextRetry(job *Job[WechatRefundNotify]) time.Time {
return time.Now().Add(30 * time.Second)
}

View File

@@ -448,3 +448,21 @@ func (m *usersModel) BuyPosts(ctx context.Context, userID, postID, price int64)
}
return nil
}
func (m *usersModel) RevokePosts(ctx context.Context, userID, postID int64) error {
tbl := table.UserPosts
stmt := tbl.
DELETE().
WHERE(
tbl.UserID.EQ(Int64(userID)).AND(
tbl.PostID.EQ(Int64(postID)),
),
)
m.log.Infof("sql: %s", stmt.DebugSql())
if _, err := stmt.ExecContext(ctx, db); err != nil {
m.log.Errorf("error revoking user post: %v", err)
return err
}
return nil
}

View File

@@ -19,10 +19,14 @@ const (
OrderStatusPending OrderStatus = iota
// OrderStatusPaid is a OrderStatus of type Paid.
OrderStatusPaid
// OrderStatusRefunding is a OrderStatus of type Refunding.
OrderStatusRefunding
// OrderStatusRefunded is a OrderStatus of type Refunded.
OrderStatusRefunded
// OrderStatusRefundSuccess is a OrderStatus of type Refund_success.
OrderStatusRefundSuccess
// OrderStatusRefundClosed is a OrderStatus of type Refund_closed.
OrderStatusRefundClosed
// OrderStatusRefundProcessing is a OrderStatus of type Refund_processing.
OrderStatusRefundProcessing
// OrderStatusRefundAbnormal is a OrderStatus of type Refund_abnormal.
OrderStatusRefundAbnormal
// OrderStatusCancelled is a OrderStatus of type Cancelled.
OrderStatusCancelled
// OrderStatusCompleted is a OrderStatus of type Completed.
@@ -31,15 +35,17 @@ const (
var ErrInvalidOrderStatus = fmt.Errorf("not a valid OrderStatus, try [%s]", strings.Join(_OrderStatusNames, ", "))
const _OrderStatusName = "pendingpaidrefundingrefundedcancelledcompleted"
const _OrderStatusName = "pendingpaidrefund_successrefund_closedrefund_processingrefund_abnormalcancelledcompleted"
var _OrderStatusNames = []string{
_OrderStatusName[0:7],
_OrderStatusName[7:11],
_OrderStatusName[11:20],
_OrderStatusName[20:28],
_OrderStatusName[28:37],
_OrderStatusName[37:46],
_OrderStatusName[11:25],
_OrderStatusName[25:38],
_OrderStatusName[38:55],
_OrderStatusName[55:70],
_OrderStatusName[70:79],
_OrderStatusName[79:88],
}
// OrderStatusNames returns a list of possible string values of OrderStatus.
@@ -54,20 +60,24 @@ func OrderStatusValues() []OrderStatus {
return []OrderStatus{
OrderStatusPending,
OrderStatusPaid,
OrderStatusRefunding,
OrderStatusRefunded,
OrderStatusRefundSuccess,
OrderStatusRefundClosed,
OrderStatusRefundProcessing,
OrderStatusRefundAbnormal,
OrderStatusCancelled,
OrderStatusCompleted,
}
}
var _OrderStatusMap = map[OrderStatus]string{
OrderStatusPending: _OrderStatusName[0:7],
OrderStatusPaid: _OrderStatusName[7:11],
OrderStatusRefunding: _OrderStatusName[11:20],
OrderStatusRefunded: _OrderStatusName[20:28],
OrderStatusCancelled: _OrderStatusName[28:37],
OrderStatusCompleted: _OrderStatusName[37:46],
OrderStatusPending: _OrderStatusName[0:7],
OrderStatusPaid: _OrderStatusName[7:11],
OrderStatusRefundSuccess: _OrderStatusName[11:25],
OrderStatusRefundClosed: _OrderStatusName[25:38],
OrderStatusRefundProcessing: _OrderStatusName[38:55],
OrderStatusRefundAbnormal: _OrderStatusName[55:70],
OrderStatusCancelled: _OrderStatusName[70:79],
OrderStatusCompleted: _OrderStatusName[79:88],
}
// String implements the Stringer interface.
@@ -88,10 +98,12 @@ func (x OrderStatus) IsValid() bool {
var _OrderStatusValue = map[string]OrderStatus{
_OrderStatusName[0:7]: OrderStatusPending,
_OrderStatusName[7:11]: OrderStatusPaid,
_OrderStatusName[11:20]: OrderStatusRefunding,
_OrderStatusName[20:28]: OrderStatusRefunded,
_OrderStatusName[28:37]: OrderStatusCancelled,
_OrderStatusName[37:46]: OrderStatusCompleted,
_OrderStatusName[11:25]: OrderStatusRefundSuccess,
_OrderStatusName[25:38]: OrderStatusRefundClosed,
_OrderStatusName[38:55]: OrderStatusRefundProcessing,
_OrderStatusName[55:70]: OrderStatusRefundAbnormal,
_OrderStatusName[70:79]: OrderStatusCancelled,
_OrderStatusName[79:88]: OrderStatusCompleted,
}
// ParseOrderStatus attempts to convert a string to a OrderStatus.

View File

@@ -1,16 +1,15 @@
package fields
import (
"quyun/providers/wepay"
"github.com/go-pay/gopay/wechat/v3"
)
// swagger:enum OrderStatus
// ENUM( pending, paid, refunding, refunded, cancelled, completed)
// ENUM( pending, paid, refund_success, refund_closed, refund_processing, refund_abnormal, cancelled, completed)
type OrderStatus int16
type OrderMeta struct {
PayNotify wepay.PayNotify `json:"pay_notify"`
RefundResp *wechat.RefundOrderResponse `json:"refund_resp"`
PayNotify *wechat.V3DecryptPayResult `json:"pay_notify"`
RefundResp *wechat.RefundOrderResponse `json:"refund_resp"`
RefundNotify *wechat.V3DecryptRefundResult `json:"refund_notify"`
}

View File

@@ -40,45 +40,19 @@ type PayNotify struct {
} `json:"amount"`
}
type RefundResponse struct {
RefundID string `json:"refund_id"`
OutRefundNo string `json:"out_refund_no"`
type RefundNotify struct {
Mchid string `json:"mchid"`
TransactionID string `json:"transaction_id"`
OutTradeNo string `json:"out_trade_no"`
Channel string `json:"channel"`
UserReceivedAccount string `json:"user_received_account"`
RefundID string `json:"refund_id"`
OutRefundNo string `json:"out_refund_no"`
RefundStatus string `json:"refund_status"`
SuccessTime time.Time `json:"success_time"`
CreateTime time.Time `json:"create_time"`
Status string `json:"status"`
FundsAccount string `json:"funds_account"`
UserReceivedAccount string `json:"user_received_account"`
Amount struct {
Total int `json:"total"`
Refund int `json:"refund"`
From []struct {
Account string `json:"account"`
Amount int `json:"amount"`
} `json:"from"`
PayerTotal int `json:"payer_total"`
PayerRefund int `json:"payer_refund"`
SettlementRefund int `json:"settlement_refund"`
SettlementTotal int `json:"settlement_total"`
DiscountRefund int `json:"discount_refund"`
Currency string `json:"currency"`
RefundFee int `json:"refund_fee"`
Total int `json:"total"`
Refund int `json:"refund"`
PayerTotal int `json:"payer_total"`
PayerRefund int `json:"payer_refund"`
} `json:"amount"`
PromotionDetail []struct {
PromotionID string `json:"promotion_id"`
Scope string `json:"scope"`
Type string `json:"type"`
Amount int `json:"amount"`
RefundAmount int `json:"refund_amount"`
GoodsDetail []struct {
MerchantGoodsID string `json:"merchant_goods_id"`
WechatpayGoodsID string `json:"wechatpay_goods_id"`
GoodsName string `json:"goods_name"`
UnitPrice int `json:"unit_price"`
RefundAmount int `json:"refund_amount"`
RefundQuantity int `json:"refund_quantity"`
} `json:"goods_detail"`
} `json:"promotion_detail"`
}

View File

@@ -78,11 +78,11 @@ type PrepayData struct {
}
// PaySignOfJSAPI
func (pay *PrepayData) PaySignOfJSAPI() (*, error) {
func (pay *PrepayData) PaySignOfJSAPI() (*wechat.JSAPIPayParams, error) {
return pay.client.payClient.PaySignOfJSAPI(pay.AppID, pay.PrepayID)
}
func (c *Client) Refund(ctx context.Context, f func(*BodyMap)) (*wechat.RefundOrderResponse,error ){
func (c *Client) Refund(ctx context.Context, f func(*BodyMap)) (*wechat.RefundOrderResponse, error) {
bm := NewBodyMap(c.config)
f(bm)
@@ -117,7 +117,11 @@ func (c *Client) V3TransactionJsapi(ctx context.Context, f func(*BodyMap)) (*Pre
}, nil
}
func (c *Client) ParseNotify(ctx fiber.Ctx) (*PayNotify, error) {
func (c *Client) ParseNotify(
ctx fiber.Ctx,
payCallback func(fiber.Ctx, *wechat.V3DecryptPayResult) error,
refundCallback func(fiber.Ctx, *wechat.V3DecryptRefundResult) error,
) error {
body := ctx.Body()
si := &wechat.SignInfo{
HeaderTimestamp: ctx.Get(wechat.HeaderTimestamp),
@@ -126,31 +130,54 @@ func (c *Client) ParseNotify(ctx fiber.Ctx) (*PayNotify, error) {
HeaderSerial: ctx.Get(wechat.HeaderSerial),
SignBody: string(body),
}
notifyReq := &wechat.V3NotifyReq{SignInfo: si}
if err := js.UnmarshalBytes(body, notifyReq); err != nil {
log.Errorf("json unmarshal error:%v", err)
return nil, ctx.Status(http.StatusBadRequest).JSON(fiber.Map{"error": fmt.Sprintf("json unmarshal error:%v", err)})
return ctx.Status(http.StatusBadRequest).JSON(fiber.Map{"error": fmt.Sprintf("json unmarshal error:%v", err)})
}
// 获取微信平台证书
certMap := c.WxPublicKeyMap()
// 验证异步通知的签名
err := notifyReq.VerifySignByPKMap(certMap)
if err != nil {
if err := notifyReq.VerifySignByPKMap(certMap); err != nil {
log.Errorf("verify sign error:%v", err)
return nil, ctx.Status(http.StatusBadRequest).JSON(fiber.Map{"error": "Invalid signature"})
return ctx.Status(http.StatusBadRequest).JSON(fiber.Map{"error": "Invalid signature"})
}
var notifyData PayNotify
err = notifyReq.DecryptCipherTextToStruct(c.config.Pay.ApiV3Key, &notifyData)
if err != nil {
return nil, ctx.Status(http.StatusBadRequest).JSON(fiber.Map{"error": "Invalid cipher text"})
// TRANSACTION.SUCCESS :支付成功通知
// REFUND.SUCCESS退款成功通知
// REFUND.ABNORMAL退款异常通知
// REFUND.CLOSED退款关闭通知
switch notifyReq.EventType {
case "TRANSACTION.SUCCESS":
var notifyData wechat.V3DecryptPayResult
if err := notifyReq.DecryptCipherTextToStruct(c.config.Pay.ApiV3Key, &notifyData); err != nil {
return ctx.Status(http.StatusBadRequest).JSON(fiber.Map{"error": "Invalid cipher text"})
}
log.Infof("Successfully decrypted cipher text for pay notify data: %+v", notifyData)
if err := payCallback(ctx, &notifyData); err != nil {
log.Errorf("payCallback error:%v", err)
return err
}
case "REFUND.SUCCESS", "REFUND.ABNORMAL", "REFUND.CLOSED":
var notifyData wechat.V3DecryptRefundResult
if err := notifyReq.DecryptCipherTextToStruct(c.config.Pay.ApiV3Key, &notifyData); err != nil {
return ctx.Status(http.StatusBadRequest).JSON(fiber.Map{"error": "Invalid cipher text"})
}
log.Infof("Successfully decrypted cipher text for refund notify data: %+v", notifyData)
if err := refundCallback(ctx, &notifyData); err != nil {
log.Errorf("refundCallback error:%v", err)
return err
}
}
log.Infof("Successfully decrypted cipher text for notify data: %+v", notifyData)
return &notifyData, nil
return ctx.Status(http.StatusOK).JSON(&wechat.V3NotifyRsp{
Code: gopay.SUCCESS,
Message: "成功",
})
}
type BodyMap struct {