package pay import ( "context" "encoding/json" "fmt" "tyc-server/app/main/api/internal/service" "tyc-server/app/main/api/internal/svc" "tyc-server/app/main/api/internal/types" "tyc-server/common/ctxdata" "tyc-server/common/xerr" "github.com/pkg/errors" "github.com/zeromicro/go-zero/core/logx" ) type PaymentLogic struct { logx.Logger ctx context.Context svcCtx *svc.ServiceContext } 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) { 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("%d:%s", userID, outTradeNo) cache, cacheErr := l.svcCtx.Redis.GetCtx(l.ctx, redisKey) if cacheErr != nil { return nil, 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) } var payMethod service.PayMethod switch req.PayMethod { case "alipay": payMethod = service.PayMethodAlipay case "wechat": payMethod = service.PayMethodWechat // case "apple": // payMethod = service.PayMethodApple default: return nil, errors.Wrapf(xerr.NewErrCode(xerr.SERVER_COMMON_ERROR), "生成订单, 不支持的支付方式: %+v", req.PayMethod) } // 创建支付订单 orderReq := &service.CreateOrderRequest{ PayMethod: payMethod, ProductEn: data.Product, } orderResp, err := l.svcCtx.PayService.CreateOrder(l.ctx, orderReq) if err != nil { return nil, errors.Wrapf(xerr.NewErrCode(xerr.SERVER_COMMON_ERROR), "生成订单失败: %+v", err) } return &types.PaymentResp{ PrepayData: orderResp.PayData, PrepayId: orderResp.OrderNo, OrderID: orderResp.OrderID, }, nil }