2024-11-21 12:18:28 +08:00
|
|
|
package pay
|
|
|
|
|
|
|
|
import (
|
|
|
|
"context"
|
|
|
|
"net/http"
|
|
|
|
"time"
|
2025-04-27 12:17:18 +08:00
|
|
|
"tyc-server/app/main/api/internal/service"
|
2025-04-09 15:58:06 +08:00
|
|
|
"tyc-server/pkg/lzkit/lzUtils"
|
|
|
|
|
2025-04-27 12:17:18 +08:00
|
|
|
"tyc-server/app/main/api/internal/svc"
|
2024-11-21 12:18:28 +08:00
|
|
|
|
|
|
|
"github.com/zeromicro/go-zero/core/logx"
|
|
|
|
)
|
|
|
|
|
|
|
|
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
|
|
|
|
}
|
|
|
|
order, findOrderErr := l.svcCtx.OrderModel.FindOneByOrderNo(l.ctx, *notification.OutTradeNo)
|
|
|
|
if findOrderErr != nil {
|
|
|
|
logx.Errorf("微信支付回调,查找订单信息失败: %+v", findOrderErr)
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
|
|
|
amount := lzUtils.ToWechatAmount(order.Amount)
|
2025-01-18 22:34:27 +08:00
|
|
|
if amount != *notification.Amount.Total {
|
2024-11-21 12:18:28 +08:00
|
|
|
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
|
|
|
|
}
|