server_payments.go 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487
  1. package server
  2. import (
  3. "bytes"
  4. "encoding/json"
  5. "errors"
  6. "fmt"
  7. "github.com/stripe/stripe-go/v74"
  8. portalsession "github.com/stripe/stripe-go/v74/billingportal/session"
  9. "github.com/stripe/stripe-go/v74/checkout/session"
  10. "github.com/stripe/stripe-go/v74/customer"
  11. "github.com/stripe/stripe-go/v74/price"
  12. "github.com/stripe/stripe-go/v74/subscription"
  13. "github.com/stripe/stripe-go/v74/webhook"
  14. "heckel.io/ntfy/log"
  15. "heckel.io/ntfy/user"
  16. "heckel.io/ntfy/util"
  17. "io"
  18. "net/http"
  19. "net/netip"
  20. "time"
  21. )
  22. // Payments in ntfy are done via Stripe.
  23. //
  24. // Pretty much all payments related things are in this file. The following processes
  25. // handle payments:
  26. //
  27. // - Checkout:
  28. // Creating a Stripe customer and subscription via the Checkout flow. This flow is only used if the
  29. // ntfy user is not already a Stripe customer. This requires redirecting to the Stripe checkout page.
  30. // It is implemented in handleAccountBillingSubscriptionCreate and the success callback
  31. // handleAccountBillingSubscriptionCreateSuccess.
  32. // - Update subscription:
  33. // Switching between Stripe subscriptions (upgrade/downgrade) is handled via
  34. // handleAccountBillingSubscriptionUpdate. This also handles proration.
  35. // - Cancel subscription (at period end):
  36. // Users can cancel the Stripe subscription via the web app at the end of the billing period. This
  37. // simply updates the subscription and Stripe will cancel it. Users cannot immediately cancel the
  38. // subscription.
  39. // - Webhooks:
  40. // Whenever a subscription changes (updated, deleted), Stripe sends us a request via a webhook.
  41. // This is used to keep the local user database fields up to date. Stripe is the source of truth.
  42. // What Stripe says is mirrored and not questioned.
  43. var (
  44. errNotAPaidTier = errors.New("tier does not have billing price identifier")
  45. errMultipleBillingSubscriptions = errors.New("cannot have multiple billing subscriptions")
  46. errNoBillingSubscription = errors.New("user does not have an active billing subscription")
  47. )
  48. var (
  49. retryUserDelays = []time.Duration{3 * time.Second, 5 * time.Second, 7 * time.Second}
  50. )
  51. // handleBillingTiersGet returns all available paid tiers, and the free tier. This is to populate the upgrade dialog
  52. // in the UI. Note that this endpoint does NOT have a user context (no u!).
  53. func (s *Server) handleBillingTiersGet(w http.ResponseWriter, _ *http.Request, _ *visitor) error {
  54. tiers, err := s.userManager.Tiers()
  55. if err != nil {
  56. return err
  57. }
  58. freeTier := configBasedVisitorLimits(s.config)
  59. response := []*apiAccountBillingTier{
  60. {
  61. // This is a bit of a hack: This is the "Free" tier. It has no tier code, name or price.
  62. Limits: &apiAccountLimits{
  63. Basis: string(visitorLimitBasisIP),
  64. Messages: freeTier.MessageLimit,
  65. MessagesExpiryDuration: int64(freeTier.MessageExpiryDuration.Seconds()),
  66. Emails: freeTier.EmailLimit,
  67. Reservations: freeTier.ReservationsLimit,
  68. AttachmentTotalSize: freeTier.AttachmentTotalSizeLimit,
  69. AttachmentFileSize: freeTier.AttachmentFileSizeLimit,
  70. AttachmentExpiryDuration: int64(freeTier.AttachmentExpiryDuration.Seconds()),
  71. },
  72. },
  73. }
  74. prices, err := s.priceCache.Value()
  75. if err != nil {
  76. return err
  77. }
  78. for _, tier := range tiers {
  79. priceStr, ok := prices[tier.StripePriceID]
  80. if tier.StripePriceID == "" || !ok {
  81. continue
  82. }
  83. response = append(response, &apiAccountBillingTier{
  84. Code: tier.Code,
  85. Name: tier.Name,
  86. Price: priceStr,
  87. Limits: &apiAccountLimits{
  88. Basis: string(visitorLimitBasisTier),
  89. Messages: tier.MessageLimit,
  90. MessagesExpiryDuration: int64(tier.MessageExpiryDuration.Seconds()),
  91. Emails: tier.EmailLimit,
  92. Reservations: tier.ReservationLimit,
  93. AttachmentTotalSize: tier.AttachmentTotalSizeLimit,
  94. AttachmentFileSize: tier.AttachmentFileSizeLimit,
  95. AttachmentExpiryDuration: int64(tier.AttachmentExpiryDuration.Seconds()),
  96. },
  97. })
  98. }
  99. return s.writeJSON(w, response)
  100. }
  101. // handleAccountBillingSubscriptionCreate creates a Stripe checkout flow to create a user subscription. The tier
  102. // will be updated by a subsequent webhook from Stripe, once the subscription becomes active.
  103. func (s *Server) handleAccountBillingSubscriptionCreate(w http.ResponseWriter, r *http.Request, v *visitor) error {
  104. u := v.User()
  105. if u.Billing.StripeSubscriptionID != "" {
  106. return errHTTPBadRequestBillingSubscriptionExists
  107. }
  108. req, err := readJSONWithLimit[apiAccountBillingSubscriptionChangeRequest](r.Body, jsonBodyBytesLimit, false)
  109. if err != nil {
  110. return err
  111. }
  112. tier, err := s.userManager.Tier(req.Tier)
  113. if err != nil {
  114. return err
  115. } else if tier.StripePriceID == "" {
  116. return errNotAPaidTier
  117. }
  118. log.Info("%s Creating Stripe checkout flow", logHTTPPrefix(v, r))
  119. var stripeCustomerID *string
  120. if u.Billing.StripeCustomerID != "" {
  121. stripeCustomerID = &u.Billing.StripeCustomerID
  122. stripeCustomer, err := s.stripe.GetCustomer(u.Billing.StripeCustomerID)
  123. if err != nil {
  124. return err
  125. } else if stripeCustomer.Subscriptions != nil && len(stripeCustomer.Subscriptions.Data) > 0 {
  126. return errMultipleBillingSubscriptions
  127. }
  128. }
  129. successURL := s.config.BaseURL + apiAccountBillingSubscriptionCheckoutSuccessTemplate
  130. params := &stripe.CheckoutSessionParams{
  131. Customer: stripeCustomerID, // A user may have previously deleted their subscription
  132. ClientReferenceID: &u.ID,
  133. SuccessURL: &successURL,
  134. Mode: stripe.String(string(stripe.CheckoutSessionModeSubscription)),
  135. AllowPromotionCodes: stripe.Bool(true),
  136. LineItems: []*stripe.CheckoutSessionLineItemParams{
  137. {
  138. Price: stripe.String(tier.StripePriceID),
  139. Quantity: stripe.Int64(1),
  140. },
  141. },
  142. Params: stripe.Params{
  143. Metadata: map[string]string{
  144. "user_id": u.ID,
  145. },
  146. },
  147. }
  148. sess, err := s.stripe.NewCheckoutSession(params)
  149. if err != nil {
  150. return err
  151. }
  152. response := &apiAccountBillingSubscriptionCreateResponse{
  153. RedirectURL: sess.URL,
  154. }
  155. return s.writeJSON(w, response)
  156. }
  157. // handleAccountBillingSubscriptionCreateSuccess is called after the Stripe checkout session has succeeded. We use
  158. // the session ID in the URL to retrieve the Stripe subscription and update the local database. This is the first
  159. // and only time we can map the local username with the Stripe customer ID.
  160. func (s *Server) handleAccountBillingSubscriptionCreateSuccess(w http.ResponseWriter, r *http.Request, v *visitor) error {
  161. // We don't have v.User() in this endpoint, only a userManager!
  162. matches := apiAccountBillingSubscriptionCheckoutSuccessRegex.FindStringSubmatch(r.URL.Path)
  163. if len(matches) != 2 {
  164. return errHTTPInternalErrorInvalidPath
  165. }
  166. sessionID := matches[1]
  167. sess, err := s.stripe.GetSession(sessionID) // FIXME How do we rate limit this?
  168. if err != nil {
  169. return err
  170. } else if sess.Customer == nil || sess.Subscription == nil || sess.ClientReferenceID == "" {
  171. return wrapErrHTTP(errHTTPBadRequestBillingRequestInvalid, "customer or subscription not found")
  172. }
  173. sub, err := s.stripe.GetSubscription(sess.Subscription.ID)
  174. if err != nil {
  175. return err
  176. } else if sub.Items == nil || len(sub.Items.Data) != 1 || sub.Items.Data[0].Price == nil {
  177. return wrapErrHTTP(errHTTPBadRequestBillingRequestInvalid, "more than one line item in existing subscription")
  178. }
  179. tier, err := s.userManager.TierByStripePrice(sub.Items.Data[0].Price.ID)
  180. if err != nil {
  181. return err
  182. }
  183. u, err := s.userManager.UserByID(sess.ClientReferenceID)
  184. if err != nil {
  185. return err
  186. }
  187. v.SetUser(u)
  188. customerParams := &stripe.CustomerParams{
  189. Params: stripe.Params{
  190. Metadata: map[string]string{
  191. "user_id": u.ID,
  192. "user_name": u.Name,
  193. },
  194. },
  195. }
  196. if _, err := s.stripe.UpdateCustomer(sess.Customer.ID, customerParams); err != nil {
  197. return err
  198. }
  199. if err := s.updateSubscriptionAndTier(logHTTPPrefix(v, r), u, tier, sess.Customer.ID, sub.ID, string(sub.Status), sub.CurrentPeriodEnd, sub.CancelAt); err != nil {
  200. return err
  201. }
  202. http.Redirect(w, r, s.config.BaseURL+accountPath, http.StatusSeeOther)
  203. return nil
  204. }
  205. // handleAccountBillingSubscriptionUpdate updates an existing Stripe subscription to a new price, and updates
  206. // a user's tier accordingly. This endpoint only works if there is an existing subscription.
  207. func (s *Server) handleAccountBillingSubscriptionUpdate(w http.ResponseWriter, r *http.Request, v *visitor) error {
  208. u := v.User()
  209. if u.Billing.StripeSubscriptionID == "" {
  210. return errNoBillingSubscription
  211. }
  212. req, err := readJSONWithLimit[apiAccountBillingSubscriptionChangeRequest](r.Body, jsonBodyBytesLimit, false)
  213. if err != nil {
  214. return err
  215. }
  216. tier, err := s.userManager.Tier(req.Tier)
  217. if err != nil {
  218. return err
  219. }
  220. log.Info("%s Changing billing tier to %s (price %s) for subscription %s", logHTTPPrefix(v, r), tier.Code, tier.StripePriceID, u.Billing.StripeSubscriptionID)
  221. sub, err := s.stripe.GetSubscription(u.Billing.StripeSubscriptionID)
  222. if err != nil {
  223. return err
  224. }
  225. params := &stripe.SubscriptionParams{
  226. CancelAtPeriodEnd: stripe.Bool(false),
  227. ProrationBehavior: stripe.String(string(stripe.SubscriptionSchedulePhaseProrationBehaviorCreateProrations)),
  228. Items: []*stripe.SubscriptionItemsParams{
  229. {
  230. ID: stripe.String(sub.Items.Data[0].ID),
  231. Price: stripe.String(tier.StripePriceID),
  232. },
  233. },
  234. }
  235. _, err = s.stripe.UpdateSubscription(sub.ID, params)
  236. if err != nil {
  237. return err
  238. }
  239. return s.writeJSON(w, newSuccessResponse())
  240. }
  241. // handleAccountBillingSubscriptionDelete facilitates downgrading a paid user to a tier-less user,
  242. // and cancelling the Stripe subscription entirely
  243. func (s *Server) handleAccountBillingSubscriptionDelete(w http.ResponseWriter, r *http.Request, v *visitor) error {
  244. u := v.User()
  245. log.Info("%s Deleting billing subscription %s", logHTTPPrefix(v, r), u.Billing.StripeSubscriptionID)
  246. if u.Billing.StripeSubscriptionID != "" {
  247. params := &stripe.SubscriptionParams{
  248. CancelAtPeriodEnd: stripe.Bool(true),
  249. }
  250. _, err := s.stripe.UpdateSubscription(u.Billing.StripeSubscriptionID, params)
  251. if err != nil {
  252. return err
  253. }
  254. }
  255. return s.writeJSON(w, newSuccessResponse())
  256. }
  257. // handleAccountBillingPortalSessionCreate creates a session to the customer billing portal, and returns the
  258. // redirect URL. The billing portal allows customers to change their payment methods, and cancel the subscription.
  259. func (s *Server) handleAccountBillingPortalSessionCreate(w http.ResponseWriter, r *http.Request, v *visitor) error {
  260. u := v.User()
  261. if u.Billing.StripeCustomerID == "" {
  262. return errHTTPBadRequestNotAPaidUser
  263. }
  264. log.Info("%s Creating billing portal session", logHTTPPrefix(v, r))
  265. params := &stripe.BillingPortalSessionParams{
  266. Customer: stripe.String(u.Billing.StripeCustomerID),
  267. ReturnURL: stripe.String(s.config.BaseURL),
  268. }
  269. ps, err := s.stripe.NewPortalSession(params)
  270. if err != nil {
  271. return err
  272. }
  273. response := &apiAccountBillingPortalRedirectResponse{
  274. RedirectURL: ps.URL,
  275. }
  276. return s.writeJSON(w, response)
  277. }
  278. // handleAccountBillingWebhook handles incoming Stripe webhooks. It mainly keeps the local user database in sync
  279. // with the Stripe view of the world. This endpoint is authorized via the Stripe webhook secret. Note that the
  280. // visitor (v) in this endpoint is the Stripe API, so we don't have u available.
  281. func (s *Server) handleAccountBillingWebhook(_ http.ResponseWriter, r *http.Request, _ *visitor) error {
  282. stripeSignature := r.Header.Get("Stripe-Signature")
  283. if stripeSignature == "" {
  284. return errHTTPBadRequestBillingRequestInvalid
  285. }
  286. body, err := util.Peek(r.Body, jsonBodyBytesLimit)
  287. if err != nil {
  288. return err
  289. } else if body.LimitReached {
  290. return errHTTPEntityTooLargeJSONBody
  291. }
  292. event, err := s.stripe.ConstructWebhookEvent(body.PeekedBytes, stripeSignature, s.config.StripeWebhookKey)
  293. if err != nil {
  294. return err
  295. } else if event.Data == nil || event.Data.Raw == nil {
  296. return errHTTPBadRequestBillingRequestInvalid
  297. }
  298. switch event.Type {
  299. case "customer.subscription.updated":
  300. return s.handleAccountBillingWebhookSubscriptionUpdated(event.Data.Raw)
  301. case "customer.subscription.deleted":
  302. return s.handleAccountBillingWebhookSubscriptionDeleted(event.Data.Raw)
  303. default:
  304. log.Warn("STRIPE Unhandled webhook event %s received", event.Type)
  305. return nil
  306. }
  307. }
  308. func (s *Server) handleAccountBillingWebhookSubscriptionUpdated(event json.RawMessage) error {
  309. ev, err := util.UnmarshalJSON[apiStripeSubscriptionUpdatedEvent](io.NopCloser(bytes.NewReader(event)))
  310. if err != nil {
  311. return err
  312. } 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 == "" {
  313. return errHTTPBadRequestBillingRequestInvalid
  314. }
  315. subscriptionID, priceID := ev.ID, ev.Items.Data[0].Price.ID
  316. log.Info("%s Updating subscription to status %s, with price %s", logStripePrefix(ev.Customer, ev.ID), ev.Status, priceID)
  317. userFn := func() (*user.User, error) {
  318. return s.userManager.UserByStripeCustomer(ev.Customer)
  319. }
  320. u, err := util.Retry[user.User](userFn, retryUserDelays...)
  321. if err != nil {
  322. return err
  323. }
  324. tier, err := s.userManager.TierByStripePrice(priceID)
  325. if err != nil {
  326. return err
  327. }
  328. if err := s.updateSubscriptionAndTier(logStripePrefix(ev.Customer, ev.ID), u, tier, ev.Customer, subscriptionID, ev.Status, ev.CurrentPeriodEnd, ev.CancelAt); err != nil {
  329. return err
  330. }
  331. s.publishSyncEventAsync(s.visitor(netip.IPv4Unspecified(), u))
  332. return nil
  333. }
  334. func (s *Server) handleAccountBillingWebhookSubscriptionDeleted(event json.RawMessage) error {
  335. ev, err := util.UnmarshalJSON[apiStripeSubscriptionDeletedEvent](io.NopCloser(bytes.NewReader(event)))
  336. if err != nil {
  337. return err
  338. } else if ev.Customer == "" {
  339. return errHTTPBadRequestBillingRequestInvalid
  340. }
  341. log.Info("%s Subscription deleted, downgrading to unpaid tier", logStripePrefix(ev.Customer, ev.ID))
  342. u, err := s.userManager.UserByStripeCustomer(ev.Customer)
  343. if err != nil {
  344. return err
  345. }
  346. if err := s.updateSubscriptionAndTier(logStripePrefix(ev.Customer, ev.ID), u, nil, ev.Customer, "", "", 0, 0); err != nil {
  347. return err
  348. }
  349. s.publishSyncEventAsync(s.visitor(netip.IPv4Unspecified(), u))
  350. return nil
  351. }
  352. func (s *Server) updateSubscriptionAndTier(logPrefix string, u *user.User, tier *user.Tier, customerID, subscriptionID, status string, paidUntil, cancelAt int64) error {
  353. reservationsLimit := visitorDefaultReservationsLimit
  354. if tier != nil {
  355. reservationsLimit = tier.ReservationLimit
  356. }
  357. if err := s.maybeRemoveMessagesAndExcessReservations(logPrefix, u, reservationsLimit); err != nil {
  358. return err
  359. }
  360. if tier == nil {
  361. if err := s.userManager.ResetTier(u.Name); err != nil {
  362. return err
  363. }
  364. } else {
  365. if err := s.userManager.ChangeTier(u.Name, tier.Code); err != nil {
  366. return err
  367. }
  368. }
  369. // Update billing fields
  370. billing := &user.Billing{
  371. StripeCustomerID: customerID,
  372. StripeSubscriptionID: subscriptionID,
  373. StripeSubscriptionStatus: stripe.SubscriptionStatus(status),
  374. StripeSubscriptionPaidUntil: time.Unix(paidUntil, 0),
  375. StripeSubscriptionCancelAt: time.Unix(cancelAt, 0),
  376. }
  377. if err := s.userManager.ChangeBilling(u.Name, billing); err != nil {
  378. return err
  379. }
  380. return nil
  381. }
  382. // fetchStripePrices contacts the Stripe API to retrieve all prices. This is used by the server to cache the prices
  383. // in memory, and ultimately for the web app to display the price table.
  384. func (s *Server) fetchStripePrices() (map[string]string, error) {
  385. log.Debug("Caching prices from Stripe API")
  386. priceMap := make(map[string]string)
  387. prices, err := s.stripe.ListPrices(&stripe.PriceListParams{Active: stripe.Bool(true)})
  388. if err != nil {
  389. log.Warn("Fetching Stripe prices failed: %s", err.Error())
  390. return nil, err
  391. }
  392. for _, p := range prices {
  393. if p.UnitAmount%100 == 0 {
  394. priceMap[p.ID] = fmt.Sprintf("$%d", p.UnitAmount/100)
  395. } else {
  396. priceMap[p.ID] = fmt.Sprintf("$%.2f", float64(p.UnitAmount)/100)
  397. }
  398. log.Trace("- Caching price %s = %v", p.ID, priceMap[p.ID])
  399. }
  400. return priceMap, nil
  401. }
  402. // stripeAPI is a small interface to facilitate mocking of the Stripe API
  403. type stripeAPI interface {
  404. NewCheckoutSession(params *stripe.CheckoutSessionParams) (*stripe.CheckoutSession, error)
  405. NewPortalSession(params *stripe.BillingPortalSessionParams) (*stripe.BillingPortalSession, error)
  406. ListPrices(params *stripe.PriceListParams) ([]*stripe.Price, error)
  407. GetCustomer(id string) (*stripe.Customer, error)
  408. GetSession(id string) (*stripe.CheckoutSession, error)
  409. GetSubscription(id string) (*stripe.Subscription, error)
  410. UpdateCustomer(id string, params *stripe.CustomerParams) (*stripe.Customer, error)
  411. UpdateSubscription(id string, params *stripe.SubscriptionParams) (*stripe.Subscription, error)
  412. CancelSubscription(id string) (*stripe.Subscription, error)
  413. ConstructWebhookEvent(payload []byte, header string, secret string) (stripe.Event, error)
  414. }
  415. // realStripeAPI is a thin shim around the Stripe functions to facilitate mocking
  416. type realStripeAPI struct{}
  417. var _ stripeAPI = (*realStripeAPI)(nil)
  418. func newStripeAPI() stripeAPI {
  419. return &realStripeAPI{}
  420. }
  421. func (s *realStripeAPI) NewCheckoutSession(params *stripe.CheckoutSessionParams) (*stripe.CheckoutSession, error) {
  422. return session.New(params)
  423. }
  424. func (s *realStripeAPI) NewPortalSession(params *stripe.BillingPortalSessionParams) (*stripe.BillingPortalSession, error) {
  425. return portalsession.New(params)
  426. }
  427. func (s *realStripeAPI) ListPrices(params *stripe.PriceListParams) ([]*stripe.Price, error) {
  428. prices := make([]*stripe.Price, 0)
  429. iter := price.List(params)
  430. for iter.Next() {
  431. prices = append(prices, iter.Price())
  432. }
  433. if iter.Err() != nil {
  434. return nil, iter.Err()
  435. }
  436. return prices, nil
  437. }
  438. func (s *realStripeAPI) GetCustomer(id string) (*stripe.Customer, error) {
  439. return customer.Get(id, nil)
  440. }
  441. func (s *realStripeAPI) GetSession(id string) (*stripe.CheckoutSession, error) {
  442. return session.Get(id, nil)
  443. }
  444. func (s *realStripeAPI) GetSubscription(id string) (*stripe.Subscription, error) {
  445. return subscription.Get(id, nil)
  446. }
  447. func (s *realStripeAPI) UpdateCustomer(id string, params *stripe.CustomerParams) (*stripe.Customer, error) {
  448. return customer.Update(id, params)
  449. }
  450. func (s *realStripeAPI) UpdateSubscription(id string, params *stripe.SubscriptionParams) (*stripe.Subscription, error) {
  451. return subscription.Update(id, params)
  452. }
  453. func (s *realStripeAPI) CancelSubscription(id string) (*stripe.Subscription, error) {
  454. return subscription.Cancel(id, nil)
  455. }
  456. func (s *realStripeAPI) ConstructWebhookEvent(payload []byte, header string, secret string) (stripe.Event, error) {
  457. return webhook.ConstructEvent(payload, header, secret)
  458. }