diff --git a/model/gmodel/fs_order_logic.go b/model/gmodel/fs_order_logic.go index 6fa62a1a..503231af 100644 --- a/model/gmodel/fs_order_logic.go +++ b/model/gmodel/fs_order_logic.go @@ -40,7 +40,7 @@ type PayInfo struct { Metadata map[string]interface{} `json:"metadata"` // 额外参数 PayAmount AmountInfo `json:"pay_amount"` // 金额明细 PayMethod string `json:"pay_method"` // 交易方式 - PayTime **time.Time `json:"pay_time"` // 支付时间 + PayTime *time.Time `json:"pay_time"` // 支付时间 Status PayStatus `json:"status"` // 当前状态 StatusLink []PayStatus `json:"status_link"` // 状态链路 TradeNo string `json:"trade_no"` // 支付交易号 diff --git a/server/pay/internal/logic/stripewebhooklogic.go b/server/pay/internal/logic/stripewebhooklogic.go index c13ab7c5..f08a0df1 100644 --- a/server/pay/internal/logic/stripewebhooklogic.go +++ b/server/pay/internal/logic/stripewebhooklogic.go @@ -3,8 +3,10 @@ package logic import ( "encoding/json" "errors" + "fmt" "fusenapi/constants" "fusenapi/model/gmodel" + "fusenapi/service/repositories" "fusenapi/utils/auth" "fusenapi/utils/basic" "time" @@ -52,7 +54,7 @@ func (l *StripeWebhookLogic) StripeWebhook(req *types.StripeWebhookReq, userinfo event := stripe.Event{} if err := json.Unmarshal(req.Payload, &event); err != nil { - logc.Errorf(l.ctx, "StripeWebhookLogic StripeWebhook Unmarshal err:", err) + logc.Errorf(l.ctx, "StripeWebhookLogic StripeWebhook Unmarshal err:%v", err) return resp.SetStatusWithMessage(basic.CodeAesCbcDecryptionErr, "pay notify Unmarshal fail") } @@ -106,7 +108,7 @@ func (l *StripeWebhookLogic) StripeWebhook(req *types.StripeWebhookReq, userinfo logx.Errorf("err:%+v,desc:%s", err, "pay notify Unmarshal fail event.Type payment_intent.succeeded") return resp.SetStatusWithMessage(basic.CodeAesCbcDecryptionErr, "pay notify Unmarshal fail event.Type payment_intent.succeeded") } - err = l.HandlePaymentIntentSucceeded(&paymentIntent) + err = l.HandlePaymentIntentSucceeded(&paymentIntent, event.ID) if err != nil { logx.Errorf("err:%+v,desc:%s", err, "pay notify handle payment_intent.succeeded") return resp.SetStatusWithMessage(basic.CodePaybackNotOk, "pay notify handle payment_intent.succeeded") @@ -230,119 +232,27 @@ func (l *StripeWebhookLogic) handlePaymentSessionCompleted(sessionId string, tra } // 付款成功 -func (l *StripeWebhookLogic) HandlePaymentIntentSucceeded(paymentIntent *stripe.PaymentIntent) error { - orderSn, ok := paymentIntent.Metadata["order_sn"] - if !ok || orderSn == "" { - return errors.New("order_sn not found") +func (l *StripeWebhookLogic) HandlePaymentIntentSucceeded(paymentIntent *stripe.PaymentIntent, eventId string) error { + // 支付成功 + if paymentIntent.Status == "succeeded" { + model, ok := paymentIntent.Metadata["model"] + if !ok { + err := errors.New("model is empty") + logc.Errorf(l.ctx, "PaymentSuccessful failed param, eventId:%s,err:%v", eventId, err) + return err + } + switch model { + case "product_order": + res, err := l.svcCtx.Repositories.NewOrder.PaymentSuccessful(l.ctx, &repositories.PaymentSuccessfulReq{ + EventId: eventId, + PaymentMethod: 1, + PaymentIntent: paymentIntent, + }) + if err != nil { + return err + } + fmt.Println(res) + } } return nil - // 查询订单 - - // 支付成功 - // if paymentIntent.Status == "succeeded" { - // var card string - // var brand string - // if paymentIntent.LatestCharge.PaymentMethodDetails != nil { - // if paymentIntent.LatestCharge.PaymentMethodDetails.Card != nil { - // if paymentIntent.LatestCharge.PaymentMethodDetails.Card.Last4 != "" { - // card = paymentIntent.LatestCharge.PaymentMethodDetails.Card.Last4 - // } - // if paymentIntent.LatestCharge.PaymentMethodDetails.Card.Brand != "" { - // brand = string(paymentIntent.LatestCharge.PaymentMethodDetails.Card.Brand) - // } - // } - // } - - // ctx := l.ctx - // err = l.svcCtx.MysqlConn.Transaction(func(connGorm *gorm.DB) error { - // // 更新支付信息 - // payModelT := gmodel.NewFsPayModel(connGorm) - // *payInfo.PayStatus = 1 - // *payInfo.PayTime = nowTime - // *payInfo.CardNo = card - // *payInfo.Brand = brand - // *payInfo.TradeNo = paymentIntent.ID - // _, err = payModelT.RBCreateOrUpdate(ctx, payInfo) - // if err != nil { - // return err - // } - - // // 更新设计数据 - // productDesignModelT := gmodel.NewFsProductDesignModel(connGorm) - // productDesignModelTRSB := productDesignModelT.BuilderTrans(ctx, nil) - // var isPay int64 = 1 - // err = productDesignModelT.RBUpdateByIds(productDesignModelTRSB, designIds, &gmodel.FsProductDesign{IsPay: &isPay}) - // if err != nil { - // return err - // } - - // var orderInfo = &gmodel.FsOrder{} - // var orderStatus int64 - // var orderIsPartPay int64 - // var orderPayedAmount int64 - // var orderIsPayCompleted int64 - // // 支付记录是首款 - // if *payInfo.PayStage == int64(constants.PAYSTAGE_DEPOSIT) { - // orderStatus = int64(constants.STATUS_NEW_PART_PAY) - // orderIsPartPay = 1 - // orderInfo.IsPartPay = &orderIsPartPay - // orderPayedAmount = paymentIntent.Amount - - // // 删除购物车 - // cartModelT := gmodel.NewFsCartModel(connGorm) - // cartModelTRSB := cartModelT.BuilderTrans(ctx, nil) - // err = cartModelT.RBDeleteCartsByIds(cartModelTRSB, cartIds) - // if err != nil { - // return err - // } - // } - - // // 支付记录是尾款 - // if *payInfo.PayStage == int64(constants.PAYSTAGE_REMAINING) { - // if *fsOrderRelInfo.Status < int64(constants.STATUS_NEW_PAY_COMPLETED) { - // orderStatus = int64(constants.STATUS_NEW_PAY_COMPLETED) - // } - // orderIsPayCompleted = 1 - // orderInfo.IsPayCompleted = &orderIsPayCompleted - // orderPayedAmount = *fsOrderRelInfo.PayedAmount + paymentIntent.Amount - // } - - // // 更新订单信息 - // orderInfo.Id = fsOrderRelInfo.Id - // orderInfo.Status = &orderStatus - // orderInfo.Ptime = &nowTime - // orderInfo.PayedAmount = &orderPayedAmount - // orderModelT := gmodel.NewFsOrderModel(connGorm) - // err = orderModelT.RBUpdate(ctx, orderInfo) - // if err != nil { - // return err - // } - // return err - // }) - // if err != nil { - // return err - // } - - //千人千面的处理 - // $renderServer = (new RenderService()); - // $renderServer->thousandsFacesV2($order->id); - // //清除用户最新的设计 - // $cache = \Yii::$app->cache; - // $cache->delete(CacheConfigHelper::LAST_DESIGN . $order->user_id); - // //缓存最新订单编号 - // $cache->set(CacheConfigHelper::USER_ORDERNO . $order->user_id, $order->sn); - - // //查询用户邮箱信息 - // $user = \api\models\User::find()->where(['id' => $order->user_id])->one(); - // $redisData = [ - // 'key' => 'receipt_download', - // 'param' => [ - // 'email' => $user->email, - // 'order_id' => $order->id, - // 'pay_id' => $pay->id, - // 'type' => 1,//付款成功为1 - // ] - // ]; - // Email::timely($redisData); - } diff --git a/server/pay/internal/svc/servicecontext.go b/server/pay/internal/svc/servicecontext.go index 9eca2703..4b437fd9 100644 --- a/server/pay/internal/svc/servicecontext.go +++ b/server/pay/internal/svc/servicecontext.go @@ -18,8 +18,9 @@ type ServiceContext struct { Config config.Config SharedState *shared.SharedState - MysqlConn *gorm.DB - AllModels *gmodel.AllModelsGen + MysqlConn *gorm.DB + AllModels *gmodel.AllModelsGen + Repositories *initalize.Repositories } func NewServiceContext(c config.Config) *ServiceContext { @@ -31,6 +32,9 @@ func NewServiceContext(c config.Config) *ServiceContext { MysqlConn: conn, SharedState: nil, AllModels: gmodel.NewAllModels(initalize.InitMysql(c.SourceMysql)), + Repositories: initalize.NewAllRepositories(&initalize.NewAllRepositorieData{ + GormDB: conn, + }), } } diff --git a/service/repositories/order.go b/service/repositories/order.go index a54045bf..e9aa19d8 100644 --- a/service/repositories/order.go +++ b/service/repositories/order.go @@ -15,6 +15,8 @@ import ( "time" "github.com/aws/aws-sdk-go/aws/session" + "github.com/stripe/stripe-go/v74" + "github.com/zeromicro/go-zero/core/logc" "github.com/zeromicro/go-zero/core/logx" "gorm.io/gorm" ) @@ -40,6 +42,16 @@ type ( List(ctx context.Context, in *ListReq) (res *ListRes, err error) // 详情 Detail(ctx context.Context, in *DetailReq) (res *DetailRes, err error) + // 支付成功 + PaymentSuccessful(ctx context.Context, in *PaymentSuccessfulReq) (res *PaymentSuccessfulRes, err error) + } + + PayInfo struct { + PayMethod int64 `json:"pay_method"` // 交易方式 + PayTime time.Time `json:"pay_time"` // 支付时间 + Status gmodel.PayStatus `json:"status"` // 当前状态 + StatusLink []gmodel.PayStatus `json:"status_link"` // 状态链路 + TradeNo string `json:"trade_no"` // 支付交易号 } OrderAddress struct { @@ -63,6 +75,16 @@ type ( Amount int64 `json:"amount"` // 金额 Label string `json:"label"` // 标签 } + + /* 支付成功 */ + PaymentSuccessfulReq struct { + EventId string + PaymentMethod int64 + PaymentIntent *stripe.PaymentIntent + } + PaymentSuccessfulRes struct{} + /* 支付成功 */ + /* 预支付--定金 */ CreatePrePaymentByDepositReq struct { StripeKey string `json:"stripe_key"` @@ -139,6 +161,175 @@ type ( /* 列表 */ ) +// 支付成功 +func (d *defaultOrder) PaymentSuccessful(ctx context.Context, in *PaymentSuccessfulReq) (res *PaymentSuccessfulRes, err error) { + var orderSn string + var payStage string + var ok bool + var card string + var brand string + var country string + var currency string + var tradeSn string + var payAmount int64 + var payTitle string + var payTime time.Time + if in.PaymentIntent != nil { + paymentIntent := in.PaymentIntent + orderSn, ok = paymentIntent.Metadata["order_sn"] + if !ok || orderSn == "" { + err = errors.New("order_sn is empty") + logc.Errorf(ctx, "PaymentSuccessful failed param, eventId:%s,err:%v", in.EventId, err) + return &PaymentSuccessfulRes{}, err + } + payStage, ok = paymentIntent.Metadata["pay_stage"] + if !ok || payStage == "" { + err = errors.New("pay_stage is empty") + logc.Errorf(ctx, "PaymentSuccessful failed param, eventId:%s,err:%v", in.EventId, err) + return &PaymentSuccessfulRes{}, err + } + country, ok = paymentIntent.Metadata["country"] + if !ok || country == "" { + err = errors.New("country is empty") + logc.Errorf(ctx, "PaymentSuccessful failed param, eventId:%s,err:%v", in.EventId, err) + return &PaymentSuccessfulRes{}, err + } + if paymentIntent.LatestCharge.PaymentMethodDetails != nil { + if paymentIntent.LatestCharge.PaymentMethodDetails.Card != nil { + if paymentIntent.LatestCharge.PaymentMethodDetails.Card.Last4 != "" { + card = paymentIntent.LatestCharge.PaymentMethodDetails.Card.Last4 + } + if paymentIntent.LatestCharge.PaymentMethodDetails.Card.Brand != "" { + brand = string(paymentIntent.LatestCharge.PaymentMethodDetails.Card.Brand) + } + } + } + if paymentIntent.Currency != "" { + currency = string(paymentIntent.Currency) + } + tradeSn = paymentIntent.ID + payAmount = paymentIntent.Amount + payTitle = paymentIntent.Description + payTime = time.Unix(paymentIntent.Created, 0) + } + err = d.MysqlConn.WithContext(ctx).Transaction(func(tx *gorm.DB) error { + var orderInfo gmodel.FsOrder + result := tx.Where("is_del = ?", 0).Where("order_sn = ?", orderSn).Take(&orderInfo) + err = result.Error + if err != nil { + logx.Errorf("PaymentSuccessful failed order Take, eventId:%s,err: %v", in.EventId, err) + return err + } + ress, err := d.OrderDetailHandler(ctx, &orderInfo, 0) + if err != nil { + logx.Errorf("PaymentSuccessful failed DetailOrderDetailHandler,eventId:%s, err: %v", in.EventId, err) + return err + } + var ntime = time.Now().UTC() + if (payStage == "deposit" && *orderInfo.PayStatus == int64(constants.ORDERPAYSTATUSUNPAIDDEPOSIT)) || (payStage == "remaining_balance" && *orderInfo.PayStatus == int64(constants.ORDERPAYSTATUSPAIDDEPOSIT)) { + var payStatus = int64(constants.PAYSTATUSPAID) + var payStageInt int64 + var orderPayStatusCode constants.OrderPayStatusCode + // 订单状态--当前 + var status gmodel.OrderStatus + var statusLink []gmodel.OrderStatus + var uOrderDetail = make(map[string]interface{}) + var payInfo PayInfo + payInfo.PayMethod = in.PaymentMethod + payInfo.PayTime = payTime + payInfo.TradeNo = tradeSn + + if payStage == "deposit" { + payStageInt = 1 + orderPayStatusCode = constants.ORDERPAYSTATUSPAIDDEPOSIT + status = gmodel.OrderStatus{ + Ctime: &ntime, + Utime: &ntime, + StatusCode: constants.ORDERSTATUSDIRECTMAILORDERED, + StatusTitle: constants.OrderStatusMessage[constants.ORDERSTATUSDIRECTMAILORDERED], + } + statusLink = order.UpdateOrderStatusLink(ress.OrderDetailOriginal.OrderInfo.StatusLink, gmodel.OrderStatus{ + Utime: &ntime, + StatusCode: constants.ORDERSTATUSDIRECTMAILORDERED, + StatusTitle: constants.OrderStatusMessage[constants.ORDERSTATUSDIRECTMAILORDERED], + }) + payInfo.Status = gmodel.PayStatus{ + StatusCode: int64(constants.PAYSTATUSPAID), + StatusTitle: constants.PayStatusMessage[constants.PAYSTATUSPAID], + } + payInfo.StatusLink = append(ress.OrderDetail.OrderAmount.Deposit.StatusLink, payInfo.Status) + uOrderDetail["order_amount"] = struct { + Deposit PayInfo `json:"deposit"` + }{ + Deposit: payInfo, + } + } + if payStage == "remaining_balance" { + payStageInt = 2 + orderPayStatusCode = constants.ORDERPAYSTATUSPAIDDREMAINING + status = gmodel.OrderStatus{ + Ctime: &ntime, + Utime: &ntime, + StatusCode: constants.ORDERSTATUSCLOUDSTOREORDERED, + StatusTitle: constants.OrderStatusMessage[constants.ORDERSTATUSCLOUDSTOREORDERED], + } + statusLink = order.UpdateOrderStatusLink(ress.OrderDetailOriginal.OrderInfo.StatusLink, gmodel.OrderStatus{ + Utime: &ntime, + StatusCode: constants.ORDERSTATUSCLOUDSTOREORDERED, + StatusTitle: constants.OrderStatusMessage[constants.ORDERSTATUSCLOUDSTOREORDERED], + }) + payInfo.StatusLink = append(ress.OrderDetail.OrderAmount.RemainingBalance.StatusLink, payInfo.Status) + uOrderDetail["order_amount"] = struct { + RemainingBalance PayInfo `json:"remaining_balance"` + }{ + RemainingBalance: payInfo, + } + } + + // 新增交易信息 + tx.Create(&gmodel.FsOrderTrade{ + UserId: orderInfo.UserId, + OrderSn: &orderSn, + OrderSource: orderInfo.OrderSource, + TradeSn: &tradeSn, + PayAmount: &payAmount, + PayStatus: &payStatus, + PaymentMethod: &in.PaymentMethod, + PayStage: &payStageInt, + CardSn: &card, + CardBrand: &brand, + Country: &country, + Currency: ¤cy, + Ctime: &ntime, + Utime: &ntime, + PayTitle: &payTitle, + }) + // 更新订单信息 + var sql string = fmt.Sprintf(", `utime` = '%s'", ntime) + uOrderDetail["pay_status"] = orderPayStatusCode + uOrderDetail["order_info"] = struct { + Utime *time.Time `json:"utime"` + Status gmodel.OrderStatus `json:"status"` + StatusLink []gmodel.OrderStatus `json:"status_link"` + }{ + Utime: &ntime, + Status: status, + StatusLink: statusLink, + } + if len(uOrderDetail) > 0 { + err = fssql.MetadataOrderPATCH(d.MysqlConn, sql, orderSn, gmodel.FsOrder{}, uOrderDetail, "id = ?", orderInfo.Id) + if err != nil { + logx.Errorf("PaymentSuccessful failed MetadataOrderPATCH,eventId:%s, err: %v", in.EventId, err) + return err + } + } + + } + return nil + }) + return &PaymentSuccessfulRes{}, nil +} + // 预支付--尾款 func (d *defaultOrder) CreatePrePaymentByBalance(ctx context.Context, in *CreatePrePaymentByBalanceReq) (res *CreatePrePaymentByBalanceRes, err error) { var errorCode basic.StatusResponse @@ -172,7 +363,7 @@ func (d *defaultOrder) CreatePrePaymentByBalance(ctx context.Context, in *Create }, err } - ress, err := d.OrderDetailHandler(ctx, &order) + ress, err := d.OrderDetailHandler(ctx, &order, 1) if err != nil { logx.Errorf("create prePayment balance failed DetailOrderDetailHandler, err: %v", err) errorCode = *basic.CodeServiceErr @@ -185,8 +376,13 @@ func (d *defaultOrder) CreatePrePaymentByBalance(ctx context.Context, in *Create payConfig := &pay.Config{} payConfig.Stripe.PayType = "intent" payConfig.Stripe.Key = in.StripeKey + var metadata = make(map[string]string, 2) + metadata["model"] = "product_order" + metadata["order_sn"] = in.OrderSn + metadata["pay_stage"] = "remaining_balance" + metadata["country"] = in.Country var generatePrepaymentReq = &pay.GeneratePrepaymentReq{ - OrderSn: in.OrderSn, + Metadata: metadata, ProductName: "支付尾款后期统一调整", Amount: amount, Currency: "usd", @@ -270,7 +466,7 @@ func (d *defaultOrder) CreatePrePaymentByDeposit(ctx context.Context, in *Create }, err } - ress, err := d.OrderDetailHandler(ctx, &order) + ress, err := d.OrderDetailHandler(ctx, &order, 0) if err != nil { logx.Errorf("create prePayment deposit failed DetailOrderDetailHandler, err: %v", err) errorCode = *basic.CodeServiceErr @@ -342,8 +538,13 @@ func (d *defaultOrder) CreatePrePaymentByDeposit(ctx context.Context, in *Create payConfig := &pay.Config{} payConfig.Stripe.PayType = "intent" payConfig.Stripe.Key = in.StripeKey + var metadata = make(map[string]string, 2) + metadata["model"] = "product_order" + metadata["order_sn"] = in.OrderSn + metadata["pay_stage"] = "deposit" + metadata["country"] = in.Country var generatePrepaymentReq = &pay.GeneratePrepaymentReq{ - OrderSn: in.OrderSn, + Metadata: metadata, ProductName: "支付首款", Amount: amount, Currency: "usd", @@ -417,7 +618,7 @@ func (d *defaultOrder) List(ctx context.Context, in *ListReq) (res *ListRes, err return nil, result.Error } for _, order := range orderList { - ress, err := d.OrderDetailHandler(ctx, &order) + ress, err := d.OrderDetailHandler(ctx, &order, 1) if err != nil { return nil, err } @@ -474,7 +675,7 @@ func (d *defaultOrder) Detail(ctx context.Context, in *DetailReq) (res *DetailRe }, err } - ress, err := d.OrderDetailHandler(ctx, &order) + ress, err := d.OrderDetailHandler(ctx, &order, 1) if err != nil { logx.Errorf("order detail failed, err: %v", err) errorCode = *basic.CodeServiceErr @@ -718,6 +919,7 @@ func (d *defaultOrder) Create(ctx context.Context, in *CreateReq) (res *CreateRe StatusCode: int64(constants.PAYSTATUSUNPAID), StatusTitle: constants.PayStatusMessage[constants.PAYSTATUSUNPAID], }, + StatusLink: make([]gmodel.PayStatus, 0), PayAmount: order.GetAmountInfo(order.GetAmountInfoReq{ ExchangeRate: in.ExchangeRate, Initiate: depositInt, @@ -734,6 +936,7 @@ func (d *defaultOrder) Create(ctx context.Context, in *CreateReq) (res *CreateRe StatusCode: int64(constants.PAYSTATUSUNPAID), StatusTitle: constants.PayStatusMessage[constants.PAYSTATUSUNPAID], }, + StatusLink: make([]gmodel.PayStatus, 0), PayAmount: order.GetAmountInfo(order.GetAmountInfoReq{ ExchangeRate: in.ExchangeRate, Initiate: remainingBalanceInt, @@ -817,7 +1020,7 @@ func (d *defaultOrder) Create(ctx context.Context, in *CreateReq) (res *CreateRe } // 详情处理 -func (d *defaultOrder) OrderDetailHandler(ctx context.Context, orderInfo *gmodel.FsOrder) (res *DetailRes, err error) { +func (d *defaultOrder) OrderDetailHandler(ctx context.Context, orderInfo *gmodel.FsOrder, original int64) (res *DetailRes, err error) { var orderDetail gmodel.OrderDetail err = json.Unmarshal(*orderInfo.Metadata, &orderDetail) @@ -826,18 +1029,21 @@ func (d *defaultOrder) OrderDetailHandler(ctx context.Context, orderInfo *gmodel return nil, err } orderDetailOriginal := orderDetail - for orderProductKey, orderProduct := range orderDetail.OrderProduct { - orderDetail.OrderProduct[orderProductKey].TotalPrice = order.GetAmountInfoFormat(&orderProduct.TotalPrice) - orderDetail.OrderProduct[orderProductKey].ItemPrice = order.GetAmountInfoFormat(&orderProduct.ItemPrice) - orderDetail.OrderProduct[orderProductKey].ShoppingCartSnapshot = nil - orderDetail.OrderProduct[orderProductKey].ProductSnapshot = nil + if original == 1 { + for orderProductKey, orderProduct := range orderDetail.OrderProduct { + orderDetail.OrderProduct[orderProductKey].TotalPrice = order.GetAmountInfoFormat(&orderProduct.TotalPrice) + orderDetail.OrderProduct[orderProductKey].ItemPrice = order.GetAmountInfoFormat(&orderProduct.ItemPrice) + orderDetail.OrderProduct[orderProductKey].ShoppingCartSnapshot = nil + orderDetail.OrderProduct[orderProductKey].ProductSnapshot = nil + } + orderDetail.OrderInfo.StatusLink = order.GetOrderStatusLinkUser(orderDetail.OrderInfo.DeliveryMethod, orderDetail.OrderInfo.StatusLink) + orderDetail.OrderAmount.Deposit.PayAmount = order.GetAmountInfoFormat(&orderDetail.OrderAmount.Deposit.PayAmount) + orderDetail.OrderAmount.RemainingBalance.PayAmount = order.GetAmountInfoFormat(&orderDetail.OrderAmount.RemainingBalance.PayAmount) + orderDetail.OrderAmount.Subtotal = order.GetAmountInfoFormat(&orderDetail.OrderAmount.Subtotal) + orderDetail.OrderAmount.Total = order.GetAmountInfoFormat(&orderDetail.OrderAmount.Total) + orderDetail.PayTimeout = time.Duration(orderDetail.OrderInfo.Ctime.Add(orderDetail.PayTimeout).UTC().Unix() - time.Now().UTC().Unix()) + } - orderDetail.OrderInfo.StatusLink = order.GetOrderStatusLinkUser(orderDetail.OrderInfo.DeliveryMethod, orderDetail.OrderInfo.StatusLink) - orderDetail.OrderAmount.Deposit.PayAmount = order.GetAmountInfoFormat(&orderDetail.OrderAmount.Deposit.PayAmount) - orderDetail.OrderAmount.RemainingBalance.PayAmount = order.GetAmountInfoFormat(&orderDetail.OrderAmount.RemainingBalance.PayAmount) - orderDetail.OrderAmount.Subtotal = order.GetAmountInfoFormat(&orderDetail.OrderAmount.Subtotal) - orderDetail.OrderAmount.Total = order.GetAmountInfoFormat(&orderDetail.OrderAmount.Total) - orderDetail.PayTimeout = time.Duration(orderDetail.OrderInfo.Ctime.Add(orderDetail.PayTimeout).UTC().Unix() - time.Now().UTC().Unix()) return &DetailRes{ OrderDetail: orderDetail, diff --git a/utils/order/order.go b/utils/order/order.go index 60c25905..61b49a16 100644 --- a/utils/order/order.go +++ b/utils/order/order.go @@ -120,7 +120,7 @@ func GenerateOrderNumber() string { return orderNumber } -// 初始化订单状态 +// 初始化订单状态--链路 func GenerateOrderStatusLink(deliveryMethod int64, noTime time.Time, expectedTime time.Time) []gmodel.OrderStatus { var list []gmodel.OrderStatus @@ -142,6 +142,39 @@ func GenerateOrderStatusLink(deliveryMethod int64, noTime time.Time, expectedTim return list } +// 更新订单状态--链路 +func UpdateOrderStatusLink(statusLink []gmodel.OrderStatus, status gmodel.OrderStatus) []gmodel.OrderStatus { + var list []gmodel.OrderStatus + for _, v := range statusLink { + if v.StatusCode == status.StatusCode { + item := v + if status.StatusTitle != "" { + item.StatusTitle = status.StatusTitle + } + if status.StatusCode != 0 { + item.StatusCode = status.StatusCode + } + if status.Utime != nil { + item.Utime = status.Utime + } + if status.Metadata != nil { + item.Metadata = status.Metadata + } + if status.ExpectedTime != nil { + item.ExpectedTime = status.ExpectedTime + } + if status.Children != nil || len(status.Children) > 0 { + item.Children = status.Children + } + + list = append(list, item) + } else { + list = append(list, v) + } + } + return list +} + // 获取订单状态 func GetOrderStatusLinkUser(deliveryMethod int64, statusLink []gmodel.OrderStatus) []gmodel.OrderStatus { var list []gmodel.OrderStatus diff --git a/utils/pay/pay.go b/utils/pay/pay.go index 12c7998f..9d602318 100644 --- a/utils/pay/pay.go +++ b/utils/pay/pay.go @@ -29,15 +29,15 @@ type Pay interface { } type GeneratePrepaymentReq struct { - OrderSn string `json:"order_sn"` // 订单编号 - Amount int64 `json:"amount"` // 支付金额 - Currency string `json:"currency"` // 支付货币 - ProductName string `json:"product_name"` // 商品名称 - ProductDescription string `json:"product_description"` // 商品描述 - ProductImages []*string `json:"product_imageso"` // 商品照片 - Quantity int64 `json:"quantity"` //数量 - SuccessURL string `json:"success_url"` // 支付成功回调 - CancelURL string `json:"cancel_url"` // 支付取消回调 + Metadata map[string]string `json:"metadata"` // 元数据 + Amount int64 `json:"amount"` // 支付金额 + Currency string `json:"currency"` // 支付货币 + ProductName string `json:"product_name"` // 商品名称 + ProductDescription string `json:"product_description"` // 商品描述 + ProductImages []*string `json:"product_imageso"` // 商品照片 + Quantity int64 `json:"quantity"` //数量 + SuccessURL string `json:"success_url"` // 支付成功回调 + CancelURL string `json:"cancel_url"` // 支付取消回调 } type GeneratePrepaymentRes struct { diff --git a/utils/pay/stripe.go b/utils/pay/stripe.go index 43cf28d3..ba709cbb 100644 --- a/utils/pay/stripe.go +++ b/utils/pay/stripe.go @@ -50,7 +50,7 @@ func (stripePay *Stripe) GeneratePrepayment(req *GeneratePrepaymentReq) (res *Ge case "session": // session 方式 params := &stripe.CheckoutSessionParams{ - PaymentIntentData: &stripe.CheckoutSessionPaymentIntentDataParams{Metadata: map[string]string{"order_sn": req.OrderSn}}, + PaymentIntentData: &stripe.CheckoutSessionPaymentIntentDataParams{Metadata: req.Metadata}, // Params: stripe.Params{Metadata: map[string]string{"order_id": "1111111111111"}}, PaymentMethodTypes: stripe.StringSlice([]string{ "card", @@ -79,7 +79,6 @@ func (stripePay *Stripe) GeneratePrepayment(req *GeneratePrepaymentReq) (res *Ge case "intent": // 密钥方式 params := &stripe.PaymentIntentParams{ - Params: stripe.Params{Metadata: map[string]string{"order_sn": req.OrderSn}}, Amount: stripe.Int64(req.Amount), Currency: stripe.String(string(req.Currency)), PaymentMethodTypes: stripe.StringSlice([]string{ @@ -87,6 +86,9 @@ func (stripePay *Stripe) GeneratePrepayment(req *GeneratePrepaymentReq) (res *Ge // "ideal", }), } + for key, item := range req.Metadata { + params.AddMetadata(key, item) + } resPaymentintent, err := paymentintent.New(params) if err != nil { return nil, err