1
0
Fork 0
mirror of https://github.com/binwiederhier/ntfy.git synced 2024-12-23 02:02:33 +01:00
ntfy/server/server_payments.go

Ignoring revisions in .git-blame-ignore-revs. Click here to bypass and see the normal blame view.

565 lines
22 KiB
Go
Raw Normal View History

2023-01-16 05:29:46 +01:00
package server
import (
2023-01-18 21:50:06 +01:00
"bytes"
2023-01-16 05:29:46 +01:00
"errors"
2023-01-17 16:09:37 +01:00
"fmt"
2023-01-16 05:29:46 +01:00
"github.com/stripe/stripe-go/v74"
portalsession "github.com/stripe/stripe-go/v74/billingportal/session"
"github.com/stripe/stripe-go/v74/checkout/session"
"github.com/stripe/stripe-go/v74/customer"
2023-01-17 16:09:37 +01:00
"github.com/stripe/stripe-go/v74/price"
2023-01-16 05:29:46 +01:00
"github.com/stripe/stripe-go/v74/subscription"
"github.com/stripe/stripe-go/v74/webhook"
"heckel.io/ntfy/log"
2023-01-17 16:09:37 +01:00
"heckel.io/ntfy/user"
2023-01-16 05:29:46 +01:00
"heckel.io/ntfy/util"
2023-01-18 21:50:06 +01:00
"io"
2023-01-16 05:29:46 +01:00
"net/http"
"net/netip"
2023-01-16 05:29:46 +01:00
"time"
)
// Payments in ntfy are done via Stripe.
//
// Pretty much all payments related things are in this file. The following processes
// handle payments:
//
// - Checkout:
// Creating a Stripe customer and subscription via the Checkout flow. This flow is only used if the
// ntfy user is not already a Stripe customer. This requires redirecting to the Stripe checkout page.
// It is implemented in handleAccountBillingSubscriptionCreate and the success callback
// handleAccountBillingSubscriptionCreateSuccess.
// - Update subscription:
// Switching between Stripe subscriptions (upgrade/downgrade) is handled via
// handleAccountBillingSubscriptionUpdate. This also handles proration.
// - Cancel subscription (at period end):
// Users can cancel the Stripe subscription via the web app at the end of the billing period. This
// simply updates the subscription and Stripe will cancel it. Users cannot immediately cancel the
// subscription.
// - Webhooks:
// Whenever a subscription changes (updated, deleted), Stripe sends us a request via a webhook.
// This is used to keep the local user database fields up to date. Stripe is the source of truth.
// What Stripe says is mirrored and not questioned.
2023-01-23 04:21:30 +01:00
var (
errNotAPaidTier = errors.New("tier does not have billing price identifier")
errMultipleBillingSubscriptions = errors.New("cannot have multiple billing subscriptions")
errNoBillingSubscription = errors.New("user does not have an active billing subscription")
)
var (
retryUserDelays = []time.Duration{3 * time.Second, 5 * time.Second, 7 * time.Second}
)
// handleBillingTiersGet returns all available paid tiers, and the free tier. This is to populate the upgrade dialog
2023-01-29 02:43:06 +01:00
// in the UI. Note that this endpoint does NOT have a user context (no u!).
func (s *Server) handleBillingTiersGet(w http.ResponseWriter, _ *http.Request, _ *visitor) error {
tiers, err := s.userManager.Tiers()
2023-01-17 16:09:37 +01:00
if err != nil {
return err
}
2023-01-27 04:57:18 +01:00
freeTier := configBasedVisitorLimits(s.config)
2023-01-18 01:40:03 +01:00
response := []*apiAccountBillingTier{
{
// This is a bit of a hack: This is the "Free" tier. It has no tier code, name or price.
2023-01-18 01:40:03 +01:00
Limits: &apiAccountLimits{
Basis: string(visitorLimitBasisIP),
2023-01-27 04:57:18 +01:00
Messages: freeTier.MessageLimit,
MessagesExpiryDuration: int64(freeTier.MessageExpiryDuration.Seconds()),
Emails: freeTier.EmailLimit,
Calls: freeTier.CallLimit,
2023-01-18 01:40:03 +01:00
Reservations: freeTier.ReservationsLimit,
AttachmentTotalSize: freeTier.AttachmentTotalSizeLimit,
AttachmentFileSize: freeTier.AttachmentFileSizeLimit,
AttachmentExpiryDuration: int64(freeTier.AttachmentExpiryDuration.Seconds()),
},
},
}
2023-01-18 21:50:06 +01:00
prices, err := s.priceCache.Value()
if err != nil {
return err
}
2023-01-17 16:09:37 +01:00
for _, tier := range tiers {
2023-02-22 04:44:30 +01:00
priceMonth, priceYear := prices[tier.StripeMonthlyPriceID], prices[tier.StripeYearlyPriceID]
if priceMonth == 0 || priceYear == 0 { // Only allow tiers that have both prices!
2023-01-17 16:09:37 +01:00
continue
}
response = append(response, &apiAccountBillingTier{
2023-02-22 04:44:30 +01:00
Code: tier.Code,
Name: tier.Name,
Prices: &apiAccountBillingPrices{
Month: priceMonth,
Year: priceYear,
},
2023-01-18 01:40:03 +01:00
Limits: &apiAccountLimits{
Basis: string(visitorLimitBasisTier),
2023-01-27 04:57:18 +01:00
Messages: tier.MessageLimit,
MessagesExpiryDuration: int64(tier.MessageExpiryDuration.Seconds()),
Emails: tier.EmailLimit,
Calls: tier.CallLimit,
2023-01-27 04:57:18 +01:00
Reservations: tier.ReservationLimit,
2023-01-18 01:40:03 +01:00
AttachmentTotalSize: tier.AttachmentTotalSizeLimit,
AttachmentFileSize: tier.AttachmentFileSizeLimit,
AttachmentExpiryDuration: int64(tier.AttachmentExpiryDuration.Seconds()),
},
2023-01-17 16:09:37 +01:00
})
}
2023-01-18 21:50:06 +01:00
return s.writeJSON(w, response)
2023-01-17 16:09:37 +01:00
}
// handleAccountBillingSubscriptionCreate creates a Stripe checkout flow to create a user subscription. The tier
// will be updated by a subsequent webhook from Stripe, once the subscription becomes active.
func (s *Server) handleAccountBillingSubscriptionCreate(w http.ResponseWriter, r *http.Request, v *visitor) error {
2023-01-29 02:43:06 +01:00
u := v.User()
if u.Billing.StripeSubscriptionID != "" {
return errHTTPBadRequestBillingSubscriptionExists
}
2023-01-28 05:10:59 +01:00
req, err := readJSONWithLimit[apiAccountBillingSubscriptionChangeRequest](r.Body, jsonBodyBytesLimit, false)
2023-01-16 05:29:46 +01:00
if err != nil {
return err
}
tier, err := s.userManager.Tier(req.Tier)
if err != nil {
return err
2023-02-22 04:44:30 +01:00
}
var priceID string
if req.Interval == string(stripe.PriceRecurringIntervalMonth) && tier.StripeMonthlyPriceID != "" {
priceID = tier.StripeMonthlyPriceID
} else if req.Interval == string(stripe.PriceRecurringIntervalYear) && tier.StripeYearlyPriceID != "" {
priceID = tier.StripeYearlyPriceID
} else {
2023-01-18 01:40:03 +01:00
return errNotAPaidTier
2023-01-16 05:29:46 +01:00
}
2023-02-05 03:26:01 +01:00
logvr(v, r).
2023-02-11 16:49:37 +01:00
With(tier).
2023-02-22 04:44:30 +01:00
Fields(log.Context{
"stripe_price_id": priceID,
"stripe_subscription_interval": req.Interval,
}).
2023-02-06 05:34:27 +01:00
Tag(tagStripe).
2023-02-05 03:26:01 +01:00
Info("Creating Stripe checkout flow")
2023-01-16 05:29:46 +01:00
var stripeCustomerID *string
2023-01-29 02:43:06 +01:00
if u.Billing.StripeCustomerID != "" {
stripeCustomerID = &u.Billing.StripeCustomerID
stripeCustomer, err := s.stripe.GetCustomer(u.Billing.StripeCustomerID)
if err != nil {
return err
} else if stripeCustomer.Subscriptions != nil && len(stripeCustomer.Subscriptions.Data) > 0 {
return errMultipleBillingSubscriptions
}
2023-01-16 05:29:46 +01:00
}
2023-01-17 16:09:37 +01:00
successURL := s.config.BaseURL + apiAccountBillingSubscriptionCheckoutSuccessTemplate
2023-01-16 05:29:46 +01:00
params := &stripe.CheckoutSessionParams{
2023-01-18 01:40:03 +01:00
Customer: stripeCustomerID, // A user may have previously deleted their subscription
2023-01-29 02:43:06 +01:00
ClientReferenceID: &u.ID,
2023-01-18 01:40:03 +01:00
SuccessURL: &successURL,
Mode: stripe.String(string(stripe.CheckoutSessionModeSubscription)),
AllowPromotionCodes: stripe.Bool(true),
2023-01-16 05:29:46 +01:00
LineItems: []*stripe.CheckoutSessionLineItemParams{
{
2023-02-22 04:44:30 +01:00
Price: stripe.String(priceID),
2023-01-16 05:29:46 +01:00
Quantity: stripe.Int64(1),
},
},
2023-01-30 15:30:51 +01:00
AutomaticTax: &stripe.CheckoutSessionAutomaticTaxParams{
Enabled: stripe.Bool(true),
},
2023-01-16 05:29:46 +01:00
}
2023-01-19 05:01:26 +01:00
sess, err := s.stripe.NewCheckoutSession(params)
2023-01-16 05:29:46 +01:00
if err != nil {
return err
}
2023-01-17 16:09:37 +01:00
response := &apiAccountBillingSubscriptionCreateResponse{
2023-01-16 05:29:46 +01:00
RedirectURL: sess.URL,
}
2023-01-18 21:50:06 +01:00
return s.writeJSON(w, response)
2023-01-16 05:29:46 +01:00
}
// handleAccountBillingSubscriptionCreateSuccess is called after the Stripe checkout session has succeeded. We use
// the session ID in the URL to retrieve the Stripe subscription and update the local database. This is the first
// and only time we can map the local username with the Stripe customer ID.
2023-01-23 04:21:30 +01:00
func (s *Server) handleAccountBillingSubscriptionCreateSuccess(w http.ResponseWriter, r *http.Request, v *visitor) error {
2023-01-29 02:43:06 +01:00
// We don't have v.User() in this endpoint, only a userManager!
2023-01-17 16:09:37 +01:00
matches := apiAccountBillingSubscriptionCheckoutSuccessRegex.FindStringSubmatch(r.URL.Path)
2023-01-16 05:29:46 +01:00
if len(matches) != 2 {
return errHTTPInternalErrorInvalidPath
}
sessionID := matches[1]
2023-01-19 05:01:26 +01:00
sess, err := s.stripe.GetSession(sessionID) // FIXME How do we rate limit this?
2023-01-16 05:29:46 +01:00
if err != nil {
return err
2023-01-16 05:29:46 +01:00
} else if sess.Customer == nil || sess.Subscription == nil || sess.ClientReferenceID == "" {
2023-02-26 02:23:22 +01:00
return errHTTPBadRequestBillingRequestInvalid.Wrap("customer or subscription not found")
2023-01-16 05:29:46 +01:00
}
2023-01-19 05:01:26 +01:00
sub, err := s.stripe.GetSubscription(sess.Subscription.ID)
2023-01-16 05:29:46 +01:00
if err != nil {
return err
2023-02-22 04:44:30 +01:00
} else if sub.Items == nil || len(sub.Items.Data) != 1 || sub.Items.Data[0].Price == nil || sub.Items.Data[0].Price.Recurring == nil {
2023-02-26 02:23:22 +01:00
return errHTTPBadRequestBillingRequestInvalid.Wrap("more than one line item in existing subscription")
2023-01-16 05:29:46 +01:00
}
2023-02-22 04:44:30 +01:00
priceID, interval := sub.Items.Data[0].Price.ID, sub.Items.Data[0].Price.Recurring.Interval
tier, err := s.userManager.TierByStripePrice(priceID)
2023-01-16 05:29:46 +01:00
if err != nil {
return err
}
u, err := s.userManager.UserByID(sess.ClientReferenceID)
2023-01-16 05:29:46 +01:00
if err != nil {
return err
}
2023-01-23 04:21:30 +01:00
v.SetUser(u)
2023-02-05 03:26:01 +01:00
logvr(v, r).
2023-02-11 16:49:37 +01:00
With(tier).
2023-02-06 05:34:27 +01:00
Tag(tagStripe).
Fields(log.Context{
2023-02-05 03:26:01 +01:00
"stripe_customer_id": sess.Customer.ID,
2023-02-22 04:44:30 +01:00
"stripe_price_id": priceID,
2023-02-05 03:26:01 +01:00
"stripe_subscription_id": sub.ID,
"stripe_subscription_status": string(sub.Status),
2023-02-22 04:44:30 +01:00
"stripe_subscription_interval": string(interval),
2023-02-05 03:26:01 +01:00
"stripe_subscription_paid_until": sub.CurrentPeriodEnd,
}).
Info("Stripe checkout flow succeeded, updating user tier and subscription")
customerParams := &stripe.CustomerParams{
Params: stripe.Params{
Metadata: map[string]string{
"user_id": u.ID,
"user_name": u.Name,
},
},
}
if _, err := s.stripe.UpdateCustomer(sess.Customer.ID, customerParams); err != nil {
return err
}
2023-02-22 04:44:30 +01:00
if err := s.updateSubscriptionAndTier(r, v, u, tier, sess.Customer.ID, sub.ID, string(sub.Status), string(interval), sub.CurrentPeriodEnd, sub.CancelAt); err != nil {
2023-01-16 05:29:46 +01:00
return err
}
2023-01-17 16:09:37 +01:00
http.Redirect(w, r, s.config.BaseURL+accountPath, http.StatusSeeOther)
2023-01-16 05:29:46 +01:00
return nil
}
// handleAccountBillingSubscriptionUpdate updates an existing Stripe subscription to a new price, and updates
// a user's tier accordingly. This endpoint only works if there is an existing subscription.
func (s *Server) handleAccountBillingSubscriptionUpdate(w http.ResponseWriter, r *http.Request, v *visitor) error {
2023-01-29 02:43:06 +01:00
u := v.User()
if u.Billing.StripeSubscriptionID == "" {
return errNoBillingSubscription
}
2023-01-28 05:10:59 +01:00
req, err := readJSONWithLimit[apiAccountBillingSubscriptionChangeRequest](r.Body, jsonBodyBytesLimit, false)
if err != nil {
return err
}
tier, err := s.userManager.Tier(req.Tier)
if err != nil {
return err
}
2023-02-22 04:44:30 +01:00
var priceID string
if req.Interval == string(stripe.PriceRecurringIntervalMonth) && tier.StripeMonthlyPriceID != "" {
priceID = tier.StripeMonthlyPriceID
} else if req.Interval == string(stripe.PriceRecurringIntervalYear) && tier.StripeYearlyPriceID != "" {
priceID = tier.StripeYearlyPriceID
} else {
return errNotAPaidTier
}
2023-02-05 03:26:01 +01:00
logvr(v, r).
2023-02-06 05:34:27 +01:00
Tag(tagStripe).
Fields(log.Context{
2023-02-22 04:44:30 +01:00
"new_tier_id": tier.ID,
"new_tier_code": tier.Code,
"new_tier_stripe_price_id": priceID,
"new_tier_stripe_subscription_interval": req.Interval,
2023-02-05 03:26:01 +01:00
// Other stripe_* fields filled by visitor context
}).
2023-02-22 04:44:30 +01:00
Info("Changing Stripe subscription and billing tier to %s/%s (price %s, %s)", tier.ID, tier.Name, priceID, req.Interval)
2023-01-29 02:43:06 +01:00
sub, err := s.stripe.GetSubscription(u.Billing.StripeSubscriptionID)
if err != nil {
return err
2023-01-29 22:15:08 +01:00
} else if sub.Items == nil || len(sub.Items.Data) != 1 {
2023-02-26 02:23:22 +01:00
return errHTTPBadRequestBillingRequestInvalid.Wrap("no items, or more than one item")
}
params := &stripe.SubscriptionParams{
CancelAtPeriodEnd: stripe.Bool(false),
2023-02-22 04:44:30 +01:00
ProrationBehavior: stripe.String(string(stripe.SubscriptionSchedulePhaseProrationBehaviorAlwaysInvoice)),
Items: []*stripe.SubscriptionItemsParams{
{
ID: stripe.String(sub.Items.Data[0].ID),
2023-02-22 04:44:30 +01:00
Price: stripe.String(priceID),
},
},
}
2023-01-19 05:01:26 +01:00
_, err = s.stripe.UpdateSubscription(sub.ID, params)
if err != nil {
return err
}
2023-01-18 21:50:06 +01:00
return s.writeJSON(w, newSuccessResponse())
}
// handleAccountBillingSubscriptionDelete facilitates downgrading a paid user to a tier-less user,
2023-02-11 16:49:37 +01:00
// and cancelling the Stripe subscription entirely. Note that this does not actually change the tier.
// That is done by a webhook at the period end (in X days).
func (s *Server) handleAccountBillingSubscriptionDelete(w http.ResponseWriter, r *http.Request, v *visitor) error {
2023-02-06 05:34:27 +01:00
logvr(v, r).Tag(tagStripe).Info("Deleting Stripe subscription")
2023-01-29 02:43:06 +01:00
u := v.User()
if u.Billing.StripeSubscriptionID != "" {
params := &stripe.SubscriptionParams{
CancelAtPeriodEnd: stripe.Bool(true),
}
2023-01-29 02:43:06 +01:00
_, err := s.stripe.UpdateSubscription(u.Billing.StripeSubscriptionID, params)
if err != nil {
return err
}
}
2023-01-18 21:50:06 +01:00
return s.writeJSON(w, newSuccessResponse())
}
// handleAccountBillingPortalSessionCreate creates a session to the customer billing portal, and returns the
// redirect URL. The billing portal allows customers to change their payment methods, and cancel the subscription.
2023-01-16 05:29:46 +01:00
func (s *Server) handleAccountBillingPortalSessionCreate(w http.ResponseWriter, r *http.Request, v *visitor) error {
2023-02-06 05:34:27 +01:00
logvr(v, r).Tag(tagStripe).Info("Creating Stripe billing portal session")
2023-01-29 02:43:06 +01:00
u := v.User()
if u.Billing.StripeCustomerID == "" {
2023-01-16 05:29:46 +01:00
return errHTTPBadRequestNotAPaidUser
}
params := &stripe.BillingPortalSessionParams{
2023-01-29 02:43:06 +01:00
Customer: stripe.String(u.Billing.StripeCustomerID),
2023-01-16 05:29:46 +01:00
ReturnURL: stripe.String(s.config.BaseURL),
}
2023-01-19 05:01:26 +01:00
ps, err := s.stripe.NewPortalSession(params)
2023-01-16 05:29:46 +01:00
if err != nil {
return err
}
response := &apiAccountBillingPortalRedirectResponse{
RedirectURL: ps.URL,
}
2023-01-18 21:50:06 +01:00
return s.writeJSON(w, response)
2023-01-16 05:29:46 +01:00
}
// handleAccountBillingWebhook handles incoming Stripe webhooks. It mainly keeps the local user database in sync
// with the Stripe view of the world. This endpoint is authorized via the Stripe webhook secret. Note that the
2023-01-29 02:43:06 +01:00
// visitor (v) in this endpoint is the Stripe API, so we don't have u available.
2023-02-05 03:26:01 +01:00
func (s *Server) handleAccountBillingWebhook(_ http.ResponseWriter, r *http.Request, v *visitor) error {
2023-01-16 05:29:46 +01:00
stripeSignature := r.Header.Get("Stripe-Signature")
if stripeSignature == "" {
return errHTTPBadRequestBillingRequestInvalid
2023-01-16 05:29:46 +01:00
}
2023-01-18 21:50:06 +01:00
body, err := util.Peek(r.Body, jsonBodyBytesLimit)
2023-01-16 05:29:46 +01:00
if err != nil {
return err
} else if body.LimitReached {
return errHTTPEntityTooLargeJSONBody
}
2023-01-19 05:01:26 +01:00
event, err := s.stripe.ConstructWebhookEvent(body.PeekedBytes, stripeSignature, s.config.StripeWebhookKey)
2023-01-16 05:29:46 +01:00
if err != nil {
return err
2023-01-16 05:29:46 +01:00
} else if event.Data == nil || event.Data.Raw == nil {
return errHTTPBadRequestBillingRequestInvalid
2023-01-16 05:29:46 +01:00
}
switch event.Type {
case "customer.subscription.updated":
2023-02-05 03:26:01 +01:00
return s.handleAccountBillingWebhookSubscriptionUpdated(r, v, event)
2023-01-16 05:29:46 +01:00
case "customer.subscription.deleted":
2023-02-05 03:26:01 +01:00
return s.handleAccountBillingWebhookSubscriptionDeleted(r, v, event)
2023-01-16 05:29:46 +01:00
default:
2023-02-05 03:26:01 +01:00
logvr(v, r).
2023-02-06 05:34:27 +01:00
Tag(tagStripe).
2023-02-05 03:26:01 +01:00
Field("stripe_webhook_type", event.Type).
Warn("Unhandled Stripe webhook event %s received", event.Type)
2023-01-16 05:29:46 +01:00
return nil
}
}
2023-02-05 03:26:01 +01:00
func (s *Server) handleAccountBillingWebhookSubscriptionUpdated(r *http.Request, v *visitor, event stripe.Event) error {
ev, err := util.UnmarshalJSON[apiStripeSubscriptionUpdatedEvent](io.NopCloser(bytes.NewReader(event.Data.Raw)))
2023-01-18 21:50:06 +01:00
if err != nil {
return err
2023-02-22 04:44:30 +01:00
} else if ev.ID == "" || ev.Customer == "" || ev.Status == "" || ev.CurrentPeriodEnd == 0 || ev.Items == nil || len(ev.Items.Data) != 1 || ev.Items.Data[0].Price == nil || ev.Items.Data[0].Price.ID == "" || ev.Items.Data[0].Price.Recurring == nil {
logvr(v, r).Tag(tagStripe).Field("stripe_request", fmt.Sprintf("%#v", ev)).Warn("Unexpected request from Stripe")
return errHTTPBadRequestBillingRequestInvalid
2023-01-16 05:29:46 +01:00
}
2023-02-22 04:44:30 +01:00
subscriptionID, priceID, interval := ev.ID, ev.Items.Data[0].Price.ID, ev.Items.Data[0].Price.Recurring.Interval
2023-02-05 03:26:01 +01:00
logvr(v, r).
2023-02-06 05:34:27 +01:00
Tag(tagStripe).
Fields(log.Context{
2023-02-05 03:26:01 +01:00
"stripe_webhook_type": event.Type,
"stripe_customer_id": ev.Customer,
2023-02-22 04:44:30 +01:00
"stripe_price_id": priceID,
2023-02-05 03:26:01 +01:00
"stripe_subscription_id": ev.ID,
"stripe_subscription_status": ev.Status,
2023-02-22 04:44:30 +01:00
"stripe_subscription_interval": interval,
2023-02-05 03:26:01 +01:00
"stripe_subscription_paid_until": ev.CurrentPeriodEnd,
"stripe_subscription_cancel_at": ev.CancelAt,
}).
Info("Updating subscription to status %s, with price %s", ev.Status, priceID)
2023-01-23 04:21:30 +01:00
userFn := func() (*user.User, error) {
return s.userManager.UserByStripeCustomer(ev.Customer)
}
2023-02-05 03:26:01 +01:00
// We retry the user retrieval function, because during the Stripe checkout, there a race between the browser
// checkout success redirect (see handleAccountBillingSubscriptionCreateSuccess), and this webhook. The checkout
// success call is the one that updates the user with the Stripe customer ID.
2023-01-23 04:21:30 +01:00
u, err := util.Retry[user.User](userFn, retryUserDelays...)
2023-01-16 05:29:46 +01:00
if err != nil {
return err
}
2023-02-05 03:26:01 +01:00
v.SetUser(u)
2023-01-18 21:50:06 +01:00
tier, err := s.userManager.TierByStripePrice(priceID)
2023-01-16 05:29:46 +01:00
if err != nil {
return err
}
2023-02-22 04:44:30 +01:00
if err := s.updateSubscriptionAndTier(r, v, u, tier, ev.Customer, subscriptionID, ev.Status, string(interval), ev.CurrentPeriodEnd, ev.CancelAt); err != nil {
2023-01-16 05:29:46 +01:00
return err
}
2023-01-27 04:57:18 +01:00
s.publishSyncEventAsync(s.visitor(netip.IPv4Unspecified(), u))
2023-01-16 05:29:46 +01:00
return nil
}
2023-02-05 03:26:01 +01:00
func (s *Server) handleAccountBillingWebhookSubscriptionDeleted(r *http.Request, v *visitor, event stripe.Event) error {
ev, err := util.UnmarshalJSON[apiStripeSubscriptionDeletedEvent](io.NopCloser(bytes.NewReader(event.Data.Raw)))
2023-01-18 21:50:06 +01:00
if err != nil {
return err
2023-01-23 04:21:30 +01:00
} else if ev.Customer == "" {
return errHTTPBadRequestBillingRequestInvalid
2023-01-16 05:29:46 +01:00
}
2023-01-23 04:21:30 +01:00
u, err := s.userManager.UserByStripeCustomer(ev.Customer)
2023-01-16 05:29:46 +01:00
if err != nil {
return err
}
2023-02-05 03:26:01 +01:00
v.SetUser(u)
logvr(v, r).
2023-02-06 05:34:27 +01:00
Tag(tagStripe).
2023-02-05 03:26:01 +01:00
Field("stripe_webhook_type", event.Type).
Info("Subscription deleted, downgrading to unpaid tier")
2023-02-22 04:44:30 +01:00
if err := s.updateSubscriptionAndTier(r, v, u, nil, ev.Customer, "", "", "", 0, 0); err != nil {
2023-01-16 05:29:46 +01:00
return err
}
2023-01-27 04:57:18 +01:00
s.publishSyncEventAsync(s.visitor(netip.IPv4Unspecified(), u))
2023-01-17 16:09:37 +01:00
return nil
}
2023-02-22 04:44:30 +01:00
func (s *Server) updateSubscriptionAndTier(r *http.Request, v *visitor, u *user.User, tier *user.Tier, customerID, subscriptionID, status, interval string, paidUntil, cancelAt int64) error {
reservationsLimit := visitorDefaultReservationsLimit
if tier != nil {
2023-01-27 04:57:18 +01:00
reservationsLimit = tier.ReservationLimit
}
2023-02-05 03:26:01 +01:00
if err := s.maybeRemoveMessagesAndExcessReservations(r, v, u, reservationsLimit); err != nil {
2023-01-23 04:21:30 +01:00
return err
}
2023-02-05 03:26:01 +01:00
if tier == nil && u.Tier != nil {
2023-02-06 05:34:27 +01:00
logvr(v, r).Tag(tagStripe).Info("Resetting tier for user %s", u.Name)
2023-01-17 16:09:37 +01:00
if err := s.userManager.ResetTier(u.Name); err != nil {
return err
}
2023-02-05 03:26:01 +01:00
} else if tier != nil && u.TierID() != tier.ID {
logvr(v, r).
2023-02-06 05:34:27 +01:00
Tag(tagStripe).
Fields(log.Context{
2023-02-22 04:44:30 +01:00
"new_tier_id": tier.ID,
"new_tier_code": tier.Code,
2023-02-05 03:26:01 +01:00
}).
Info("Changing tier to tier %s (%s) for user %s", tier.ID, tier.Name, u.Name)
if err := s.userManager.ChangeTier(u.Name, tier.Code); err != nil {
2023-01-17 16:09:37 +01:00
return err
}
}
// Update billing fields
billing := &user.Billing{
StripeCustomerID: customerID,
StripeSubscriptionID: subscriptionID,
StripeSubscriptionStatus: stripe.SubscriptionStatus(status),
2023-02-22 04:44:30 +01:00
StripeSubscriptionInterval: stripe.PriceRecurringInterval(interval),
StripeSubscriptionPaidUntil: time.Unix(paidUntil, 0),
StripeSubscriptionCancelAt: time.Unix(cancelAt, 0),
}
if err := s.userManager.ChangeBilling(u.Name, billing); err != nil {
2023-01-16 05:29:46 +01:00
return err
}
return nil
}
2023-01-18 21:50:06 +01:00
// fetchStripePrices contacts the Stripe API to retrieve all prices. This is used by the server to cache the prices
// in memory, and ultimately for the web app to display the price table.
2023-02-22 04:44:30 +01:00
func (s *Server) fetchStripePrices() (map[string]int64, error) {
2023-01-18 21:50:06 +01:00
log.Debug("Caching prices from Stripe API")
2023-02-22 04:44:30 +01:00
priceMap := make(map[string]int64)
2023-01-19 05:01:26 +01:00
prices, err := s.stripe.ListPrices(&stripe.PriceListParams{Active: stripe.Bool(true)})
if err != nil {
log.Warn("Fetching Stripe prices failed: %s", err.Error())
return nil, err
}
for _, p := range prices {
2023-02-22 04:44:30 +01:00
priceMap[p.ID] = p.UnitAmount
2023-01-19 05:01:26 +01:00
log.Trace("- Caching price %s = %v", p.ID, priceMap[p.ID])
}
return priceMap, nil
}
// stripeAPI is a small interface to facilitate mocking of the Stripe API
type stripeAPI interface {
NewCheckoutSession(params *stripe.CheckoutSessionParams) (*stripe.CheckoutSession, error)
NewPortalSession(params *stripe.BillingPortalSessionParams) (*stripe.BillingPortalSession, error)
ListPrices(params *stripe.PriceListParams) ([]*stripe.Price, error)
GetCustomer(id string) (*stripe.Customer, error)
GetSession(id string) (*stripe.CheckoutSession, error)
GetSubscription(id string) (*stripe.Subscription, error)
UpdateCustomer(id string, params *stripe.CustomerParams) (*stripe.Customer, error)
2023-01-19 05:01:26 +01:00
UpdateSubscription(id string, params *stripe.SubscriptionParams) (*stripe.Subscription, error)
2023-01-19 20:03:39 +01:00
CancelSubscription(id string) (*stripe.Subscription, error)
2023-01-19 05:01:26 +01:00
ConstructWebhookEvent(payload []byte, header string, secret string) (stripe.Event, error)
}
// realStripeAPI is a thin shim around the Stripe functions to facilitate mocking
type realStripeAPI struct{}
var _ stripeAPI = (*realStripeAPI)(nil)
func newStripeAPI() stripeAPI {
return &realStripeAPI{}
}
func (s *realStripeAPI) NewCheckoutSession(params *stripe.CheckoutSessionParams) (*stripe.CheckoutSession, error) {
return session.New(params)
}
func (s *realStripeAPI) NewPortalSession(params *stripe.BillingPortalSessionParams) (*stripe.BillingPortalSession, error) {
return portalsession.New(params)
}
func (s *realStripeAPI) ListPrices(params *stripe.PriceListParams) ([]*stripe.Price, error) {
prices := make([]*stripe.Price, 0)
iter := price.List(params)
for iter.Next() {
prices = append(prices, iter.Price())
2023-01-18 21:50:06 +01:00
}
if iter.Err() != nil {
return nil, iter.Err()
}
return prices, nil
}
2023-01-19 05:01:26 +01:00
func (s *realStripeAPI) GetCustomer(id string) (*stripe.Customer, error) {
return customer.Get(id, nil)
}
func (s *realStripeAPI) GetSession(id string) (*stripe.CheckoutSession, error) {
return session.Get(id, nil)
}
func (s *realStripeAPI) GetSubscription(id string) (*stripe.Subscription, error) {
return subscription.Get(id, nil)
}
func (s *realStripeAPI) UpdateCustomer(id string, params *stripe.CustomerParams) (*stripe.Customer, error) {
return customer.Update(id, params)
}
2023-01-19 05:01:26 +01:00
func (s *realStripeAPI) UpdateSubscription(id string, params *stripe.SubscriptionParams) (*stripe.Subscription, error) {
return subscription.Update(id, params)
}
2023-01-19 20:03:39 +01:00
func (s *realStripeAPI) CancelSubscription(id string) (*stripe.Subscription, error) {
return subscription.Cancel(id, nil)
}
2023-01-19 05:01:26 +01:00
func (s *realStripeAPI) ConstructWebhookEvent(payload []byte, header string, secret string) (stripe.Event, error) {
return webhook.ConstructEvent(payload, header, secret)
}