first commit
This commit is contained in:
216
app/main/api/internal/logic/pay/alipaycallbacklogic.go
Normal file
216
app/main/api/internal/logic/pay/alipaycallbacklogic.go
Normal file
@@ -0,0 +1,216 @@
|
||||
package pay
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"net/http"
|
||||
"strings"
|
||||
"time"
|
||||
"hm-server/pkg/lzkit/lzUtils"
|
||||
|
||||
"github.com/smartwalle/alipay/v3"
|
||||
|
||||
"hm-server/app/main/api/internal/svc"
|
||||
"hm-server/app/main/model"
|
||||
|
||||
"github.com/zeromicro/go-zero/core/logx"
|
||||
"github.com/zeromicro/go-zero/core/stores/sqlx"
|
||||
)
|
||||
|
||||
type AlipayCallbackLogic struct {
|
||||
logx.Logger
|
||||
ctx context.Context
|
||||
svcCtx *svc.ServiceContext
|
||||
}
|
||||
|
||||
func NewAlipayCallbackLogic(ctx context.Context, svcCtx *svc.ServiceContext) *AlipayCallbackLogic {
|
||||
return &AlipayCallbackLogic{
|
||||
Logger: logx.WithContext(ctx),
|
||||
ctx: ctx,
|
||||
svcCtx: svcCtx,
|
||||
}
|
||||
}
|
||||
|
||||
func (l *AlipayCallbackLogic) AlipayCallback(w http.ResponseWriter, r *http.Request) error {
|
||||
notification, err := l.svcCtx.AlipayService.HandleAliPaymentNotification(r)
|
||||
if err != nil {
|
||||
logx.Errorf("支付宝支付回调,%v", err)
|
||||
return nil
|
||||
}
|
||||
|
||||
// 根据订单号前缀判断订单类型
|
||||
orderNo := notification.OutTradeNo
|
||||
if strings.HasPrefix(orderNo, "Q_") {
|
||||
// 查询订单处理
|
||||
return l.handleQueryOrderPayment(w, notification)
|
||||
} else if strings.HasPrefix(orderNo, "A_") {
|
||||
// 代理会员订单处理
|
||||
return l.handleAgentVipOrderPayment(w, notification)
|
||||
} else {
|
||||
// 兼容旧订单,假设没有前缀的是查询订单
|
||||
return l.handleQueryOrderPayment(w, notification)
|
||||
}
|
||||
}
|
||||
|
||||
// 处理查询订单支付
|
||||
func (l *AlipayCallbackLogic) handleQueryOrderPayment(w http.ResponseWriter, notification *alipay.Notification) error {
|
||||
order, findOrderErr := l.svcCtx.OrderModel.FindOneByOrderNo(l.ctx, notification.OutTradeNo)
|
||||
if findOrderErr != nil {
|
||||
logx.Errorf("支付宝支付回调,查找订单失败: %+v", findOrderErr)
|
||||
return nil
|
||||
}
|
||||
|
||||
if order.Status != "pending" {
|
||||
alipay.ACKNotification(w)
|
||||
return nil
|
||||
}
|
||||
|
||||
user, err := l.svcCtx.UserModel.FindOne(l.ctx, order.UserId)
|
||||
if err != nil {
|
||||
logx.Errorf("支付宝支付回调,查找用户失败: %+v", err)
|
||||
return nil
|
||||
}
|
||||
|
||||
amount := lzUtils.ToAlipayAmount(order.Amount)
|
||||
if user.Inside != 1 {
|
||||
// 确保订单金额和状态正确,防止重复更新
|
||||
if amount != notification.TotalAmount {
|
||||
logx.Errorf("支付宝支付回调,金额不一致")
|
||||
return nil
|
||||
}
|
||||
}
|
||||
|
||||
switch notification.TradeStatus {
|
||||
case alipay.TradeStatusSuccess:
|
||||
order.Status = "paid"
|
||||
order.PayTime = lzUtils.TimeToNullTime(time.Now())
|
||||
default:
|
||||
return nil
|
||||
}
|
||||
|
||||
order.PlatformOrderId = lzUtils.StringToNullString(notification.TradeNo)
|
||||
if updateErr := l.svcCtx.OrderModel.UpdateWithVersion(l.ctx, nil, order); updateErr != nil {
|
||||
logx.Errorf("支付宝支付回调,修改订单信息失败: %+v", updateErr)
|
||||
return nil
|
||||
}
|
||||
|
||||
if order.Status == "paid" {
|
||||
if asyncErr := l.svcCtx.AsynqService.SendQueryTask(order.Id); asyncErr != nil {
|
||||
logx.Errorf("异步任务调度失败: %v", asyncErr)
|
||||
return asyncErr
|
||||
}
|
||||
}
|
||||
|
||||
alipay.ACKNotification(w)
|
||||
return nil
|
||||
}
|
||||
|
||||
// 处理代理会员订单支付
|
||||
func (l *AlipayCallbackLogic) handleAgentVipOrderPayment(w http.ResponseWriter, notification *alipay.Notification) error {
|
||||
agentOrder, findAgentOrderErr := l.svcCtx.AgentMembershipRechargeOrderModel.FindOneByOrderNo(l.ctx, notification.OutTradeNo)
|
||||
if findAgentOrderErr != nil {
|
||||
logx.Errorf("支付宝支付回调,查找代理会员订单失败: %+v", findAgentOrderErr)
|
||||
return nil
|
||||
}
|
||||
|
||||
if agentOrder.Status != "pending" {
|
||||
alipay.ACKNotification(w)
|
||||
return nil
|
||||
}
|
||||
|
||||
user, err := l.svcCtx.UserModel.FindOne(l.ctx, agentOrder.UserId)
|
||||
if err != nil {
|
||||
logx.Errorf("支付宝支付回调,查找用户失败: %+v", err)
|
||||
return nil
|
||||
}
|
||||
|
||||
amount := lzUtils.ToAlipayAmount(agentOrder.Amount)
|
||||
if user.Inside != 1 {
|
||||
// 确保订单金额和状态正确,防止重复更新
|
||||
if amount != notification.TotalAmount {
|
||||
logx.Errorf("支付宝支付回调,金额不一致")
|
||||
return nil
|
||||
}
|
||||
}
|
||||
|
||||
switch notification.TradeStatus {
|
||||
case alipay.TradeStatusSuccess:
|
||||
agentOrder.Status = "paid"
|
||||
default:
|
||||
return nil
|
||||
}
|
||||
|
||||
if agentOrder.Status == "paid" {
|
||||
err = l.svcCtx.AgentModel.Trans(l.ctx, func(transCtx context.Context, session sqlx.Session) error {
|
||||
agentModel, err := l.svcCtx.AgentModel.FindOne(transCtx, agentOrder.AgentId)
|
||||
if err != nil {
|
||||
return fmt.Errorf("查找代理信息失败: %+v", err)
|
||||
}
|
||||
agentOrder.PlatformOrderId = lzUtils.StringToNullString(notification.TradeNo)
|
||||
if updateErr := l.svcCtx.AgentMembershipRechargeOrderModel.UpdateWithVersion(l.ctx, nil, agentOrder); updateErr != nil {
|
||||
return fmt.Errorf("修改代理会员订单信息失败: %+v", updateErr)
|
||||
}
|
||||
|
||||
// 设置会员等级
|
||||
agentModel.LevelName = agentOrder.LevelName
|
||||
|
||||
// 延长会员时间
|
||||
// 检查是否是同级续费并记录到日志
|
||||
isRenewal := agentModel.LevelName == agentOrder.LevelName && agentModel.MembershipExpiryTime.Valid
|
||||
if isRenewal {
|
||||
logx.Infof("代理会员续费成功,会员ID:%d,等级:%s", agentModel.Id, agentModel.LevelName)
|
||||
} else {
|
||||
logx.Infof("代理会员新购或升级成功,会员ID:%d,等级:%s", agentModel.Id, agentModel.LevelName)
|
||||
}
|
||||
agentModel.MembershipExpiryTime = lzUtils.RenewMembership(agentModel.MembershipExpiryTime)
|
||||
|
||||
if updateErr := l.svcCtx.AgentModel.UpdateWithVersion(l.ctx, nil, agentModel); updateErr != nil {
|
||||
return fmt.Errorf("修改代理信息失败: %+v", updateErr)
|
||||
}
|
||||
return nil
|
||||
})
|
||||
if err != nil {
|
||||
logx.Errorf("支付宝支付回调,处理代理会员订单失败: %+v", err)
|
||||
refundErr := l.handleRefund(agentOrder)
|
||||
if refundErr != nil {
|
||||
logx.Errorf("支付宝支付回调,退款失败: %+v", refundErr)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
}
|
||||
|
||||
alipay.ACKNotification(w)
|
||||
return nil
|
||||
}
|
||||
|
||||
func (l *AlipayCallbackLogic) handleRefund(order *model.AgentMembershipRechargeOrder) error {
|
||||
ctx := context.Background()
|
||||
// 退款
|
||||
if order.PaymentMethod == "wechat" {
|
||||
refundErr := l.svcCtx.WechatPayService.WeChatRefund(ctx, order.OrderNo, order.Amount, order.Amount)
|
||||
if refundErr != nil {
|
||||
return refundErr
|
||||
}
|
||||
} else {
|
||||
refund, refundErr := l.svcCtx.AlipayService.AliRefund(ctx, order.OrderNo, order.Amount)
|
||||
if refundErr != nil {
|
||||
return refundErr
|
||||
}
|
||||
if refund.IsSuccess() {
|
||||
logx.Errorf("支付宝退款成功, orderID: %d", order.Id)
|
||||
// 更新订单状态为退款
|
||||
order.Status = "refunded"
|
||||
updateOrderErr := l.svcCtx.AgentMembershipRechargeOrderModel.UpdateWithVersion(ctx, nil, order)
|
||||
if updateOrderErr != nil {
|
||||
logx.Errorf("更新订单状态失败,订单ID: %d, 错误: %v", order.Id, updateOrderErr)
|
||||
return fmt.Errorf("更新订单状态失败: %v", updateOrderErr)
|
||||
}
|
||||
return nil
|
||||
} else {
|
||||
logx.Errorf("支付宝退款失败:%v", refundErr)
|
||||
return refundErr
|
||||
}
|
||||
// 直接成功
|
||||
}
|
||||
return nil
|
||||
}
|
||||
82
app/main/api/internal/logic/pay/iapcallbacklogic.go
Normal file
82
app/main/api/internal/logic/pay/iapcallbacklogic.go
Normal file
@@ -0,0 +1,82 @@
|
||||
package pay
|
||||
|
||||
import (
|
||||
"context"
|
||||
"time"
|
||||
"hm-server/app/main/api/internal/svc"
|
||||
"hm-server/app/main/api/internal/types"
|
||||
"hm-server/common/xerr"
|
||||
"hm-server/pkg/lzkit/lzUtils"
|
||||
|
||||
"github.com/pkg/errors"
|
||||
|
||||
"github.com/zeromicro/go-zero/core/logx"
|
||||
)
|
||||
|
||||
type IapCallbackLogic struct {
|
||||
logx.Logger
|
||||
ctx context.Context
|
||||
svcCtx *svc.ServiceContext
|
||||
}
|
||||
|
||||
func NewIapCallbackLogic(ctx context.Context, svcCtx *svc.ServiceContext) *IapCallbackLogic {
|
||||
return &IapCallbackLogic{
|
||||
Logger: logx.WithContext(ctx),
|
||||
ctx: ctx,
|
||||
svcCtx: svcCtx,
|
||||
}
|
||||
}
|
||||
|
||||
func (l *IapCallbackLogic) IapCallback(req *types.IapCallbackReq) error {
|
||||
// Step 1: 查找订单
|
||||
order, findOrderErr := l.svcCtx.OrderModel.FindOne(l.ctx, req.OrderID)
|
||||
if findOrderErr != nil {
|
||||
logx.Errorf("苹果内购支付回调,查找订单失败: %+v", findOrderErr)
|
||||
return nil
|
||||
}
|
||||
|
||||
// Step 2: 验证订单状态
|
||||
if order.Status != "pending" {
|
||||
return errors.Wrapf(xerr.NewErrCode(xerr.SERVER_COMMON_ERROR), "苹果内购支付回调, 订单状态异常: %+v", order)
|
||||
}
|
||||
|
||||
// Step 3: 调用 VerifyReceipt 验证苹果支付凭证
|
||||
//receipt := req.TransactionReceipt // 从请求中获取支付凭证
|
||||
//verifyResponse, verifyErr := l.svcCtx.ApplePayService.VerifyReceipt(l.ctx, receipt)
|
||||
//if verifyErr != nil {
|
||||
// return errors.Wrapf(xerr.NewErrCode(xerr.SERVER_COMMON_ERROR), "苹果内购支付回调, 验证订单异常: %+v", verifyErr)
|
||||
//}
|
||||
|
||||
// Step 4: 验证订单
|
||||
//product, findProductErr := l.svcCtx.ProductModel.FindOne(l.ctx, order.Id)
|
||||
//if findProductErr != nil {
|
||||
// return errors.Wrapf(xerr.NewErrCode(xerr.DB_ERROR), "苹果内购支付回调, 获取订单相关商品失败: %+v", findProductErr)
|
||||
//}
|
||||
//isProductMatched := false
|
||||
//appleProductID := l.svcCtx.ApplePayService.GetIappayAppID(product.ProductEn)
|
||||
//for _, item := range verifyResponse.Receipt.InApp {
|
||||
// if item.ProductID == appleProductID {
|
||||
// isProductMatched = true
|
||||
// order.PlatformOrderId = lzUtils.StringToNullString(item.TransactionID) // 记录交易 ID
|
||||
// break
|
||||
// }
|
||||
//}
|
||||
//if !isProductMatched {
|
||||
// return errors.Wrapf(xerr.NewErrCode(xerr.SERVER_COMMON_ERROR), "苹果内购支付回调, 商品 ID 不匹配,订单 ID: %d, 回调苹果商品 ID: %s", order.Id, verifyResponse.Receipt.InApp[0].ProductID)
|
||||
//}
|
||||
|
||||
// Step 5: 更新订单状态 mm
|
||||
order.Status = "paid"
|
||||
order.PayTime = lzUtils.TimeToNullTime(time.Now())
|
||||
|
||||
// 更新订单到数据库
|
||||
if updateErr := l.svcCtx.OrderModel.UpdateWithVersion(l.ctx, nil, order); updateErr != nil {
|
||||
return errors.Wrapf(xerr.NewErrCode(xerr.SERVER_COMMON_ERROR), "苹果内购支付回调, 修改订单信息失败: %+v", updateErr)
|
||||
}
|
||||
|
||||
// Step 6: 处理订单完成后的逻辑
|
||||
if asyncErr := l.svcCtx.AsynqService.SendQueryTask(order.Id); asyncErr != nil {
|
||||
return errors.Wrapf(xerr.NewErrCode(xerr.SERVER_COMMON_ERROR), "苹果内购支付回调,异步任务调度失败: %v", asyncErr)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
49
app/main/api/internal/logic/pay/paymentchecklogic.go
Normal file
49
app/main/api/internal/logic/pay/paymentchecklogic.go
Normal file
@@ -0,0 +1,49 @@
|
||||
package pay
|
||||
|
||||
import (
|
||||
"context"
|
||||
"strings"
|
||||
|
||||
"hm-server/app/main/api/internal/svc"
|
||||
"hm-server/app/main/api/internal/types"
|
||||
"hm-server/common/xerr"
|
||||
|
||||
"github.com/pkg/errors"
|
||||
"github.com/zeromicro/go-zero/core/logx"
|
||||
)
|
||||
|
||||
type PaymentCheckLogic struct {
|
||||
logx.Logger
|
||||
ctx context.Context
|
||||
svcCtx *svc.ServiceContext
|
||||
}
|
||||
|
||||
func NewPaymentCheckLogic(ctx context.Context, svcCtx *svc.ServiceContext) *PaymentCheckLogic {
|
||||
return &PaymentCheckLogic{
|
||||
Logger: logx.WithContext(ctx),
|
||||
ctx: ctx,
|
||||
svcCtx: svcCtx,
|
||||
}
|
||||
}
|
||||
|
||||
func (l *PaymentCheckLogic) PaymentCheck(req *types.PaymentCheckReq) (resp *types.PaymentCheckResp, err error) {
|
||||
if strings.HasPrefix(req.OrderNo, "A_") {
|
||||
order, err := l.svcCtx.AgentMembershipRechargeOrderModel.FindOneByOrderNo(l.ctx, req.OrderNo)
|
||||
if err != nil {
|
||||
return nil, errors.Wrapf(xerr.NewErrCode(xerr.DB_ERROR), "查询订单失败: %v", err)
|
||||
}
|
||||
return &types.PaymentCheckResp{
|
||||
Type: "agent_vip",
|
||||
Status: order.Status,
|
||||
}, nil
|
||||
} else {
|
||||
order, err := l.svcCtx.OrderModel.FindOneByOrderNo(l.ctx, req.OrderNo)
|
||||
if err != nil {
|
||||
return nil, errors.Wrapf(xerr.NewErrCode(xerr.DB_ERROR), "查询订单失败: %v", err)
|
||||
}
|
||||
return &types.PaymentCheckResp{
|
||||
Type: "query",
|
||||
Status: order.Status,
|
||||
}, nil
|
||||
}
|
||||
}
|
||||
227
app/main/api/internal/logic/pay/paymentlogic.go
Normal file
227
app/main/api/internal/logic/pay/paymentlogic.go
Normal file
@@ -0,0 +1,227 @@
|
||||
package pay
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/hex"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"hm-server/app/main/api/internal/svc"
|
||||
"hm-server/app/main/api/internal/types"
|
||||
"hm-server/app/main/model"
|
||||
"hm-server/common/ctxdata"
|
||||
"hm-server/common/xerr"
|
||||
"hm-server/pkg/lzkit/crypto"
|
||||
|
||||
"github.com/pkg/errors"
|
||||
"github.com/redis/go-redis/v9"
|
||||
"github.com/zeromicro/go-zero/core/logx"
|
||||
"github.com/zeromicro/go-zero/core/stores/sqlx"
|
||||
)
|
||||
|
||||
type PaymentLogic struct {
|
||||
logx.Logger
|
||||
ctx context.Context
|
||||
svcCtx *svc.ServiceContext
|
||||
}
|
||||
type PaymentTypeResp struct {
|
||||
amount float64
|
||||
outTradeNo string
|
||||
description string
|
||||
}
|
||||
|
||||
func NewPaymentLogic(ctx context.Context, svcCtx *svc.ServiceContext) *PaymentLogic {
|
||||
return &PaymentLogic{
|
||||
Logger: logx.WithContext(ctx),
|
||||
ctx: ctx,
|
||||
svcCtx: svcCtx,
|
||||
}
|
||||
}
|
||||
|
||||
func (l *PaymentLogic) Payment(req *types.PaymentReq) (resp *types.PaymentResp, err error) {
|
||||
var paymentTypeResp *PaymentTypeResp
|
||||
var prepayData interface{}
|
||||
l.svcCtx.OrderModel.Trans(l.ctx, func(ctx context.Context, session sqlx.Session) error {
|
||||
switch req.PayType {
|
||||
case "agent_vip":
|
||||
paymentTypeResp, err = l.AgentVipOrderPayment(req, session)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
case "query":
|
||||
paymentTypeResp, err = l.QueryOrderPayment(req, session)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
|
||||
var createOrderErr error
|
||||
if req.PayMethod == "wechat" {
|
||||
prepayData, createOrderErr = l.svcCtx.WechatPayService.CreateWechatOrder(l.ctx, paymentTypeResp.amount, paymentTypeResp.description, paymentTypeResp.outTradeNo)
|
||||
} else if req.PayMethod == "alipay" {
|
||||
prepayData, createOrderErr = l.svcCtx.AlipayService.CreateAlipayOrder(l.ctx, paymentTypeResp.amount, paymentTypeResp.description, paymentTypeResp.outTradeNo)
|
||||
} else if req.PayMethod == "appleiap" {
|
||||
prepayData = l.svcCtx.ApplePayService.GetIappayAppID(paymentTypeResp.outTradeNo)
|
||||
}
|
||||
if createOrderErr != nil {
|
||||
return errors.Wrapf(xerr.NewErrCode(xerr.SERVER_COMMON_ERROR), "生成订单, 创建支付订单失败: %+v", createOrderErr)
|
||||
}
|
||||
return nil
|
||||
})
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
switch v := prepayData.(type) {
|
||||
case string:
|
||||
// 如果 prepayData 是字符串类型,直接返回
|
||||
return &types.PaymentResp{PrepayId: v, OrderNo: paymentTypeResp.outTradeNo}, nil
|
||||
default:
|
||||
return &types.PaymentResp{PrepayData: prepayData, OrderNo: paymentTypeResp.outTradeNo}, nil
|
||||
}
|
||||
}
|
||||
|
||||
func (l *PaymentLogic) QueryOrderPayment(req *types.PaymentReq, session sqlx.Session) (resp *PaymentTypeResp, err error) {
|
||||
userID, getUidErr := ctxdata.GetUidFromCtx(l.ctx)
|
||||
if getUidErr != nil {
|
||||
return nil, errors.Wrapf(xerr.NewErrCode(xerr.SERVER_COMMON_ERROR), "生成订单, 获取用户信息失败, %+v", getUidErr)
|
||||
}
|
||||
outTradeNo := req.Id
|
||||
redisKey := fmt.Sprintf(types.QueryCacheKey, userID, outTradeNo)
|
||||
cache, cacheErr := l.svcCtx.Redis.GetCtx(l.ctx, redisKey)
|
||||
if cacheErr != nil {
|
||||
if cacheErr == redis.Nil {
|
||||
return nil, errors.Wrapf(xerr.NewErrMsg("订单已过期"), "生成订单, 缓存不存在, %+v", cacheErr)
|
||||
}
|
||||
return nil, errors.Wrapf(xerr.NewErrCode(xerr.SERVER_COMMON_ERROR), "生成订单, 获取缓存失败, %+v", cacheErr)
|
||||
}
|
||||
var data types.QueryCacheLoad
|
||||
err = json.Unmarshal([]byte(cache), &data)
|
||||
if err != nil {
|
||||
return nil, errors.Wrapf(xerr.NewErrCode(xerr.SERVER_COMMON_ERROR), "生成订单, 解析缓存内容失败, %v", err)
|
||||
}
|
||||
|
||||
product, err := l.svcCtx.ProductModel.FindOneByProductEn(l.ctx, data.Product)
|
||||
if err != nil {
|
||||
return nil, errors.Wrapf(xerr.NewErrCode(xerr.SERVER_COMMON_ERROR), "生成订单, 查找产品错误: %v", err)
|
||||
}
|
||||
|
||||
var amount float64
|
||||
user, err := l.svcCtx.UserModel.FindOne(l.ctx, userID)
|
||||
if err != nil {
|
||||
return nil, errors.Wrapf(xerr.NewErrCode(xerr.DB_ERROR), "生成订单, 获取用户信息失败: %v", err)
|
||||
}
|
||||
|
||||
if data.AgentIdentifier != "" {
|
||||
agentLinkModel, findAgentLinkErr := l.svcCtx.AgentLinkModel.FindOneByLinkIdentifier(l.ctx, data.AgentIdentifier)
|
||||
if findAgentLinkErr != nil {
|
||||
return nil, errors.Wrapf(xerr.NewErrCode(xerr.DB_ERROR), "生成订单, 获取代理订单失败: %+v", findAgentLinkErr)
|
||||
}
|
||||
amount = agentLinkModel.Price
|
||||
} else {
|
||||
amount = product.SellPrice
|
||||
}
|
||||
|
||||
if user.Inside == 1 {
|
||||
amount = 0.01
|
||||
}
|
||||
var orderID int64
|
||||
order := model.Order{
|
||||
OrderNo: outTradeNo,
|
||||
UserId: userID,
|
||||
ProductId: product.Id,
|
||||
PaymentPlatform: req.PayMethod,
|
||||
PaymentScene: "app",
|
||||
Amount: amount,
|
||||
Status: "pending",
|
||||
}
|
||||
orderInsertResult, insertOrderErr := l.svcCtx.OrderModel.Insert(l.ctx, session, &order)
|
||||
if insertOrderErr != nil {
|
||||
return nil, errors.Wrapf(xerr.NewErrCode(xerr.DB_ERROR), "生成订单, 保存订单失败: %+v", insertOrderErr)
|
||||
}
|
||||
insertedOrderID, lastInsertIdErr := orderInsertResult.LastInsertId()
|
||||
if lastInsertIdErr != nil {
|
||||
return nil, errors.Wrapf(xerr.NewErrCode(xerr.DB_ERROR), "生成订单, 获取保存订单ID失败: %+v", lastInsertIdErr)
|
||||
}
|
||||
orderID = insertedOrderID
|
||||
|
||||
if data.AgentIdentifier != "" {
|
||||
agent, parsingErr := l.agentParsing(data.AgentIdentifier)
|
||||
if parsingErr != nil {
|
||||
return nil, errors.Wrapf(xerr.NewErrCode(xerr.DB_ERROR), "生成订单, 解析代理标识符失败: %+v", parsingErr)
|
||||
}
|
||||
var agentOrder model.AgentOrder
|
||||
agentOrder.OrderId = orderID
|
||||
agentOrder.AgentId = agent.AgentID
|
||||
_, agentOrderInsert := l.svcCtx.AgentOrderModel.Insert(l.ctx, session, &agentOrder)
|
||||
if agentOrderInsert != nil {
|
||||
return nil, errors.Wrapf(xerr.NewErrCode(xerr.DB_ERROR), "生成订单, 保存代理订单失败: %+v", agentOrderInsert)
|
||||
}
|
||||
}
|
||||
return &PaymentTypeResp{amount: amount, outTradeNo: outTradeNo, description: product.ProductName}, nil
|
||||
}
|
||||
func (l *PaymentLogic) AgentVipOrderPayment(req *types.PaymentReq, session sqlx.Session) (resp *PaymentTypeResp, err error) {
|
||||
userID, getUidErr := ctxdata.GetUidFromCtx(l.ctx)
|
||||
if getUidErr != nil {
|
||||
return nil, errors.Wrapf(xerr.NewErrCode(xerr.SERVER_COMMON_ERROR), "生成订单, 获取用户信息失败, %+v", getUidErr)
|
||||
}
|
||||
user, err := l.svcCtx.UserModel.FindOne(l.ctx, userID)
|
||||
if err != nil {
|
||||
return nil, errors.Wrapf(xerr.NewErrCode(xerr.DB_ERROR), "生成订单, 获取用户信息失败: %v", err)
|
||||
}
|
||||
// 查询用户代理信息
|
||||
agentModel, err := l.svcCtx.AgentModel.FindOneByUserId(l.ctx, userID)
|
||||
if err != nil {
|
||||
return nil, errors.Wrapf(xerr.NewErrCode(xerr.DB_ERROR), "查询代理信息失败: %v", err)
|
||||
}
|
||||
redisKey := fmt.Sprintf(types.AgentVipCacheKey, userID, req.Id)
|
||||
cache, cacheErr := l.svcCtx.Redis.GetCtx(l.ctx, redisKey)
|
||||
if cacheErr != nil {
|
||||
return nil, errors.Wrapf(xerr.NewErrCode(xerr.SERVER_COMMON_ERROR), "生成订单, 获取缓存失败, %+v", cacheErr)
|
||||
}
|
||||
var agentVipCache types.AgentVipCache
|
||||
err = json.Unmarshal([]byte(cache), &agentVipCache)
|
||||
if err != nil {
|
||||
return nil, errors.Wrapf(xerr.NewErrCode(xerr.SERVER_COMMON_ERROR), "生成订单, 解析缓存内容失败, %+v", err)
|
||||
}
|
||||
agentMembershipConfig, err := l.svcCtx.AgentMembershipConfigModel.FindOneByLevelName(l.ctx, agentVipCache.Type)
|
||||
if err != nil {
|
||||
return nil, errors.Wrapf(xerr.NewErrCode(xerr.SERVER_COMMON_ERROR), "生成订单, 获取代理会员配置失败, %+v", err)
|
||||
}
|
||||
|
||||
amount := agentMembershipConfig.Price.Float64
|
||||
if user.Inside == 1 {
|
||||
amount = 0.01
|
||||
}
|
||||
agentMembershipRechargeOrder := model.AgentMembershipRechargeOrder{
|
||||
OrderNo: req.Id,
|
||||
UserId: userID,
|
||||
AgentId: agentModel.Id,
|
||||
Amount: amount,
|
||||
PaymentMethod: req.PayMethod,
|
||||
LevelName: agentVipCache.Type,
|
||||
Status: "pending",
|
||||
}
|
||||
_, err = l.svcCtx.AgentMembershipRechargeOrderModel.Insert(l.ctx, session, &agentMembershipRechargeOrder)
|
||||
if err != nil {
|
||||
return nil, errors.Wrapf(xerr.NewErrCode(xerr.DB_ERROR), "生成订单, 保存代理会员充值订单失败: %+v", err)
|
||||
}
|
||||
return &PaymentTypeResp{amount: amount, outTradeNo: req.Id, description: fmt.Sprintf("%s代理会员充值", agentMembershipConfig.LevelName)}, nil
|
||||
}
|
||||
func (l *PaymentLogic) agentParsing(agentIdentifier string) (*types.AgentIdentifier, error) {
|
||||
key, decodeErr := hex.DecodeString("8e3e7a2f60edb49221e953b9c029ed10")
|
||||
if decodeErr != nil {
|
||||
return nil, errors.Wrapf(xerr.NewErrCode(xerr.SERVER_COMMON_ERROR), "查询服务, 获取AES密钥失败: %+v", decodeErr)
|
||||
}
|
||||
// Encrypt the params
|
||||
|
||||
encrypted, err := crypto.AesDecryptURL(agentIdentifier, key)
|
||||
if err != nil {
|
||||
return nil, errors.Wrapf(xerr.NewErrCode(xerr.SERVER_COMMON_ERROR), "查询服务, %v", err)
|
||||
}
|
||||
var agentIdentifierStruct types.AgentIdentifier
|
||||
err = json.Unmarshal(encrypted, &agentIdentifierStruct)
|
||||
if err != nil {
|
||||
return nil, errors.Wrapf(xerr.NewErrCode(xerr.SERVER_COMMON_ERROR), "查询服务,反序列化失败 %v", err)
|
||||
}
|
||||
return &agentIdentifierStruct, nil
|
||||
}
|
||||
215
app/main/api/internal/logic/pay/wechatpaycallbacklogic.go
Normal file
215
app/main/api/internal/logic/pay/wechatpaycallbacklogic.go
Normal file
@@ -0,0 +1,215 @@
|
||||
package pay
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"net/http"
|
||||
"strings"
|
||||
"time"
|
||||
"hm-server/app/main/api/internal/service"
|
||||
"hm-server/app/main/model"
|
||||
"hm-server/pkg/lzkit/lzUtils"
|
||||
|
||||
"hm-server/app/main/api/internal/svc"
|
||||
|
||||
"github.com/wechatpay-apiv3/wechatpay-go/services/payments"
|
||||
"github.com/zeromicro/go-zero/core/logx"
|
||||
"github.com/zeromicro/go-zero/core/stores/sqlx"
|
||||
)
|
||||
|
||||
type WechatPayCallbackLogic struct {
|
||||
logx.Logger
|
||||
ctx context.Context
|
||||
svcCtx *svc.ServiceContext
|
||||
}
|
||||
|
||||
func NewWechatPayCallbackLogic(ctx context.Context, svcCtx *svc.ServiceContext) *WechatPayCallbackLogic {
|
||||
return &WechatPayCallbackLogic{
|
||||
Logger: logx.WithContext(ctx),
|
||||
ctx: ctx,
|
||||
svcCtx: svcCtx,
|
||||
}
|
||||
}
|
||||
|
||||
func (l *WechatPayCallbackLogic) WechatPayCallback(w http.ResponseWriter, r *http.Request) error {
|
||||
notification, err := l.svcCtx.WechatPayService.HandleWechatPayNotification(l.ctx, r)
|
||||
if err != nil {
|
||||
logx.Errorf("微信支付回调,%v", err)
|
||||
return nil
|
||||
}
|
||||
|
||||
// 根据订单号前缀判断订单类型
|
||||
orderNo := *notification.OutTradeNo
|
||||
if strings.HasPrefix(orderNo, "Q_") {
|
||||
// 查询订单处理
|
||||
return l.handleQueryOrderPayment(w, notification)
|
||||
} else if strings.HasPrefix(orderNo, "A_") {
|
||||
// 代理会员订单处理
|
||||
return l.handleAgentVipOrderPayment(w, notification)
|
||||
} else {
|
||||
// 兼容旧订单,假设没有前缀的是查询订单
|
||||
return l.handleQueryOrderPayment(w, notification)
|
||||
}
|
||||
}
|
||||
|
||||
// 处理查询订单支付
|
||||
func (l *WechatPayCallbackLogic) handleQueryOrderPayment(w http.ResponseWriter, notification *payments.Transaction) error {
|
||||
order, findOrderErr := l.svcCtx.OrderModel.FindOneByOrderNo(l.ctx, *notification.OutTradeNo)
|
||||
if findOrderErr != nil {
|
||||
logx.Errorf("微信支付回调,查找订单信息失败: %+v", findOrderErr)
|
||||
return nil
|
||||
}
|
||||
|
||||
amount := lzUtils.ToWechatAmount(order.Amount)
|
||||
if amount != *notification.Amount.Total {
|
||||
logx.Errorf("微信支付回调,金额不一致")
|
||||
return nil
|
||||
}
|
||||
|
||||
if order.Status != "pending" {
|
||||
w.WriteHeader(http.StatusOK)
|
||||
_, _ = w.Write([]byte("success"))
|
||||
return nil
|
||||
}
|
||||
|
||||
switch *notification.TradeState {
|
||||
case service.TradeStateSuccess:
|
||||
order.Status = "paid"
|
||||
order.PayTime = lzUtils.TimeToNullTime(time.Now())
|
||||
case service.TradeStateClosed:
|
||||
order.Status = "closed"
|
||||
order.CloseTime = lzUtils.TimeToNullTime(time.Now())
|
||||
case service.TradeStateRevoked:
|
||||
order.Status = "failed"
|
||||
default:
|
||||
return nil
|
||||
}
|
||||
|
||||
order.PlatformOrderId = lzUtils.StringToNullString(*notification.TransactionId)
|
||||
if updateErr := l.svcCtx.OrderModel.UpdateWithVersion(l.ctx, nil, order); updateErr != nil {
|
||||
logx.Errorf("微信支付回调,更新订单失败%+v", updateErr)
|
||||
return nil
|
||||
}
|
||||
|
||||
if order.Status == "paid" {
|
||||
if asyncErr := l.svcCtx.AsynqService.SendQueryTask(order.Id); asyncErr != nil {
|
||||
logx.Errorf("异步任务调度失败: %v", asyncErr)
|
||||
return asyncErr
|
||||
}
|
||||
}
|
||||
|
||||
w.WriteHeader(http.StatusOK)
|
||||
_, _ = w.Write([]byte("success"))
|
||||
return nil
|
||||
}
|
||||
|
||||
// 处理代理会员订单支付
|
||||
func (l *WechatPayCallbackLogic) handleAgentVipOrderPayment(w http.ResponseWriter, notification *payments.Transaction) error {
|
||||
agentOrder, findAgentOrderErr := l.svcCtx.AgentMembershipRechargeOrderModel.FindOneByOrderNo(l.ctx, *notification.OutTradeNo)
|
||||
if findAgentOrderErr != nil {
|
||||
logx.Errorf("微信支付回调,查找代理会员订单失败: %+v", findAgentOrderErr)
|
||||
return nil
|
||||
}
|
||||
|
||||
if agentOrder.Status != "pending" {
|
||||
w.WriteHeader(http.StatusOK)
|
||||
_, _ = w.Write([]byte("success"))
|
||||
return nil
|
||||
}
|
||||
|
||||
user, err := l.svcCtx.UserModel.FindOne(l.ctx, agentOrder.UserId)
|
||||
if err != nil {
|
||||
logx.Errorf("微信支付回调,查找用户失败: %+v", err)
|
||||
return nil
|
||||
}
|
||||
|
||||
amount := lzUtils.ToWechatAmount(agentOrder.Amount)
|
||||
if user.Inside != 1 {
|
||||
if amount != *notification.Amount.Total {
|
||||
logx.Errorf("微信支付回调,金额不一致")
|
||||
return nil
|
||||
}
|
||||
}
|
||||
|
||||
switch *notification.TradeState {
|
||||
case service.TradeStateSuccess:
|
||||
agentOrder.Status = "paid"
|
||||
default:
|
||||
return nil
|
||||
}
|
||||
|
||||
if agentOrder.Status == "paid" {
|
||||
err = l.svcCtx.AgentModel.Trans(l.ctx, func(transCtx context.Context, session sqlx.Session) error {
|
||||
agentModel, err := l.svcCtx.AgentModel.FindOne(transCtx, agentOrder.AgentId)
|
||||
if err != nil {
|
||||
return fmt.Errorf("查找代理信息失败: %+v", err)
|
||||
}
|
||||
|
||||
agentOrder.PlatformOrderId = lzUtils.StringToNullString(*notification.TransactionId)
|
||||
if updateErr := l.svcCtx.AgentMembershipRechargeOrderModel.UpdateWithVersion(l.ctx, nil, agentOrder); updateErr != nil {
|
||||
return fmt.Errorf("修改代理会员订单信息失败: %+v", updateErr)
|
||||
}
|
||||
|
||||
// 设置会员等级
|
||||
agentModel.LevelName = agentOrder.LevelName
|
||||
|
||||
// 延长会员时间
|
||||
isRenewal := agentModel.LevelName == agentOrder.LevelName && agentModel.MembershipExpiryTime.Valid
|
||||
if isRenewal {
|
||||
logx.Infof("代理会员续费成功,会员ID:%d,等级:%s", agentModel.Id, agentModel.LevelName)
|
||||
} else {
|
||||
logx.Infof("代理会员新购或升级成功,会员ID:%d,等级:%s", agentModel.Id, agentModel.LevelName)
|
||||
}
|
||||
agentModel.MembershipExpiryTime = lzUtils.RenewMembership(agentModel.MembershipExpiryTime)
|
||||
|
||||
if updateErr := l.svcCtx.AgentModel.UpdateWithVersion(l.ctx, nil, agentModel); updateErr != nil {
|
||||
return fmt.Errorf("修改代理信息失败: %+v", updateErr)
|
||||
}
|
||||
return nil
|
||||
})
|
||||
|
||||
if err != nil {
|
||||
logx.Errorf("微信支付回调,处理代理会员订单失败: %+v", err)
|
||||
refundErr := l.handleRefund(agentOrder)
|
||||
if refundErr != nil {
|
||||
logx.Errorf("微信支付回调,退款失败: %+v", refundErr)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
}
|
||||
|
||||
w.WriteHeader(http.StatusOK)
|
||||
_, _ = w.Write([]byte("success"))
|
||||
return nil
|
||||
}
|
||||
|
||||
func (l *WechatPayCallbackLogic) handleRefund(order *model.AgentMembershipRechargeOrder) error {
|
||||
ctx := context.Background()
|
||||
// 退款
|
||||
if order.PaymentMethod == "wechat" {
|
||||
refundErr := l.svcCtx.WechatPayService.WeChatRefund(ctx, order.OrderNo, order.Amount, order.Amount)
|
||||
if refundErr != nil {
|
||||
return refundErr
|
||||
}
|
||||
} else {
|
||||
refund, refundErr := l.svcCtx.AlipayService.AliRefund(ctx, order.OrderNo, order.Amount)
|
||||
if refundErr != nil {
|
||||
return refundErr
|
||||
}
|
||||
if refund.IsSuccess() {
|
||||
logx.Errorf("支付宝退款成功, orderID: %d", order.Id)
|
||||
// 更新订单状态为退款
|
||||
order.Status = "refunded"
|
||||
updateOrderErr := l.svcCtx.AgentMembershipRechargeOrderModel.UpdateWithVersion(ctx, nil, order)
|
||||
if updateOrderErr != nil {
|
||||
logx.Errorf("更新订单状态失败,订单ID: %d, 错误: %v", order.Id, updateOrderErr)
|
||||
return fmt.Errorf("更新订单状态失败: %v", updateOrderErr)
|
||||
}
|
||||
return nil
|
||||
} else {
|
||||
logx.Errorf("支付宝退款失败:%v", refundErr)
|
||||
return refundErr
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
@@ -0,0 +1,55 @@
|
||||
package pay
|
||||
|
||||
import (
|
||||
"context"
|
||||
"net/http"
|
||||
"hm-server/app/main/api/internal/svc"
|
||||
|
||||
"github.com/wechatpay-apiv3/wechatpay-go/services/refunddomestic"
|
||||
"github.com/zeromicro/go-zero/core/logx"
|
||||
)
|
||||
|
||||
type WechatPayRefundCallbackLogic struct {
|
||||
logx.Logger
|
||||
ctx context.Context
|
||||
svcCtx *svc.ServiceContext
|
||||
}
|
||||
|
||||
func NewWechatPayRefundCallbackLogic(ctx context.Context, svcCtx *svc.ServiceContext) *WechatPayRefundCallbackLogic {
|
||||
return &WechatPayRefundCallbackLogic{
|
||||
Logger: logx.WithContext(ctx),
|
||||
ctx: ctx,
|
||||
svcCtx: svcCtx,
|
||||
}
|
||||
}
|
||||
|
||||
func (l *WechatPayRefundCallbackLogic) WechatPayRefundCallback(w http.ResponseWriter, r *http.Request) error {
|
||||
notification, err := l.svcCtx.WechatPayService.HandleRefundNotification(l.ctx, r)
|
||||
if err != nil {
|
||||
logx.Errorf("微信退款回调,%v", err)
|
||||
return nil
|
||||
}
|
||||
order, findOrderErr := l.svcCtx.OrderModel.FindOneByOrderNo(l.ctx, *notification.OutTradeNo)
|
||||
if findOrderErr != nil {
|
||||
logx.Errorf("微信退款回调,查找订单信息失败: %+v", findOrderErr)
|
||||
return nil
|
||||
}
|
||||
|
||||
switch *notification.Status {
|
||||
case refunddomestic.STATUS_SUCCESS:
|
||||
order.Status = "refunded"
|
||||
case refunddomestic.STATUS_ABNORMAL:
|
||||
// 异常
|
||||
return nil
|
||||
default:
|
||||
return nil
|
||||
}
|
||||
if updateErr := l.svcCtx.OrderModel.UpdateWithVersion(l.ctx, nil, order); updateErr != nil {
|
||||
logx.Errorf("微信退款回调,更新订单失败%+v", updateErr)
|
||||
return nil
|
||||
}
|
||||
// 响应微信回调成功
|
||||
w.WriteHeader(http.StatusOK)
|
||||
_, _ = w.Write([]byte("success")) // 确保只写入一次响应
|
||||
return nil
|
||||
}
|
||||
Reference in New Issue
Block a user