| 1 |
//go:build !nopayments |
| 2 |
|
| 3 |
package server |
| 4 |
|
| 5 |
import ( |
| 6 |
"bytes" |
| 7 |
"errors" |
| 8 |
"fmt" |
| 9 |
"github.com/stripe/stripe-go/v74" |
| 10 |
portalsession "github.com/stripe/stripe-go/v74/billingportal/session" |
| 11 |
"github.com/stripe/stripe-go/v74/checkout/session" |
| 12 |
"github.com/stripe/stripe-go/v74/customer" |
| 13 |
"github.com/stripe/stripe-go/v74/price" |
| 14 |
"github.com/stripe/stripe-go/v74/subscription" |
| 15 |
"github.com/stripe/stripe-go/v74/webhook" |
| 16 |
"heckel.io/ntfy/v2/log" |
| 17 |
"heckel.io/ntfy/v2/payments" |
| 18 |
"heckel.io/ntfy/v2/user" |
| 19 |
"heckel.io/ntfy/v2/util" |
| 20 |
"io" |
| 21 |
"net/http" |
| 22 |
"net/netip" |
| 23 |
"time" |
| 24 |
) |
| 25 |
|
| 26 |
// Payments in ntfy are done via Stripe. |
| 27 |
// |
| 28 |
// Pretty much all payments-related things are in this file. The following processes |
| 29 |
// handle payments: |
| 30 |
// |
| 31 |
// - Checkout: |
| 32 |
// Creating a Stripe customer and subscription via the Checkout flow. This flow is only used if the |
| 33 |
// ntfy user is not already a Stripe customer. This requires redirecting to the Stripe checkout page. |
| 34 |
// It is implemented in handleAccountBillingSubscriptionCreate and the success callback |
| 35 |
// handleAccountBillingSubscriptionCreateSuccess. |
| 36 |
// - Update subscription: |
| 37 |
// Switching between Stripe subscriptions (upgrade/downgrade) is handled via |
| 38 |
// handleAccountBillingSubscriptionUpdate. This also handles proration. |
| 39 |
// - Cancel subscription (at period end): |
| 40 |
// Users can cancel the Stripe subscription via the web app at the end of the billing period. This |
| 41 |
// simply updates the subscription and Stripe will cancel it. Users cannot immediately cancel the |
| 42 |
// subscription. |
| 43 |
// - Webhooks: |
| 44 |
// Whenever a subscription changes (updated, deleted), Stripe sends us a request via a webhook. |
| 45 |
// This is used to keep the local user database fields up to date. Stripe is the source of truth. |
| 46 |
// What Stripe says is mirrored and not questioned. |
| 47 |
|
| 48 |
var ( |
| 49 |
errNotAPaidTier = errors.New("tier does not have billing price identifier") |
| 50 |
errMultipleBillingSubscriptions = errors.New("cannot have multiple billing subscriptions") |
| 51 |
errNoBillingSubscription = errors.New("user does not have an active billing subscription") |
| 52 |
) |
| 53 |
|
| 54 |
var ( |
| 55 |
retryUserDelays = []time.Duration{3 * time.Second, 5 * time.Second, 7 * time.Second} |
| 56 |
) |
| 57 |
|
| 58 |
// handleBillingTiersGet returns all available paid tiers, and the free tier. This is to populate the upgrade dialog |
| 59 |
// in the UI. Note that this endpoint does NOT have a user context (no u!). |
| 60 |
func (s *Server) handleBillingTiersGet(w http.ResponseWriter, _ *http.Request, _ *visitor) error { |
| 61 |
tiers, err := s.userManager.Tiers() |
| 62 |
if err != nil { |
| 63 |
return err |
| 64 |
} |
| 65 |
freeTier := configBasedVisitorLimits(s.config) |
| 66 |
response := []*apiAccountBillingTier{ |
| 67 |
{ |
| 68 |
// This is a bit of a hack: This is the "Free" tier. It has no tier code, name or price. |
| 69 |
Limits: &apiAccountLimits{ |
| 70 |
Basis: string(visitorLimitBasisIP), |
| 71 |
Messages: freeTier.MessageLimit, |
| 72 |
MessagesExpiryDuration: int64(freeTier.MessageExpiryDuration.Seconds()), |
| 73 |
Emails: freeTier.EmailLimit, |
| 74 |
Calls: freeTier.CallLimit, |
| 75 |
Reservations: freeTier.ReservationsLimit, |
| 76 |
AttachmentTotalSize: freeTier.AttachmentTotalSizeLimit, |
| 77 |
AttachmentFileSize: freeTier.AttachmentFileSizeLimit, |
| 78 |
AttachmentExpiryDuration: int64(freeTier.AttachmentExpiryDuration.Seconds()), |
| 79 |
}, |
| 80 |
}, |
| 81 |
} |
| 82 |
prices, err := s.priceCache.Value() |
| 83 |
if err != nil { |
| 84 |
return err |
| 85 |
} |
| 86 |
for _, tier := range tiers { |
| 87 |
priceMonth, priceYear := prices[tier.StripeMonthlyPriceID], prices[tier.StripeYearlyPriceID] |
| 88 |
if priceMonth == 0 || priceYear == 0 { // Only allow tiers that have both prices! |
| 89 |
continue |
| 90 |
} |
| 91 |
response = append(response, &apiAccountBillingTier{ |
| 92 |
Code: tier.Code, |
| 93 |
Name: tier.Name, |
| 94 |
Prices: &apiAccountBillingPrices{ |
| 95 |
Month: priceMonth, |
| 96 |
Year: priceYear, |
| 97 |
}, |
| 98 |
Limits: &apiAccountLimits{ |
| 99 |
Basis: string(visitorLimitBasisTier), |
| 100 |
Messages: tier.MessageLimit, |
| 101 |
MessagesExpiryDuration: int64(tier.MessageExpiryDuration.Seconds()), |
| 102 |
Emails: tier.EmailLimit, |
| 103 |
Calls: tier.CallLimit, |
| 104 |
Reservations: tier.ReservationLimit, |
| 105 |
AttachmentTotalSize: tier.AttachmentTotalSizeLimit, |
| 106 |
AttachmentFileSize: tier.AttachmentFileSizeLimit, |
| 107 |
AttachmentExpiryDuration: int64(tier.AttachmentExpiryDuration.Seconds()), |
| 108 |
}, |
| 109 |
}) |
| 110 |
} |
| 111 |
return s.writeJSON(w, response) |
| 112 |
} |
| 113 |
|
| 114 |
// handleAccountBillingSubscriptionCreate creates a Stripe checkout flow to create a user subscription. The tier |
| 115 |
// will be updated by a subsequent webhook from Stripe, once the subscription becomes active. |
| 116 |
func (s *Server) handleAccountBillingSubscriptionCreate(w http.ResponseWriter, r *http.Request, v *visitor) error { |
| 117 |
u := v.User() |
| 118 |
if u.Billing.StripeSubscriptionID != "" { |
| 119 |
return errHTTPBadRequestBillingSubscriptionExists |
| 120 |
} |
| 121 |
req, err := readJSONWithLimit[apiAccountBillingSubscriptionChangeRequest](r.Body, jsonBodyBytesLimit, false) |
| 122 |
if err != nil { |
| 123 |
return err |
| 124 |
} |
| 125 |
tier, err := s.userManager.Tier(req.Tier) |
| 126 |
if err != nil { |
| 127 |
return err |
| 128 |
} |
| 129 |
var priceID string |
| 130 |
if req.Interval == string(stripe.PriceRecurringIntervalMonth) && tier.StripeMonthlyPriceID != "" { |
| 131 |
priceID = tier.StripeMonthlyPriceID |
| 132 |
} else if req.Interval == string(stripe.PriceRecurringIntervalYear) && tier.StripeYearlyPriceID != "" { |
| 133 |
priceID = tier.StripeYearlyPriceID |
| 134 |
} else { |
| 135 |
return errNotAPaidTier |
| 136 |
} |
| 137 |
logvr(v, r). |
| 138 |
With(tier). |
| 139 |
Fields(log.Context{ |
| 140 |
"stripe_price_id": priceID, |
| 141 |
"stripe_subscription_interval": req.Interval, |
| 142 |
}). |
| 143 |
Tag(tagStripe). |
| 144 |
Info("Creating Stripe checkout flow") |
| 145 |
var stripeCustomerID *string |
| 146 |
if u.Billing.StripeCustomerID != "" { |
| 147 |
stripeCustomerID = &u.Billing.StripeCustomerID |
| 148 |
stripeCustomer, err := s.stripe.GetCustomer(u.Billing.StripeCustomerID) |
| 149 |
if err != nil { |
| 150 |
return err |
| 151 |
} else if stripeCustomer.Subscriptions != nil && len(stripeCustomer.Subscriptions.Data) > 0 { |
| 152 |
return errMultipleBillingSubscriptions |
| 153 |
} |
| 154 |
} |
| 155 |
successURL := s.config.BaseURL + apiAccountBillingSubscriptionCheckoutSuccessTemplate |
| 156 |
params := &stripe.CheckoutSessionParams{ |
| 157 |
Customer: stripeCustomerID, // A user may have previously deleted their subscription |
| 158 |
ClientReferenceID: &u.ID, |
| 159 |
SuccessURL: &successURL, |
| 160 |
Mode: stripe.String(string(stripe.CheckoutSessionModeSubscription)), |
| 161 |
AllowPromotionCodes: stripe.Bool(true), |
| 162 |
LineItems: []*stripe.CheckoutSessionLineItemParams{ |
| 163 |
{ |
| 164 |
Price: stripe.String(priceID), |
| 165 |
Quantity: stripe.Int64(1), |
| 166 |
}, |
| 167 |
}, |
| 168 |
AutomaticTax: &stripe.CheckoutSessionAutomaticTaxParams{ |
| 169 |
Enabled: stripe.Bool(true), |
| 170 |
}, |
| 171 |
} |
| 172 |
sess, err := s.stripe.NewCheckoutSession(params) |
| 173 |
if err != nil { |
| 174 |
return err |
| 175 |
} |
| 176 |
response := &apiAccountBillingSubscriptionCreateResponse{ |
| 177 |
RedirectURL: sess.URL, |
| 178 |
} |
| 179 |
return s.writeJSON(w, response) |
| 180 |
} |
| 181 |
|
| 182 |
// handleAccountBillingSubscriptionCreateSuccess is called after the Stripe checkout session has succeeded. We use |
| 183 |
// the session ID in the URL to retrieve the Stripe subscription and update the local database. This is the first |
| 184 |
// and only time we can map the local username with the Stripe customer ID. |
| 185 |
func (s *Server) handleAccountBillingSubscriptionCreateSuccess(w http.ResponseWriter, r *http.Request, v *visitor) error { |
| 186 |
// We don't have v.User() in this endpoint, only a userManager! |
| 187 |
matches := apiAccountBillingSubscriptionCheckoutSuccessRegex.FindStringSubmatch(r.URL.Path) |
| 188 |
if len(matches) != 2 { |
| 189 |
return errHTTPInternalErrorInvalidPath |
| 190 |
} |
| 191 |
sessionID := matches[1] |
| 192 |
sess, err := s.stripe.GetSession(sessionID) // FIXME How do we rate limit this? |
| 193 |
if err != nil { |
| 194 |
return err |
| 195 |
} else if sess.Customer == nil || sess.Subscription == nil || sess.ClientReferenceID == "" { |
| 196 |
return errHTTPBadRequestBillingRequestInvalid.Wrap("customer or subscription not found") |
| 197 |
} |
| 198 |
sub, err := s.stripe.GetSubscription(sess.Subscription.ID) |
| 199 |
if err != nil { |
| 200 |
return err |
| 201 |
} else if sub.Items == nil || len(sub.Items.Data) != 1 || sub.Items.Data[0].Price == nil || sub.Items.Data[0].Price.Recurring == nil { |
| 202 |
return errHTTPBadRequestBillingRequestInvalid.Wrap("more than one line item in existing subscription") |
| 203 |
} |
| 204 |
priceID, interval := sub.Items.Data[0].Price.ID, sub.Items.Data[0].Price.Recurring.Interval |
| 205 |
tier, err := s.userManager.TierByStripePrice(priceID) |
| 206 |
if err != nil { |
| 207 |
return err |
| 208 |
} |
| 209 |
u, err := s.userManager.UserByID(sess.ClientReferenceID) |
| 210 |
if err != nil { |
| 211 |
return err |
| 212 |
} |
| 213 |
v.SetUser(u) |
| 214 |
logvr(v, r). |
| 215 |
With(tier). |
| 216 |
Tag(tagStripe). |
| 217 |
Fields(log.Context{ |
| 218 |
"stripe_customer_id": sess.Customer.ID, |
| 219 |
"stripe_price_id": priceID, |
| 220 |
"stripe_subscription_id": sub.ID, |
| 221 |
"stripe_subscription_status": string(sub.Status), |
| 222 |
"stripe_subscription_interval": string(interval), |
| 223 |
"stripe_subscription_paid_until": sub.CurrentPeriodEnd, |
| 224 |
}). |
| 225 |
Info("Stripe checkout flow succeeded, updating user tier and subscription") |
| 226 |
customerParams := &stripe.CustomerParams{ |
| 227 |
Params: stripe.Params{ |
| 228 |
Metadata: map[string]string{ |
| 229 |
"user_id": u.ID, |
| 230 |
"user_name": u.Name, |
| 231 |
}, |
| 232 |
}, |
| 233 |
} |
| 234 |
if _, err := s.stripe.UpdateCustomer(sess.Customer.ID, customerParams); err != nil { |
| 235 |
return err |
| 236 |
} |
| 237 |
if err := s.updateSubscriptionAndTier(r, v, u, tier, sess.Customer.ID, sub.ID, string(sub.Status), string(interval), sub.CurrentPeriodEnd, sub.CancelAt); err != nil { |
| 238 |
return err |
| 239 |
} |
| 240 |
// Offer email recovery: auto-send a verification link to the billing email (best-effort). |
| 241 |
// Provisioned users can't reset their password, so recovery setup doesn't apply to them. |
| 242 |
if sess.CustomerDetails != nil && !u.Provisioned { |
| 243 |
s.maybeEnqueueBillingEmailVerification(r, v, u.ID, sess.CustomerDetails.Email) |
| 244 |
} |
| 245 |
http.Redirect(w, r, s.config.BaseURL+accountPath, http.StatusSeeOther) |
| 246 |
return nil |
| 247 |
} |
| 248 |
|
| 249 |
// maybeEnqueueBillingEmailVerification sends an email-verification link to a paying user's |
| 250 |
// billing email, so they can use it for password recovery -- but only if they have no verified |
| 251 |
// email yet and the billing email is not already the recovery email on another account. On a |
| 252 |
// collision (or any other skip), the generic "no recovery email set" warning on the account page |
| 253 |
// nudges the user to add one. This is best-effort: failures are logged, never surfaced. |
| 254 |
func (s *Server) maybeEnqueueBillingEmailVerification(r *http.Request, v *visitor, userID, billingEmail string) { |
| 255 |
if s.mailer == nil || s.config.BaseURL == "" || billingEmail == "" || !emailAddressRegex.MatchString(billingEmail) { |
| 256 |
return |
| 257 |
} |
| 258 |
emails, err := s.userManager.Emails(userID) |
| 259 |
if err != nil { |
| 260 |
logvr(v, r).Tag(tagStripe).Err(err).Warn("Failed to load emails for billing verification") |
| 261 |
return |
| 262 |
} else if len(emails) > 0 { |
| 263 |
return // User already has a verified email -- don't nag |
| 264 |
} |
| 265 |
if _, err := s.userManager.UserIDByPrimaryEmail(billingEmail); err == nil { |
| 266 |
logvr(v, r).Tag(tagStripe).Debug("Billing email is primary on another account, skipping auto-verification") |
| 267 |
return // Collision: skip + let the generic no-recovery-email warning nudge instead |
| 268 |
} |
| 269 |
logvr(v, r).Tag(tagStripe).Field("email", billingEmail).Info("Sending verification link to billing email") |
| 270 |
if err := s.enqueueEmailVerification(userID, billingEmail); err != nil { |
| 271 |
logvr(v, r).Tag(tagStripe).Err(err).Warn("Failed to enqueue billing email verification") |
| 272 |
} |
| 273 |
} |
| 274 |
|
| 275 |
// handleAccountBillingSubscriptionUpdate updates an existing Stripe subscription to a new price, and updates |
| 276 |
// a user's tier accordingly. This endpoint only works if there is an existing subscription. |
| 277 |
func (s *Server) handleAccountBillingSubscriptionUpdate(w http.ResponseWriter, r *http.Request, v *visitor) error { |
| 278 |
u := v.User() |
| 279 |
if u.Billing.StripeSubscriptionID == "" { |
| 280 |
return errNoBillingSubscription |
| 281 |
} |
| 282 |
req, err := readJSONWithLimit[apiAccountBillingSubscriptionChangeRequest](r.Body, jsonBodyBytesLimit, false) |
| 283 |
if err != nil { |
| 284 |
return err |
| 285 |
} |
| 286 |
tier, err := s.userManager.Tier(req.Tier) |
| 287 |
if err != nil { |
| 288 |
return err |
| 289 |
} |
| 290 |
var priceID string |
| 291 |
if req.Interval == string(stripe.PriceRecurringIntervalMonth) && tier.StripeMonthlyPriceID != "" { |
| 292 |
priceID = tier.StripeMonthlyPriceID |
| 293 |
} else if req.Interval == string(stripe.PriceRecurringIntervalYear) && tier.StripeYearlyPriceID != "" { |
| 294 |
priceID = tier.StripeYearlyPriceID |
| 295 |
} else { |
| 296 |
return errNotAPaidTier |
| 297 |
} |
| 298 |
logvr(v, r). |
| 299 |
Tag(tagStripe). |
| 300 |
Fields(log.Context{ |
| 301 |
"new_tier_id": tier.ID, |
| 302 |
"new_tier_code": tier.Code, |
| 303 |
"new_tier_stripe_price_id": priceID, |
| 304 |
"new_tier_stripe_subscription_interval": req.Interval, |
| 305 |
// Other stripe_* fields filled by visitor context |
| 306 |
}). |
| 307 |
Info("Changing Stripe subscription and billing tier to %s/%s (price %s, %s)", tier.ID, tier.Name, priceID, req.Interval) |
| 308 |
sub, err := s.stripe.GetSubscription(u.Billing.StripeSubscriptionID) |
| 309 |
if err != nil { |
| 310 |
return err |
| 311 |
} else if sub.Items == nil || len(sub.Items.Data) != 1 { |
| 312 |
return errHTTPBadRequestBillingRequestInvalid.Wrap("no items, or more than one item") |
| 313 |
} |
| 314 |
params := &stripe.SubscriptionParams{ |
| 315 |
CancelAtPeriodEnd: stripe.Bool(false), |
| 316 |
ProrationBehavior: stripe.String(string(stripe.SubscriptionSchedulePhaseProrationBehaviorAlwaysInvoice)), |
| 317 |
Items: []*stripe.SubscriptionItemsParams{ |
| 318 |
{ |
| 319 |
ID: stripe.String(sub.Items.Data[0].ID), |
| 320 |
Price: stripe.String(priceID), |
| 321 |
}, |
| 322 |
}, |
| 323 |
} |
| 324 |
_, err = s.stripe.UpdateSubscription(sub.ID, params) |
| 325 |
if err != nil { |
| 326 |
return err |
| 327 |
} |
| 328 |
return s.writeJSON(w, newSuccessResponse()) |
| 329 |
} |
| 330 |
|
| 331 |
// handleAccountBillingSubscriptionDelete facilitates downgrading a paid user to a tier-less user, |
| 332 |
// and cancelling the Stripe subscription entirely. Note that this does not actually change the tier. |
| 333 |
// That is done by a webhook at the period end (in X days). |
| 334 |
func (s *Server) handleAccountBillingSubscriptionDelete(w http.ResponseWriter, r *http.Request, v *visitor) error { |
| 335 |
logvr(v, r).Tag(tagStripe).Info("Deleting Stripe subscription") |
| 336 |
u := v.User() |
| 337 |
if u.Billing.StripeSubscriptionID != "" { |
| 338 |
params := &stripe.SubscriptionParams{ |
| 339 |
CancelAtPeriodEnd: stripe.Bool(true), |
| 340 |
} |
| 341 |
_, err := s.stripe.UpdateSubscription(u.Billing.StripeSubscriptionID, params) |
| 342 |
if err != nil { |
| 343 |
return err |
| 344 |
} |
| 345 |
} |
| 346 |
return s.writeJSON(w, newSuccessResponse()) |
| 347 |
} |
| 348 |
|
| 349 |
// handleAccountBillingPortalSessionCreate creates a session to the customer billing portal, and returns the |
| 350 |
// redirect URL. The billing portal allows customers to change their payment methods, and cancel the subscription. |
| 351 |
func (s *Server) handleAccountBillingPortalSessionCreate(w http.ResponseWriter, r *http.Request, v *visitor) error { |
| 352 |
logvr(v, r).Tag(tagStripe).Info("Creating Stripe billing portal session") |
| 353 |
u := v.User() |
| 354 |
if u.Billing.StripeCustomerID == "" { |
| 355 |
return errHTTPBadRequestNotAPaidUser |
| 356 |
} |
| 357 |
params := &stripe.BillingPortalSessionParams{ |
| 358 |
Customer: stripe.String(u.Billing.StripeCustomerID), |
| 359 |
ReturnURL: stripe.String(s.config.BaseURL), |
| 360 |
} |
| 361 |
ps, err := s.stripe.NewPortalSession(params) |
| 362 |
if err != nil { |
| 363 |
return err |
| 364 |
} |
| 365 |
response := &apiAccountBillingPortalRedirectResponse{ |
| 366 |
RedirectURL: ps.URL, |
| 367 |
} |
| 368 |
return s.writeJSON(w, response) |
| 369 |
} |
| 370 |
|
| 371 |
// handleAccountBillingWebhook handles incoming Stripe webhooks. It mainly keeps the local user database in sync |
| 372 |
// with the Stripe view of the world. This endpoint is authorized via the Stripe webhook secret. Note that the |
| 373 |
// visitor (v) in this endpoint is the Stripe API, so we don't have u available. |
| 374 |
func (s *Server) handleAccountBillingWebhook(_ http.ResponseWriter, r *http.Request, v *visitor) error { |
| 375 |
stripeSignature := r.Header.Get("Stripe-Signature") |
| 376 |
if stripeSignature == "" { |
| 377 |
return errHTTPBadRequestBillingRequestInvalid |
| 378 |
} |
| 379 |
body, err := util.Peek(r.Body, jsonBodyBytesLimit) |
| 380 |
if err != nil { |
| 381 |
return err |
| 382 |
} else if body.LimitReached { |
| 383 |
return errHTTPEntityTooLargeJSONBody |
| 384 |
} |
| 385 |
event, err := s.stripe.ConstructWebhookEvent(body.PeekedBytes, stripeSignature, s.config.StripeWebhookKey) |
| 386 |
if err != nil { |
| 387 |
return err |
| 388 |
} else if event.Data == nil || event.Data.Raw == nil { |
| 389 |
return errHTTPBadRequestBillingRequestInvalid |
| 390 |
} |
| 391 |
switch event.Type { |
| 392 |
case "customer.subscription.updated": |
| 393 |
return s.handleAccountBillingWebhookSubscriptionUpdated(r, v, event) |
| 394 |
case "customer.subscription.deleted": |
| 395 |
return s.handleAccountBillingWebhookSubscriptionDeleted(r, v, event) |
| 396 |
default: |
| 397 |
logvr(v, r). |
| 398 |
Tag(tagStripe). |
| 399 |
Field("stripe_webhook_type", event.Type). |
| 400 |
Warn("Unhandled Stripe webhook event %s received", event.Type) |
| 401 |
return nil |
| 402 |
} |
| 403 |
} |
| 404 |
|
| 405 |
func (s *Server) handleAccountBillingWebhookSubscriptionUpdated(r *http.Request, v *visitor, event stripe.Event) error { |
| 406 |
ev, err := util.UnmarshalJSON[apiStripeSubscriptionUpdatedEvent](io.NopCloser(bytes.NewReader(event.Data.Raw))) |
| 407 |
if err != nil { |
| 408 |
return err |
| 409 |
} 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 { |
| 410 |
logvr(v, r).Tag(tagStripe).Field("stripe_request", fmt.Sprintf("%#v", ev)).Warn("Unexpected request from Stripe") |
| 411 |
return errHTTPBadRequestBillingRequestInvalid |
| 412 |
} |
| 413 |
subscriptionID, priceID, interval := ev.ID, ev.Items.Data[0].Price.ID, ev.Items.Data[0].Price.Recurring.Interval |
| 414 |
logvr(v, r). |
| 415 |
Tag(tagStripe). |
| 416 |
Fields(log.Context{ |
| 417 |
"stripe_webhook_type": event.Type, |
| 418 |
"stripe_customer_id": ev.Customer, |
| 419 |
"stripe_price_id": priceID, |
| 420 |
"stripe_subscription_id": ev.ID, |
| 421 |
"stripe_subscription_status": ev.Status, |
| 422 |
"stripe_subscription_interval": interval, |
| 423 |
"stripe_subscription_paid_until": ev.CurrentPeriodEnd, |
| 424 |
"stripe_subscription_cancel_at": ev.CancelAt, |
| 425 |
}). |
| 426 |
Info("Updating subscription to status %s, with price %s", ev.Status, priceID) |
| 427 |
userFn := func() (*user.User, error) { |
| 428 |
return s.userManager.UserByStripeCustomer(ev.Customer) |
| 429 |
} |
| 430 |
// We retry the user retrieval function, because during the Stripe checkout, there a race between the browser |
| 431 |
// checkout success redirect (see handleAccountBillingSubscriptionCreateSuccess), and this webhook. The checkout |
| 432 |
// success call is the one that updates the user with the Stripe customer ID. |
| 433 |
u, err := util.Retry[user.User](userFn, retryUserDelays...) |
| 434 |
if err != nil { |
| 435 |
return err |
| 436 |
} |
| 437 |
v.SetUser(u) |
| 438 |
tier, err := s.userManager.TierByStripePrice(priceID) |
| 439 |
if err != nil { |
| 440 |
return err |
| 441 |
} |
| 442 |
if err := s.updateSubscriptionAndTier(r, v, u, tier, ev.Customer, subscriptionID, ev.Status, string(interval), ev.CurrentPeriodEnd, ev.CancelAt); err != nil { |
| 443 |
return err |
| 444 |
} |
| 445 |
s.publishSyncEventAsync(s.visitor(netip.IPv4Unspecified(), u)) |
| 446 |
return nil |
| 447 |
} |
| 448 |
|
| 449 |
func (s *Server) handleAccountBillingWebhookSubscriptionDeleted(r *http.Request, v *visitor, event stripe.Event) error { |
| 450 |
ev, err := util.UnmarshalJSON[apiStripeSubscriptionDeletedEvent](io.NopCloser(bytes.NewReader(event.Data.Raw))) |
| 451 |
if err != nil { |
| 452 |
return err |
| 453 |
} else if ev.Customer == "" { |
| 454 |
return errHTTPBadRequestBillingRequestInvalid |
| 455 |
} |
| 456 |
u, err := s.userManager.UserByStripeCustomer(ev.Customer) |
| 457 |
if err != nil { |
| 458 |
return err |
| 459 |
} |
| 460 |
v.SetUser(u) |
| 461 |
logvr(v, r). |
| 462 |
Tag(tagStripe). |
| 463 |
Field("stripe_webhook_type", event.Type). |
| 464 |
Info("Subscription deleted, downgrading to unpaid tier") |
| 465 |
if err := s.updateSubscriptionAndTier(r, v, u, nil, ev.Customer, "", "", "", 0, 0); err != nil { |
| 466 |
return err |
| 467 |
} |
| 468 |
s.publishSyncEventAsync(s.visitor(netip.IPv4Unspecified(), u)) |
| 469 |
return nil |
| 470 |
} |
| 471 |
|
| 472 |
func (s *Server) updateSubscriptionAndTier(r *http.Request, v *visitor, u *user.User, tier *user.Tier, customerID, subscriptionID, status, interval string, paidUntil, cancelAt int64) error { |
| 473 |
reservationsLimit := visitorDefaultReservationsLimit |
| 474 |
if tier != nil { |
| 475 |
reservationsLimit = tier.ReservationLimit |
| 476 |
} |
| 477 |
if err := s.maybeRemoveMessagesAndExcessReservations(r, v, u, reservationsLimit); err != nil { |
| 478 |
return err |
| 479 |
} |
| 480 |
if tier == nil && u.Tier != nil { |
| 481 |
logvr(v, r).Tag(tagStripe).Info("Resetting tier for user %s", u.Name) |
| 482 |
if err := s.userManager.ResetTier(u.Name); err != nil { |
| 483 |
return err |
| 484 |
} |
| 485 |
} else if tier != nil && u.TierID() != tier.ID { |
| 486 |
logvr(v, r). |
| 487 |
Tag(tagStripe). |
| 488 |
Fields(log.Context{ |
| 489 |
"new_tier_id": tier.ID, |
| 490 |
"new_tier_code": tier.Code, |
| 491 |
}). |
| 492 |
Info("Changing tier to tier %s (%s) for user %s", tier.ID, tier.Name, u.Name) |
| 493 |
if err := s.userManager.ChangeTier(u.Name, tier.Code); err != nil { |
| 494 |
return err |
| 495 |
} |
| 496 |
} |
| 497 |
// Update billing fields |
| 498 |
billing := &user.Billing{ |
| 499 |
StripeCustomerID: customerID, |
| 500 |
StripeSubscriptionID: subscriptionID, |
| 501 |
StripeSubscriptionStatus: payments.SubscriptionStatus(status), |
| 502 |
StripeSubscriptionInterval: payments.PriceRecurringInterval(interval), |
| 503 |
StripeSubscriptionPaidUntil: time.Unix(paidUntil, 0), |
| 504 |
StripeSubscriptionCancelAt: time.Unix(cancelAt, 0), |
| 505 |
} |
| 506 |
if err := s.userManager.ChangeBilling(u.Name, billing); err != nil { |
| 507 |
return err |
| 508 |
} |
| 509 |
return nil |
| 510 |
} |
| 511 |
|
| 512 |
// fetchStripePrices contacts the Stripe API to retrieve all prices. This is used by the server to cache the prices |
| 513 |
// in memory, and ultimately for the web app to display the price table. |
| 514 |
func (s *Server) fetchStripePrices() (map[string]int64, error) { |
| 515 |
log.Debug("Caching prices from Stripe API") |
| 516 |
priceMap := make(map[string]int64) |
| 517 |
prices, err := s.stripe.ListPrices(&stripe.PriceListParams{Active: stripe.Bool(true)}) |
| 518 |
if err != nil { |
| 519 |
log.Warn("Fetching Stripe prices failed: %s", err.Error()) |
| 520 |
return nil, err |
| 521 |
} |
| 522 |
for _, p := range prices { |
| 523 |
priceMap[p.ID] = p.UnitAmount |
| 524 |
log.Trace("- Caching price %s = %v", p.ID, priceMap[p.ID]) |
| 525 |
} |
| 526 |
return priceMap, nil |
| 527 |
} |
| 528 |
|
| 529 |
// stripeAPI is a small interface to facilitate mocking of the Stripe API |
| 530 |
type stripeAPI interface { |
| 531 |
NewCheckoutSession(params *stripe.CheckoutSessionParams) (*stripe.CheckoutSession, error) |
| 532 |
NewPortalSession(params *stripe.BillingPortalSessionParams) (*stripe.BillingPortalSession, error) |
| 533 |
ListPrices(params *stripe.PriceListParams) ([]*stripe.Price, error) |
| 534 |
GetCustomer(id string) (*stripe.Customer, error) |
| 535 |
GetSession(id string) (*stripe.CheckoutSession, error) |
| 536 |
GetSubscription(id string) (*stripe.Subscription, error) |
| 537 |
UpdateCustomer(id string, params *stripe.CustomerParams) (*stripe.Customer, error) |
| 538 |
UpdateSubscription(id string, params *stripe.SubscriptionParams) (*stripe.Subscription, error) |
| 539 |
CancelSubscription(id string) (*stripe.Subscription, error) |
| 540 |
ConstructWebhookEvent(payload []byte, header string, secret string) (stripe.Event, error) |
| 541 |
} |
| 542 |
|
| 543 |
// realStripeAPI is a thin shim around the Stripe functions to facilitate mocking |
| 544 |
type realStripeAPI struct{} |
| 545 |
|
| 546 |
var _ stripeAPI = (*realStripeAPI)(nil) |
| 547 |
|
| 548 |
func newStripeAPI() stripeAPI { |
| 549 |
return &realStripeAPI{} |
| 550 |
} |
| 551 |
|
| 552 |
func (s *realStripeAPI) NewCheckoutSession(params *stripe.CheckoutSessionParams) (*stripe.CheckoutSession, error) { |
| 553 |
return session.New(params) |
| 554 |
} |
| 555 |
|
| 556 |
func (s *realStripeAPI) NewPortalSession(params *stripe.BillingPortalSessionParams) (*stripe.BillingPortalSession, error) { |
| 557 |
return portalsession.New(params) |
| 558 |
} |
| 559 |
|
| 560 |
func (s *realStripeAPI) ListPrices(params *stripe.PriceListParams) ([]*stripe.Price, error) { |
| 561 |
prices := make([]*stripe.Price, 0) |
| 562 |
iter := price.List(params) |
| 563 |
for iter.Next() { |
| 564 |
prices = append(prices, iter.Price()) |
| 565 |
} |
| 566 |
if iter.Err() != nil { |
| 567 |
return nil, iter.Err() |
| 568 |
} |
| 569 |
return prices, nil |
| 570 |
} |
| 571 |
|
| 572 |
func (s *realStripeAPI) GetCustomer(id string) (*stripe.Customer, error) { |
| 573 |
return customer.Get(id, nil) |
| 574 |
} |
| 575 |
|
| 576 |
func (s *realStripeAPI) GetSession(id string) (*stripe.CheckoutSession, error) { |
| 577 |
return session.Get(id, nil) |
| 578 |
} |
| 579 |
|
| 580 |
func (s *realStripeAPI) GetSubscription(id string) (*stripe.Subscription, error) { |
| 581 |
return subscription.Get(id, nil) |
| 582 |
} |
| 583 |
|
| 584 |
func (s *realStripeAPI) UpdateCustomer(id string, params *stripe.CustomerParams) (*stripe.Customer, error) { |
| 585 |
return customer.Update(id, params) |
| 586 |
} |
| 587 |
|
| 588 |
func (s *realStripeAPI) UpdateSubscription(id string, params *stripe.SubscriptionParams) (*stripe.Subscription, error) { |
| 589 |
return subscription.Update(id, params) |
| 590 |
} |
| 591 |
|
| 592 |
func (s *realStripeAPI) CancelSubscription(id string) (*stripe.Subscription, error) { |
| 593 |
return subscription.Cancel(id, nil) |
| 594 |
} |
| 595 |
|
| 596 |
func (s *realStripeAPI) ConstructWebhookEvent(payload []byte, header string, secret string) (stripe.Event, error) { |
| 597 |
return webhook.ConstructEvent(payload, header, secret) |
| 598 |
} |