package logic import ( "encoding/json" "errors" "fmt" "fusenapi/constants" "fusenapi/model/gmodel" "fusenapi/service/repositories" "fusenapi/utils/auth" "fusenapi/utils/basic" "time" "context" "fusenapi/server/pay/internal/svc" "fusenapi/server/pay/internal/types" "github.com/stripe/stripe-go/v74" "github.com/stripe/stripe-go/v74/webhook" "github.com/zeromicro/go-zero/core/logc" "github.com/zeromicro/go-zero/core/logx" ) type StripeWebhookLogic struct { logx.Logger ctx context.Context svcCtx *svc.ServiceContext } func NewStripeWebhookLogic(ctx context.Context, svcCtx *svc.ServiceContext) *StripeWebhookLogic { return &StripeWebhookLogic{ Logger: logx.WithContext(ctx), ctx: ctx, svcCtx: svcCtx, } } // 处理进入前逻辑w,r // func (l *StripeWebhookLogic) BeforeLogic(w http.ResponseWriter, r *http.Request) { // } // 处理逻辑后 w,r 如:重定向, resp 必须重新处理 // func (l *StripeWebhookLogic) AfterLogic(w http.ResponseWriter, r *http.Request, resp *basic.Response) { // // httpx.OkJsonCtx(r.Context(), w, resp) // } func (l *StripeWebhookLogic) StripeWebhook(req *types.StripeWebhookReq, userinfo *auth.UserInfo) (resp *basic.Response) { // 返回值必须调用Set重新返回, resp可以空指针调用 resp.SetStatus(basic.CodeOK, data) // userinfo 传入值时, 一定不为null stripe.Key = l.svcCtx.Config.PayConfig.Stripe.Key event := stripe.Event{} if err := json.Unmarshal(req.Payload, &event); err != nil { logc.Errorf(l.ctx, "StripeWebhookLogic StripeWebhook Unmarshal err:%v", err) return resp.SetStatusWithMessage(basic.CodeAesCbcDecryptionErr, "pay notify Unmarshal fail") } endpointSecret := l.svcCtx.Config.PayConfig.Stripe.EndpointSecret signatureHeader := req.StripeSignature event, err := webhook.ConstructEvent(req.Payload, signatureHeader, endpointSecret) if err != nil { logx.Error(err) return resp.SetStatusWithMessage(basic.CodeAesCbcDecryptionErr, "Webhook signature verification failed") } // 支付回调事件日志 var payMethod = int64(constants.PAYMETHOD_STRIPE) var nowTime = time.Now().UTC() var eventData = []byte(event.Data.Raw) l.HandlePayEventCreate(&gmodel.FsOrderTradeEvent{ PayMethod: &payMethod, EventId: &event.ID, EventType: &event.Type, EventData: &eventData, Ctime: &nowTime, }) // Unmarshal the event data into an appropriate struct depending on its Type switch event.Type { case "charge.succeeded": // var charge stripe.Charge // err := json.Unmarshal(event.Data.Raw, &charge) // if err != nil { // logx.Error(err) // return resp.SetStatusWithMessage(basic.CodeAesCbcDecryptionErr, "pay notify Unmarshal fail event.Type charge.succeeded") // } case "checkout.session.completed": // checkout checkout.session.completed 处理逻辑 // var session stripe.CheckoutSession // err := json.Unmarshal(event.Data.Raw, &session) // if err != nil { // logx.Error(err) // return resp.SetStatusWithMessage(basic.CodeAesCbcDecryptionErr, "pay notify Unmarshal fail event.Type payment_intent.succeeded") // } // fmt.Println("checkout.session.completed") // err = l.handlePaymentSessionCompleted(session.ID, session.PaymentIntent.ID) // if err != nil { // return resp.SetStatusWithMessage(basic.CodeAesCbcDecryptionErr, "checkout.session.completed fail") // } case "payment_intent.succeeded": var paymentIntent stripe.PaymentIntent err := json.Unmarshal(event.Data.Raw, &paymentIntent) if err != nil { 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, 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") } case "payment_method.attached": var paymentMethod stripe.PaymentMethod err := json.Unmarshal(event.Data.Raw, &paymentMethod) if err != nil { logx.Error(err) return resp.SetStatusWithMessage(basic.CodeAesCbcDecryptionErr, "pay notify Unmarshal fail event.Type payment_method.attached") } case "charge.refunded": var chargeRefunded stripe.Charge err := json.Unmarshal(event.Data.Raw, &chargeRefunded) if err != nil { logx.Errorf("err:%+v,desc:%s", err, "pay notify Unmarshal fail event.Type charge.refunded") return resp.SetStatusWithMessage(basic.CodeAesCbcDecryptionErr, "pay notify Unmarshal fail event.Type charge.refunded") } err = l.HandleChargeRefunded(&chargeRefunded) if err != nil { logx.Errorf("err:%+v,desc:%s", err, "pay notify handle charge.refunded") return resp.SetStatusWithMessage(basic.CodeAesCbcDecryptionErr, "pay notify handle charge.refunded") } // ... handle other event types default: logx.Error("Unhandled event") return resp.SetStatusWithMessage(basic.CodeAesCbcDecryptionErr, "pay notify Unmarshal fail event.Type Unhandled") } return resp.SetStatus(basic.CodeOK) } // 回调事件日志 func (l *StripeWebhookLogic) HandlePayEventCreate(fsPayEvent *gmodel.FsOrderTradeEvent) error { result := l.svcCtx.MysqlConn.Create(fsPayEvent) return result.Error } // 退款成功 func (l *StripeWebhookLogic) HandleChargeRefunded(chargeRefunded *stripe.Charge) (err error) { // 退款成功 // if chargeRefunded.Status == "succeeded" { // ctx := l.ctx // err = l.svcCtx.MysqlConn.Transaction(func(connGorm *gorm.DB) error { // // 查询支付记录 // payModelT := gmodel.NewFsPayModel(connGorm) // payModelTRSB := payModelT.BuilderTrans(nil) // payModelTRSB1 := payModelTRSB.Where("trade_no = ?", chargeRefunded.PaymentIntent.ID).Where("pay_status = ?", constants.PAYSTATUS_SUCCESS).Where("is_refund = ?", 0) // payInfo, err := payModelT.FindOneByQuery(ctx, payModelTRSB1, nil) // if err != nil { // return err // } // // 更新支付记录 // *payInfo.IsRefund = 1 // _, err = payModelT.RBCreateOrUpdate(ctx, payInfo) // if err != nil { // return err // } // // 获取是否还有未退款的数据 // payModelTRSB2 := payModelTRSB.Where("order_number = ?", payInfo.OrderNumber).Where("pay_status = ?", constants.PAYSTATUS_SUCCESS).Where("is_refund = ?", 0) // count, err := payModelT.FindCount(l.ctx, payModelTRSB2, nil) // if count == 0 { // // 退款完成更新订单状态 // orderModelT := gmodel.NewFsOrderModel(connGorm) // orderModelTRSB := orderModelT.BuilderTrans(nil).Where("sn =?", payInfo.OrderNumber) // orderInfoRel, err := orderModelT.FindOneByQuery(ctx, orderModelTRSB, nil) // if err != nil { // return err // } // var isRefunded int64 = 1 // var isRefunding int64 = 1 // var orderStatus int64 = int64(constants.STATUS_NEW_REFUNDED) // var orderInfo = &gmodel.FsOrder{} // orderInfo.Id = orderInfoRel.Id // orderInfo.IsRefunded = &isRefunded // orderInfo.IsRefunding = &isRefunding // orderInfo.Status = &orderStatus // orderModelT.Update(ctx, orderInfo) // // 记录退款原因 // refundReasonModelT := gmodel.NewFsRefundReasonModel(connGorm) // refundReasonModelTRSB := refundReasonModelT.BuilderTrans(nil) // refundReasonModelTRSB1 := refundReasonModelTRSB.Where("order_id =?", orderInfoRel.Id) // refundReasonInfo, err := refundReasonModelT.FindOneByQuery(ctx, refundReasonModelTRSB1, nil) // if err != nil { // return err // } // *refundReasonInfo.IsRefund = 1 // _, err = refundReasonModelT.RBCreateOrUpdate(ctx, refundReasonInfo) // if err != nil { // return err // } // } // return err // }) // } return err } // session完成 func (l *StripeWebhookLogic) handlePaymentSessionCompleted(sessionId string, tradeNo string) (err error) { // 查询支付记录 payModel := gmodel.NewFsPayModel(l.svcCtx.MysqlConn) rsbPay := payModel.RowSelectBuilder(nil) rsbPay = rsbPay.Where("session_id = ?", sessionId) payInfo, err := payModel.FindOneByQuery(l.ctx, rsbPay, nil) if err != nil { return err } if *payInfo.PayStatus == 0 { *payInfo.TradeNo = tradeNo _, err = payModel.CreateOrUpdate(l.ctx, payInfo) if err != nil { return err } } else { return errors.New("pay status 1") } return err } // 付款成功 func (l *StripeWebhookLogic) HandlePaymentIntentSucceeded(paymentIntent *stripe.PaymentIntent, eventId string) error { fmt.Println(paymentIntent) // 支付成功 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 }