79 lines
		
	
	
		
			2.2 KiB
		
	
	
	
		
			Go
		
	
	
	
	
	
			
		
		
	
	
			79 lines
		
	
	
		
			2.2 KiB
		
	
	
	
		
			Go
		
	
	
	
	
	
| package pay
 | |
| 
 | |
| import (
 | |
| 	"context"
 | |
| 	"net/http"
 | |
| 	"time"
 | |
| 	"tydata-server/app/user/cmd/api/internal/service"
 | |
| 	"tydata-server/pkg/lzkit/lzUtils"
 | |
| 
 | |
| 	"github.com/zeromicro/go-zero/core/logx"
 | |
| 	"tydata-server/app/user/cmd/api/internal/svc"
 | |
| )
 | |
| 
 | |
| 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)
 | |
| 	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
 | |
| }
 |