server_payments.go 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489
  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. } else if sub.Items == nil || len(sub.Items.Data) != 1 {
  225. return wrapErrHTTP(errHTTPBadRequestBillingRequestInvalid, "no items, or more than one item")
  226. }
  227. params := &stripe.SubscriptionParams{
  228. CancelAtPeriodEnd: stripe.Bool(false),
  229. ProrationBehavior: stripe.String(string(stripe.SubscriptionSchedulePhaseProrationBehaviorCreateProrations)),
  230. Items: []*stripe.SubscriptionItemsParams{
  231. {
  232. ID: stripe.String(sub.Items.Data[0].ID),
  233. Price: stripe.String(tier.StripePriceID),
  234. },
  235. },
  236. }
  237. _, err = s.stripe.UpdateSubscription(sub.ID, params)
  238. if err != nil {
  239. return err
  240. }
  241. return s.writeJSON(w, newSuccessResponse())
  242. }
  243. // handleAccountBillingSubscriptionDelete facilitates downgrading a paid user to a tier-less user,
  244. // and cancelling the Stripe subscription entirely
  245. func (s *Server) handleAccountBillingSubscriptionDelete(w http.ResponseWriter, r *http.Request, v *visitor) error {
  246. u := v.User()
  247. log.Info("%s Deleting billing subscription %s", logHTTPPrefix(v, r), u.Billing.StripeSubscriptionID)
  248. if u.Billing.StripeSubscriptionID != "" {
  249. params := &stripe.SubscriptionParams{
  250. CancelAtPeriodEnd: stripe.Bool(true),
  251. }
  252. _, err := s.stripe.UpdateSubscription(u.Billing.StripeSubscriptionID, params)
  253. if err != nil {
  254. return err
  255. }
  256. }
  257. return s.writeJSON(w, newSuccessResponse())
  258. }
  259. // handleAccountBillingPortalSessionCreate creates a session to the customer billing portal, and returns the
  260. // redirect URL. The billing portal allows customers to change their payment methods, and cancel the subscription.
  261. func (s *Server) handleAccountBillingPortalSessionCreate(w http.ResponseWriter, r *http.Request, v *visitor) error {
  262. u := v.User()
  263. if u.Billing.StripeCustomerID == "" {
  264. return errHTTPBadRequestNotAPaidUser
  265. }
  266. log.Info("%s Creating billing portal session", logHTTPPrefix(v, r))
  267. params := &stripe.BillingPortalSessionParams{
  268. Customer: stripe.String(u.Billing.StripeCustomerID),
  269. ReturnURL: stripe.String(s.config.BaseURL),
  270. }
  271. ps, err := s.stripe.NewPortalSession(params)
  272. if err != nil {
  273. return err
  274. }
  275. response := &apiAccountBillingPortalRedirectResponse{
  276. RedirectURL: ps.URL,
  277. }
  278. return s.writeJSON(w, response)
  279. }
  280. // handleAccountBillingWebhook handles incoming Stripe webhooks. It mainly keeps the local user database in sync
  281. // with the Stripe view of the world. This endpoint is authorized via the Stripe webhook secret. Note that the
  282. // visitor (v) in this endpoint is the Stripe API, so we don't have u available.
  283. func (s *Server) handleAccountBillingWebhook(_ http.ResponseWriter, r *http.Request, _ *visitor) error {
  284. stripeSignature := r.Header.Get("Stripe-Signature")
  285. if stripeSignature == "" {
  286. return errHTTPBadRequestBillingRequestInvalid
  287. }
  288. body, err := util.Peek(r.Body, jsonBodyBytesLimit)
  289. if err != nil {
  290. return err
  291. } else if body.LimitReached {
  292. return errHTTPEntityTooLargeJSONBody
  293. }
  294. event, err := s.stripe.ConstructWebhookEvent(body.PeekedBytes, stripeSignature, s.config.StripeWebhookKey)
  295. if err != nil {
  296. return err
  297. } else if event.Data == nil || event.Data.Raw == nil {
  298. return errHTTPBadRequestBillingRequestInvalid
  299. }
  300. switch event.Type {
  301. case "customer.subscription.updated":
  302. return s.handleAccountBillingWebhookSubscriptionUpdated(event.Data.Raw)
  303. case "customer.subscription.deleted":
  304. return s.handleAccountBillingWebhookSubscriptionDeleted(event.Data.Raw)
  305. default:
  306. log.Warn("STRIPE Unhandled webhook event %s received", event.Type)
  307. return nil
  308. }
  309. }
  310. func (s *Server) handleAccountBillingWebhookSubscriptionUpdated(event json.RawMessage) error {
  311. ev, err := util.UnmarshalJSON[apiStripeSubscriptionUpdatedEvent](io.NopCloser(bytes.NewReader(event)))
  312. if err != nil {
  313. return err
  314. } 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 == "" {
  315. return errHTTPBadRequestBillingRequestInvalid
  316. }
  317. subscriptionID, priceID := ev.ID, ev.Items.Data[0].Price.ID
  318. log.Info("%s Updating subscription to status %s, with price %s", logStripePrefix(ev.Customer, ev.ID), ev.Status, priceID)
  319. userFn := func() (*user.User, error) {
  320. return s.userManager.UserByStripeCustomer(ev.Customer)
  321. }
  322. u, err := util.Retry[user.User](userFn, retryUserDelays...)
  323. if err != nil {
  324. return err
  325. }
  326. tier, err := s.userManager.TierByStripePrice(priceID)
  327. if err != nil {
  328. return err
  329. }
  330. if err := s.updateSubscriptionAndTier(logStripePrefix(ev.Customer, ev.ID), u, tier, ev.Customer, subscriptionID, ev.Status, ev.CurrentPeriodEnd, ev.CancelAt); err != nil {
  331. return err
  332. }
  333. s.publishSyncEventAsync(s.visitor(netip.IPv4Unspecified(), u))
  334. return nil
  335. }
  336. func (s *Server) handleAccountBillingWebhookSubscriptionDeleted(event json.RawMessage) error {
  337. ev, err := util.UnmarshalJSON[apiStripeSubscriptionDeletedEvent](io.NopCloser(bytes.NewReader(event)))
  338. if err != nil {
  339. return err
  340. } else if ev.Customer == "" {
  341. return errHTTPBadRequestBillingRequestInvalid
  342. }
  343. log.Info("%s Subscription deleted, downgrading to unpaid tier", logStripePrefix(ev.Customer, ev.ID))
  344. u, err := s.userManager.UserByStripeCustomer(ev.Customer)
  345. if err != nil {
  346. return err
  347. }
  348. if err := s.updateSubscriptionAndTier(logStripePrefix(ev.Customer, ev.ID), u, nil, ev.Customer, "", "", 0, 0); err != nil {
  349. return err
  350. }
  351. s.publishSyncEventAsync(s.visitor(netip.IPv4Unspecified(), u))
  352. return nil
  353. }
  354. func (s *Server) updateSubscriptionAndTier(logPrefix string, u *user.User, tier *user.Tier, customerID, subscriptionID, status string, paidUntil, cancelAt int64) error {
  355. reservationsLimit := visitorDefaultReservationsLimit
  356. if tier != nil {
  357. reservationsLimit = tier.ReservationLimit
  358. }
  359. if err := s.maybeRemoveMessagesAndExcessReservations(logPrefix, u, reservationsLimit); err != nil {
  360. return err
  361. }
  362. if tier == nil {
  363. if err := s.userManager.ResetTier(u.Name); err != nil {
  364. return err
  365. }
  366. } else {
  367. if err := s.userManager.ChangeTier(u.Name, tier.Code); err != nil {
  368. return err
  369. }
  370. }
  371. // Update billing fields
  372. billing := &user.Billing{
  373. StripeCustomerID: customerID,
  374. StripeSubscriptionID: subscriptionID,
  375. StripeSubscriptionStatus: stripe.SubscriptionStatus(status),
  376. StripeSubscriptionPaidUntil: time.Unix(paidUntil, 0),
  377. StripeSubscriptionCancelAt: time.Unix(cancelAt, 0),
  378. }
  379. if err := s.userManager.ChangeBilling(u.Name, billing); err != nil {
  380. return err
  381. }
  382. return nil
  383. }
  384. // fetchStripePrices contacts the Stripe API to retrieve all prices. This is used by the server to cache the prices
  385. // in memory, and ultimately for the web app to display the price table.
  386. func (s *Server) fetchStripePrices() (map[string]string, error) {
  387. log.Debug("Caching prices from Stripe API")
  388. priceMap := make(map[string]string)
  389. prices, err := s.stripe.ListPrices(&stripe.PriceListParams{Active: stripe.Bool(true)})
  390. if err != nil {
  391. log.Warn("Fetching Stripe prices failed: %s", err.Error())
  392. return nil, err
  393. }
  394. for _, p := range prices {
  395. if p.UnitAmount%100 == 0 {
  396. priceMap[p.ID] = fmt.Sprintf("$%d", p.UnitAmount/100)
  397. } else {
  398. priceMap[p.ID] = fmt.Sprintf("$%.2f", float64(p.UnitAmount)/100)
  399. }
  400. log.Trace("- Caching price %s = %v", p.ID, priceMap[p.ID])
  401. }
  402. return priceMap, nil
  403. }
  404. // stripeAPI is a small interface to facilitate mocking of the Stripe API
  405. type stripeAPI interface {
  406. NewCheckoutSession(params *stripe.CheckoutSessionParams) (*stripe.CheckoutSession, error)
  407. NewPortalSession(params *stripe.BillingPortalSessionParams) (*stripe.BillingPortalSession, error)
  408. ListPrices(params *stripe.PriceListParams) ([]*stripe.Price, error)
  409. GetCustomer(id string) (*stripe.Customer, error)
  410. GetSession(id string) (*stripe.CheckoutSession, error)
  411. GetSubscription(id string) (*stripe.Subscription, error)
  412. UpdateCustomer(id string, params *stripe.CustomerParams) (*stripe.Customer, error)
  413. UpdateSubscription(id string, params *stripe.SubscriptionParams) (*stripe.Subscription, error)
  414. CancelSubscription(id string) (*stripe.Subscription, error)
  415. ConstructWebhookEvent(payload []byte, header string, secret string) (stripe.Event, error)
  416. }
  417. // realStripeAPI is a thin shim around the Stripe functions to facilitate mocking
  418. type realStripeAPI struct{}
  419. var _ stripeAPI = (*realStripeAPI)(nil)
  420. func newStripeAPI() stripeAPI {
  421. return &realStripeAPI{}
  422. }
  423. func (s *realStripeAPI) NewCheckoutSession(params *stripe.CheckoutSessionParams) (*stripe.CheckoutSession, error) {
  424. return session.New(params)
  425. }
  426. func (s *realStripeAPI) NewPortalSession(params *stripe.BillingPortalSessionParams) (*stripe.BillingPortalSession, error) {
  427. return portalsession.New(params)
  428. }
  429. func (s *realStripeAPI) ListPrices(params *stripe.PriceListParams) ([]*stripe.Price, error) {
  430. prices := make([]*stripe.Price, 0)
  431. iter := price.List(params)
  432. for iter.Next() {
  433. prices = append(prices, iter.Price())
  434. }
  435. if iter.Err() != nil {
  436. return nil, iter.Err()
  437. }
  438. return prices, nil
  439. }
  440. func (s *realStripeAPI) GetCustomer(id string) (*stripe.Customer, error) {
  441. return customer.Get(id, nil)
  442. }
  443. func (s *realStripeAPI) GetSession(id string) (*stripe.CheckoutSession, error) {
  444. return session.Get(id, nil)
  445. }
  446. func (s *realStripeAPI) GetSubscription(id string) (*stripe.Subscription, error) {
  447. return subscription.Get(id, nil)
  448. }
  449. func (s *realStripeAPI) UpdateCustomer(id string, params *stripe.CustomerParams) (*stripe.Customer, error) {
  450. return customer.Update(id, params)
  451. }
  452. func (s *realStripeAPI) UpdateSubscription(id string, params *stripe.SubscriptionParams) (*stripe.Subscription, error) {
  453. return subscription.Update(id, params)
  454. }
  455. func (s *realStripeAPI) CancelSubscription(id string) (*stripe.Subscription, error) {
  456. return subscription.Cancel(id, nil)
  457. }
  458. func (s *realStripeAPI) ConstructWebhookEvent(payload []byte, header string, secret string) (stripe.Event, error) {
  459. return webhook.ConstructEvent(payload, header, secret)
  460. }