From 24d40bda67c679e9be4f7bdabfd50cea31d36268 Mon Sep 17 00:00:00 2001 From: Patrick Pfeiffer Date: Mon, 19 Aug 2024 12:50:30 +0200 Subject: [PATCH] (NOBIDS) frontend: handle stripe-promo-code for when it does not apply --- handlers/stripe.go | 42 +++++++++++++++++++++++++++++++++++++++--- 1 file changed, 39 insertions(+), 3 deletions(-) diff --git a/handlers/stripe.go b/handlers/stripe.go index 0ecb7379bb..0dbcdb1bce 100644 --- a/handlers/stripe.go +++ b/handlers/stripe.go @@ -19,6 +19,7 @@ import ( "github.com/stripe/stripe-go/v72" portalsession "github.com/stripe/stripe-go/v72/billingportal/session" "github.com/stripe/stripe-go/v72/checkout/session" + "github.com/stripe/stripe-go/v72/price" "github.com/stripe/stripe-go/v72/promotioncode" "github.com/stripe/stripe-go/v72/webhook" ) @@ -162,10 +163,34 @@ func StripeCreateCheckoutSession(w http.ResponseWriter, r *http.Request) { } if req.PromotionCode != "" { - it := promotioncode.List(&stripe.PromotionCodeListParams{ + stripePrice, err := price.Get(req.Price, nil) + if err != nil { + logger.WithError(err).Error("error retrieving stripe product for promotion code") + w.WriteHeader(http.StatusInternalServerError) + writeJSON(w, struct { + ErrorData string `json:"error"` + }{ + ErrorData: "could not create a new stripe session, please try again later", + }) + return + } + if stripePrice == nil || stripePrice.Product == nil { + logger.WithError(fmt.Errorf("product is nil")).Error("error retrieving stripe product for promotion code") + w.WriteHeader(http.StatusInternalServerError) + writeJSON(w, struct { + ErrorData string `json:"error"` + }{ + ErrorData: "could not create a new stripe session, please try again later", + }) + return + } + + pcListParams := &stripe.PromotionCodeListParams{ Code: stripe.String(req.PromotionCode), Active: stripe.Bool(true), - }) + } + pcListParams.AddExpand("applies_to") + it := promotioncode.List(pcListParams) if it.Err() != nil { logger.WithError(it.Err()).Error("error retrieving stripe promotion code") w.WriteHeader(http.StatusInternalServerError) @@ -188,7 +213,18 @@ func StripeCreateCheckoutSession(w http.ResponseWriter, r *http.Request) { if pc != nil && currPc.Created < pc.Created { continue } - pc = currPc + if currPc.Coupon == nil { + continue + } + if currPc.Coupon.AppliesTo == nil { + continue + } + for _, p := range currPc.Coupon.AppliesTo.Products { + if stripePrice.Product.ID == p { + pc = currPc + break + } + } } // if promotion code is not found just ignore it