优化支付退款钱包链路
This commit is contained in:
@@ -38,6 +38,15 @@ const (
|
||||
channelSourceMock = "mock"
|
||||
)
|
||||
|
||||
var refundBizTypes = []string{
|
||||
"cancel_refund",
|
||||
"admin_close_refund",
|
||||
"admin_refund",
|
||||
"checkout_refund",
|
||||
"deposit_refund",
|
||||
"rent_refund",
|
||||
}
|
||||
|
||||
func NewRepository(db *gorm.DB, cfg config.PaymentConfig, orderRepo *order.Repository, walletRepo *wallet.Repository) *Repository {
|
||||
provider := cfg.Provider
|
||||
if provider == "" {
|
||||
@@ -216,7 +225,7 @@ func (r *Repository) QueryWalletRecharge(userID uint64, paymentID uint64) (*Paym
|
||||
|
||||
func (r *Repository) Query(userID uint64, orderID uint64) (*PaymentDTO, error) {
|
||||
var payment model.PaymentOrder
|
||||
if err := r.db.Where("order_id = ? AND user_id = ?", orderID, userID).Order("id DESC").First(&payment).Error; err != nil {
|
||||
if err := r.db.Where("order_id = ? AND user_id = ? AND biz_type = ?", orderID, userID, "order_pay").Order("id DESC").First(&payment).Error; err != nil {
|
||||
if err == gorm.ErrRecordNotFound {
|
||||
return nil, ErrPaymentNotFound
|
||||
}
|
||||
@@ -261,6 +270,10 @@ func (r *Repository) HandleLeshuaNotify(params map[string]string, rawPayload str
|
||||
}
|
||||
log.Printf("[payment] leshua notify verified third_order_id=%s matched_key=%s", params["third_order_id"], verify.MatchedKey)
|
||||
}
|
||||
// 退款通知会携带 merchant_refund_id 或 leshua_refund_id。
|
||||
if params["merchant_refund_id"] != "" || params["leshua_refund_id"] != "" {
|
||||
return r.HandleRefundNotify(params, rawPayload, contentType)
|
||||
}
|
||||
thirdOrderID := params["third_order_id"]
|
||||
if thirdOrderID == "" {
|
||||
return nil, ErrPaymentNotFound
|
||||
@@ -285,6 +298,278 @@ func (r *Repository) HandleLeshuaNotify(params map[string]string, rawPayload str
|
||||
return &NotifyResult{OK: true, Message: "000000"}, nil
|
||||
}
|
||||
|
||||
// StartRefund 创建退款单,并在本地落库后调用乐刷退款接口。
|
||||
func (r *Repository) StartRefund(orderID uint64, refundAmountCent int64, bizType string, remark string) (*RefundDTO, error) {
|
||||
var originalPayment model.PaymentOrder
|
||||
if err := r.db.Where("order_id = ? AND status = 'paid' AND biz_type = 'order_pay'", orderID).Order("id DESC").First(&originalPayment).Error; err != nil {
|
||||
if err == gorm.ErrRecordNotFound {
|
||||
return nil, ErrPaymentNotFound
|
||||
}
|
||||
return nil, err
|
||||
}
|
||||
|
||||
var existingRefund model.PaymentOrder
|
||||
err := r.db.Where("order_id = ? AND biz_type = ? AND status NOT IN ('failed')", orderID, bizType).Order("id DESC").First(&existingRefund).Error
|
||||
if err == nil {
|
||||
dto := toRefundDTO(existingRefund)
|
||||
return &dto, nil
|
||||
}
|
||||
if err != gorm.ErrRecordNotFound {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
paymentNo, err := newPaymentNo()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
merchantRefundID := "REF" + paymentNo[3:]
|
||||
|
||||
refundOrder := model.PaymentOrder{
|
||||
PaymentNo: paymentNo,
|
||||
OrderID: orderID,
|
||||
OrderNo: originalPayment.OrderNo,
|
||||
UserID: originalPayment.UserID,
|
||||
Provider: r.provider,
|
||||
MerchantID: r.cfg.Leshua.MerchantID,
|
||||
ThirdOrderID: merchantRefundID,
|
||||
ProviderOrderID: "",
|
||||
PayWay: originalPayment.PayWay,
|
||||
JSPayFlag: originalPayment.JSPayFlag,
|
||||
AmountCent: refundAmountCent,
|
||||
BizType: bizType,
|
||||
Status: "refunding",
|
||||
}
|
||||
|
||||
if r.isMockMode {
|
||||
refundOrder.ProviderOrderID = "MOCKREF" + merchantRefundID
|
||||
refundOrder.Status = "refunded"
|
||||
now := time.Now()
|
||||
refundOrder.PaidAt = &now
|
||||
if remark != "" {
|
||||
refundOrder.RawResponse = datatypes.JSON([]byte(fmt.Sprintf(`{"mock":"true","remark":"%s"}`, remark)))
|
||||
}
|
||||
if err := r.db.Create(&refundOrder).Error; err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if err := r.updateOrderRefundStatus(orderID, refundAmountCent); err != nil {
|
||||
log.Printf("[payment] mock update order refund status failed order_id=%d err=%v", orderID, err)
|
||||
}
|
||||
dto := toRefundDTO(refundOrder)
|
||||
return &dto, nil
|
||||
}
|
||||
|
||||
if err := r.db.Create(&refundOrder).Error; err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if err := r.markOrderRefunding(orderID, refundAmountCent); err != nil {
|
||||
log.Printf("[payment] mark order refunding failed order_id=%d err=%v", orderID, err)
|
||||
}
|
||||
|
||||
resp, rawReq, err := r.leshua.CreateRefund(context.Background(), leshua.CreateRefundRequest{
|
||||
ThirdOrderID: originalPayment.ThirdOrderID,
|
||||
LeshuaOrderID: originalPayment.ProviderOrderID,
|
||||
MerchantRefundID: merchantRefundID,
|
||||
RefundAmountCent: refundAmountCent,
|
||||
NotifyURL: r.cfg.Leshua.NotifyURL,
|
||||
Attach: originalPayment.OrderNo,
|
||||
})
|
||||
if err != nil {
|
||||
_ = r.markRefundFailed(refundOrder.ID, orderID, refundAmountCent, map[string]string{"error": err.Error()})
|
||||
return nil, err
|
||||
}
|
||||
if resp.RespCode != "0" || resp.ResultCode != "0" {
|
||||
_ = r.markRefundFailed(refundOrder.ID, orderID, refundAmountCent, resp.Raw)
|
||||
return nil, ErrPaymentUnavailable
|
||||
}
|
||||
|
||||
refundStatus := "refunding"
|
||||
var paidAt *time.Time
|
||||
if resp.Status == "11" {
|
||||
refundStatus = "refunded"
|
||||
now := time.Now()
|
||||
paidAt = &now
|
||||
} else if resp.Status == "12" {
|
||||
refundStatus = "failed"
|
||||
}
|
||||
if err := r.db.Model(&model.PaymentOrder{}).Where("id = ?", refundOrder.ID).Updates(map[string]any{
|
||||
"status": refundStatus,
|
||||
"provider_order_id": resp.LeshuaRefundID,
|
||||
"raw_request": jsonMap(rawReq),
|
||||
"raw_response": jsonMap(withRawSource(resp.Raw, channelSourceCreate)),
|
||||
"paid_at": paidAt,
|
||||
}).Error; err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
if refundStatus == "refunded" {
|
||||
_ = r.updateOrderRefundStatus(orderID, refundAmountCent)
|
||||
refundOrder.PaidAt = paidAt
|
||||
} else if refundStatus == "failed" {
|
||||
_ = r.markOrderRefundFailed(orderID, refundAmountCent)
|
||||
} else {
|
||||
_ = r.markOrderRefunding(orderID, refundAmountCent)
|
||||
}
|
||||
refundOrder.Status = refundStatus
|
||||
refundOrder.ProviderOrderID = resp.LeshuaRefundID
|
||||
|
||||
dto := toRefundDTO(refundOrder)
|
||||
return &dto, nil
|
||||
}
|
||||
|
||||
// QueryRefundStatus 查询订单最近一笔退款状态。
|
||||
func (r *Repository) QueryRefundStatus(orderID uint64) (*RefundDTO, error) {
|
||||
var payment model.PaymentOrder
|
||||
if err := r.db.Where("order_id = ? AND biz_type IN ?", orderID, refundBizTypes).Order("id DESC").First(&payment).Error; err != nil {
|
||||
if err == gorm.ErrRecordNotFound {
|
||||
return nil, ErrPaymentNotFound
|
||||
}
|
||||
return nil, err
|
||||
}
|
||||
if payment.Status == "refunded" || payment.Status == "failed" || r.isMockMode {
|
||||
dto := toRefundDTO(payment)
|
||||
return &dto, nil
|
||||
}
|
||||
resp, err := r.leshua.QueryRefund(context.Background(), leshua.QueryRefundRequest{
|
||||
ThirdOrderID: payment.ThirdOrderID,
|
||||
MerchantRefundID: payment.ThirdOrderID,
|
||||
LeshuaRefundID: payment.ProviderOrderID,
|
||||
})
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if resp.Status == "11" {
|
||||
now := time.Now()
|
||||
if err := r.db.Model(&model.PaymentOrder{}).Where("id = ?", payment.ID).Updates(map[string]any{
|
||||
"status": "refunded",
|
||||
"paid_at": now,
|
||||
"raw_response": jsonMap(withRawSource(resp.Raw, channelSourceQuery)),
|
||||
}).Error; err != nil {
|
||||
return nil, err
|
||||
}
|
||||
payment.Status = "refunded"
|
||||
payment.PaidAt = &now
|
||||
_ = r.updateOrderRefundStatus(orderID, payment.AmountCent)
|
||||
} else if resp.Status == "12" {
|
||||
if err := r.db.Model(&model.PaymentOrder{}).Where("id = ?", payment.ID).Updates(map[string]any{
|
||||
"status": "failed",
|
||||
"raw_response": jsonMap(withRawSource(resp.Raw, channelSourceQuery)),
|
||||
}).Error; err != nil {
|
||||
return nil, err
|
||||
}
|
||||
payment.Status = "failed"
|
||||
_ = r.markOrderRefundFailed(orderID, payment.AmountCent)
|
||||
}
|
||||
dto := toRefundDTO(payment)
|
||||
return &dto, nil
|
||||
}
|
||||
|
||||
// HandleRefundNotify 处理乐刷退款通知。
|
||||
func (r *Repository) HandleRefundNotify(params map[string]string, rawPayload string, contentType string) (*NotifyResult, error) {
|
||||
var verify leshua.VerifyNotifyResult
|
||||
if !r.isMockMode {
|
||||
verify = r.leshua.VerifyNotifyDetail(params)
|
||||
if !verify.OK {
|
||||
log.Printf("[payment] refund notify verify failed merchant_refund_id=%s", params["merchant_refund_id"])
|
||||
return nil, ErrPaymentVerifyFailed
|
||||
}
|
||||
}
|
||||
merchantRefundID := params["merchant_refund_id"]
|
||||
if merchantRefundID == "" {
|
||||
return nil, ErrPaymentNotFound
|
||||
}
|
||||
var payment model.PaymentOrder
|
||||
if err := r.db.Where("third_order_id = ?", merchantRefundID).First(&payment).Error; err != nil {
|
||||
if err == gorm.ErrRecordNotFound {
|
||||
return nil, ErrPaymentNotFound
|
||||
}
|
||||
return nil, err
|
||||
}
|
||||
raw := withNotifyDiagnostic(params, rawPayload, contentType, verify, "verified")
|
||||
status := params["status"]
|
||||
switch status {
|
||||
case "11":
|
||||
now := time.Now()
|
||||
if err := r.db.Model(&model.PaymentOrder{}).Where("id = ?", payment.ID).Updates(map[string]any{
|
||||
"status": "refunded",
|
||||
"paid_at": now,
|
||||
"notified_at": now,
|
||||
"raw_response": jsonMap(raw),
|
||||
}).Error; err != nil {
|
||||
return nil, err
|
||||
}
|
||||
_ = r.updateOrderRefundStatus(payment.OrderID, payment.AmountCent)
|
||||
case "12":
|
||||
r.db.Model(&model.PaymentOrder{}).Where("id = ?", payment.ID).Updates(map[string]any{
|
||||
"status": "failed",
|
||||
"notified_at": time.Now(),
|
||||
"raw_response": jsonMap(raw),
|
||||
})
|
||||
_ = r.markOrderRefundFailed(payment.OrderID, payment.AmountCent)
|
||||
default:
|
||||
r.db.Model(&model.PaymentOrder{}).Where("id = ?", payment.ID).Updates(map[string]any{
|
||||
"status": "refunding",
|
||||
"raw_response": jsonMap(raw),
|
||||
})
|
||||
}
|
||||
return &NotifyResult{OK: true, Message: "000000"}, nil
|
||||
}
|
||||
|
||||
// updateOrderRefundStatus 更新订单退款成功状态。
|
||||
func (r *Repository) updateOrderRefundStatus(orderID uint64, refundAmountCent int64) error {
|
||||
now := time.Now()
|
||||
return r.db.Model(&model.RentalOrder{}).Where("id = ?", orderID).Updates(map[string]any{
|
||||
"refund_status": "refunded",
|
||||
"refund_amount_cent": refundAmountCent,
|
||||
"refunded_at": now,
|
||||
}).Error
|
||||
}
|
||||
|
||||
func (r *Repository) markOrderRefunding(orderID uint64, refundAmountCent int64) error {
|
||||
return r.db.Model(&model.RentalOrder{}).Where("id = ?", orderID).Updates(map[string]any{
|
||||
"refund_status": "refunding",
|
||||
"refund_amount_cent": refundAmountCent,
|
||||
"refunded_at": nil,
|
||||
}).Error
|
||||
}
|
||||
|
||||
func (r *Repository) markOrderRefundFailed(orderID uint64, refundAmountCent int64) error {
|
||||
return r.db.Model(&model.RentalOrder{}).Where("id = ?", orderID).Updates(map[string]any{
|
||||
"refund_status": "failed",
|
||||
"refund_amount_cent": refundAmountCent,
|
||||
"refunded_at": nil,
|
||||
}).Error
|
||||
}
|
||||
|
||||
func (r *Repository) markRefundFailed(paymentID uint64, orderID uint64, refundAmountCent int64, raw map[string]string) error {
|
||||
if raw == nil {
|
||||
raw = map[string]string{"error": "refund failed"}
|
||||
}
|
||||
if err := r.db.Model(&model.PaymentOrder{}).Where("id = ?", paymentID).Updates(map[string]any{
|
||||
"status": "failed",
|
||||
"raw_response": jsonMap(raw),
|
||||
}).Error; err != nil {
|
||||
return err
|
||||
}
|
||||
return r.markOrderRefundFailed(orderID, refundAmountCent)
|
||||
}
|
||||
|
||||
// toRefundDTO 将支付表里的退款单转换为接口 DTO。
|
||||
func toRefundDTO(payment model.PaymentOrder) RefundDTO {
|
||||
return RefundDTO{
|
||||
ID: payment.ID,
|
||||
PaymentNo: payment.PaymentNo,
|
||||
OrderID: payment.OrderID,
|
||||
OrderNo: payment.OrderNo,
|
||||
BizType: payment.BizType,
|
||||
AmountCent: payment.AmountCent,
|
||||
Status: payment.Status,
|
||||
ProviderOrderID: payment.ProviderOrderID,
|
||||
PaidAt: payment.PaidAt,
|
||||
CreatedAt: payment.CreatedAt,
|
||||
UpdatedAt: payment.UpdatedAt,
|
||||
}
|
||||
}
|
||||
|
||||
func (r *Repository) preparePayment(userID uint64, orderID uint64, req StartPaymentRequest) (*model.PaymentOrder, *model.RentalOrder, error) {
|
||||
var paymentID uint64
|
||||
var orderRow model.RentalOrder
|
||||
@@ -304,7 +589,7 @@ func (r *Repository) preparePayment(userID uint64, orderID uint64, req StartPaym
|
||||
}
|
||||
var existing model.PaymentOrder
|
||||
err := tx.Clauses(clause.Locking{Strength: "UPDATE"}).
|
||||
Where("order_id = ?", row.ID).
|
||||
Where("order_id = ? AND biz_type = ?", row.ID, "order_pay").
|
||||
Order("id DESC").
|
||||
First(&existing).Error
|
||||
if err == nil {
|
||||
@@ -342,6 +627,7 @@ func (r *Repository) preparePayment(userID uint64, orderID uint64, req StartPaym
|
||||
PayWay: firstNonEmpty(req.PayWay, r.cfg.Leshua.PayWay, "ZFBZF"),
|
||||
JSPayFlag: firstNonEmpty(req.JSPayFlag, r.cfg.Leshua.JSPayFlag, "2"),
|
||||
AmountCent: amountCent,
|
||||
BizType: "order_pay",
|
||||
Status: "created",
|
||||
}
|
||||
if r.isMockMode {
|
||||
@@ -382,6 +668,7 @@ func (r *Repository) createWalletRechargePayment(userID uint64, amountCent int64
|
||||
PayWay: firstNonEmpty(req.PayWay, r.cfg.Leshua.PayWay, "ZFBZF"),
|
||||
JSPayFlag: firstNonEmpty(req.JSPayFlag, r.cfg.Leshua.JSPayFlag, "2"),
|
||||
AmountCent: amountCent,
|
||||
BizType: "wallet_recharge",
|
||||
Status: "created",
|
||||
}
|
||||
if r.isMockMode {
|
||||
|
||||
Reference in New Issue
Block a user