🎨 优化余额支付逻辑

This commit is contained in:
2025-07-31 02:40:37 +08:00
parent 4ce59a3090
commit da1ebd72f4

View File

@@ -2,6 +2,7 @@ package app
import (
"fmt"
"git.echol.cn/loser/lckt/global"
"git.echol.cn/loser/lckt/model/app"
"git.echol.cn/loser/lckt/model/app/request"
@@ -112,16 +113,22 @@ func (s *OrderService) BalancePay(p request.BalancePay) error {
global.GVA_LOG.Error("查询用户信息失败", zap.Error(err))
return err
}
// 将user.Balance转为int64类型进行比较
balance := int64(user.Balance)
if balance < order.Price/100 { // 订单价格是以分为单位存储的
global.GVA_LOG.Error("用户余额不足", zap.Int64("balance", balance), zap.Int64("order_price", order.Price))
// 将订单价格从分转换为元(保持精度)
orderPriceInYuan := float64(order.Price) / 100.0
// 检查用户余额是否足够使用float64进行比较避免精度丢失
if user.Balance < float32(orderPriceInYuan) {
global.GVA_LOG.Error("用户余额不足",
zap.Float32("balance", user.Balance),
zap.Float64("order_price_yuan", orderPriceInYuan),
zap.Int64("order_price_cent", order.Price))
return fmt.Errorf("用户余额不足")
}
// 扣除用户余额
balance -= order.Price / 100
err = global.GVA_DB.Model(&user).Where("id = ?", p.UserId).Update("balance", balance).Error
// 扣除用户余额(保持精度)
newBalance := user.Balance - float32(orderPriceInYuan)
err = global.GVA_DB.Model(&user).Where("id = ?", p.UserId).Update("balance", newBalance).Error
if err != nil {
global.GVA_LOG.Error("扣除用户余额失败", zap.Error(err))
return err