server_payments.go 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366
  1. package server
  2. import (
  3. "encoding/json"
  4. "errors"
  5. "fmt"
  6. "github.com/stripe/stripe-go/v74"
  7. portalsession "github.com/stripe/stripe-go/v74/billingportal/session"
  8. "github.com/stripe/stripe-go/v74/checkout/session"
  9. "github.com/stripe/stripe-go/v74/customer"
  10. "github.com/stripe/stripe-go/v74/price"
  11. "github.com/stripe/stripe-go/v74/subscription"
  12. "github.com/stripe/stripe-go/v74/webhook"
  13. "github.com/tidwall/gjson"
  14. "heckel.io/ntfy/log"
  15. "heckel.io/ntfy/user"
  16. "heckel.io/ntfy/util"
  17. "net/http"
  18. "net/netip"
  19. "time"
  20. )
  21. const (
  22. stripeBodyBytesLimit = 16384
  23. )
  24. var (
  25. errNotAPaidTier = errors.New("tier does not have billing price identifier")
  26. errMultipleBillingSubscriptions = errors.New("cannot have multiple billing subscriptions")
  27. errNoBillingSubscription = errors.New("user does not have an active billing subscription")
  28. )
  29. // handleBillingTiersGet returns all available paid tiers, and the free tier. This is to populate the upgrade dialog
  30. // in the UI. Note that this endpoint does NOT have a user context (no v.user!).
  31. func (s *Server) handleBillingTiersGet(w http.ResponseWriter, _ *http.Request, _ *visitor) error {
  32. tiers, err := s.userManager.Tiers()
  33. if err != nil {
  34. return err
  35. }
  36. freeTier := defaultVisitorLimits(s.config)
  37. response := []*apiAccountBillingTier{
  38. {
  39. // Free tier: no code, name or price
  40. Limits: &apiAccountLimits{
  41. Messages: freeTier.MessagesLimit,
  42. MessagesExpiryDuration: int64(freeTier.MessagesExpiryDuration.Seconds()),
  43. Emails: freeTier.EmailsLimit,
  44. Reservations: freeTier.ReservationsLimit,
  45. AttachmentTotalSize: freeTier.AttachmentTotalSizeLimit,
  46. AttachmentFileSize: freeTier.AttachmentFileSizeLimit,
  47. AttachmentExpiryDuration: int64(freeTier.AttachmentExpiryDuration.Seconds()),
  48. },
  49. },
  50. }
  51. for _, tier := range tiers {
  52. if tier.StripePriceID == "" {
  53. continue
  54. }
  55. priceStr, ok := s.priceCache[tier.StripePriceID]
  56. if !ok {
  57. p, err := price.Get(tier.StripePriceID, nil)
  58. if err != nil {
  59. return err
  60. }
  61. if p.UnitAmount%100 == 0 {
  62. priceStr = fmt.Sprintf("$%d", p.UnitAmount/100)
  63. } else {
  64. priceStr = fmt.Sprintf("$%.2f", float64(p.UnitAmount)/100)
  65. }
  66. s.priceCache[tier.StripePriceID] = priceStr // FIXME race, make this sync.Map or something
  67. }
  68. response = append(response, &apiAccountBillingTier{
  69. Code: tier.Code,
  70. Name: tier.Name,
  71. Price: priceStr,
  72. Limits: &apiAccountLimits{
  73. Messages: tier.MessagesLimit,
  74. MessagesExpiryDuration: int64(tier.MessagesExpiryDuration.Seconds()),
  75. Emails: tier.EmailsLimit,
  76. Reservations: tier.ReservationsLimit,
  77. AttachmentTotalSize: tier.AttachmentTotalSizeLimit,
  78. AttachmentFileSize: tier.AttachmentFileSizeLimit,
  79. AttachmentExpiryDuration: int64(tier.AttachmentExpiryDuration.Seconds()),
  80. },
  81. })
  82. }
  83. w.Header().Set("Content-Type", "application/json")
  84. w.Header().Set("Access-Control-Allow-Origin", "*") // FIXME remove this
  85. if err := json.NewEncoder(w).Encode(response); err != nil {
  86. return err
  87. }
  88. return nil
  89. }
  90. // handleAccountBillingSubscriptionCreate creates a Stripe checkout flow to create a user subscription. The tier
  91. // will be updated by a subsequent webhook from Stripe, once the subscription becomes active.
  92. func (s *Server) handleAccountBillingSubscriptionCreate(w http.ResponseWriter, r *http.Request, v *visitor) error {
  93. if v.user.Billing.StripeSubscriptionID != "" {
  94. return errHTTPBadRequestBillingSubscriptionExists
  95. }
  96. req, err := readJSONWithLimit[apiAccountBillingSubscriptionChangeRequest](r.Body, jsonBodyBytesLimit)
  97. if err != nil {
  98. return err
  99. }
  100. tier, err := s.userManager.Tier(req.Tier)
  101. if err != nil {
  102. return err
  103. } else if tier.StripePriceID == "" {
  104. return errNotAPaidTier
  105. }
  106. log.Info("Stripe: No existing subscription, creating checkout flow")
  107. var stripeCustomerID *string
  108. if v.user.Billing.StripeCustomerID != "" {
  109. stripeCustomerID = &v.user.Billing.StripeCustomerID
  110. stripeCustomer, err := customer.Get(v.user.Billing.StripeCustomerID, nil)
  111. if err != nil {
  112. return err
  113. } else if stripeCustomer.Subscriptions != nil && len(stripeCustomer.Subscriptions.Data) > 0 {
  114. return errMultipleBillingSubscriptions
  115. }
  116. }
  117. successURL := s.config.BaseURL + apiAccountBillingSubscriptionCheckoutSuccessTemplate
  118. params := &stripe.CheckoutSessionParams{
  119. Customer: stripeCustomerID, // A user may have previously deleted their subscription
  120. ClientReferenceID: &v.user.Name,
  121. SuccessURL: &successURL,
  122. Mode: stripe.String(string(stripe.CheckoutSessionModeSubscription)),
  123. AllowPromotionCodes: stripe.Bool(true),
  124. LineItems: []*stripe.CheckoutSessionLineItemParams{
  125. {
  126. Price: stripe.String(tier.StripePriceID),
  127. Quantity: stripe.Int64(1),
  128. },
  129. },
  130. /*AutomaticTax: &stripe.CheckoutSessionAutomaticTaxParams{
  131. Enabled: stripe.Bool(true),
  132. },*/
  133. }
  134. sess, err := session.New(params)
  135. if err != nil {
  136. return err
  137. }
  138. response := &apiAccountBillingSubscriptionCreateResponse{
  139. RedirectURL: sess.URL,
  140. }
  141. w.Header().Set("Content-Type", "application/json")
  142. w.Header().Set("Access-Control-Allow-Origin", "*") // FIXME remove this
  143. if err := json.NewEncoder(w).Encode(response); err != nil {
  144. return err
  145. }
  146. return nil
  147. }
  148. func (s *Server) handleAccountBillingSubscriptionCreateSuccess(w http.ResponseWriter, r *http.Request, _ *visitor) error {
  149. // We don't have a v.user in this endpoint, only a userManager!
  150. matches := apiAccountBillingSubscriptionCheckoutSuccessRegex.FindStringSubmatch(r.URL.Path)
  151. if len(matches) != 2 {
  152. return errHTTPInternalErrorInvalidPath
  153. }
  154. sessionID := matches[1]
  155. sess, err := session.Get(sessionID, nil) // FIXME how do I rate limit this?
  156. if err != nil {
  157. log.Warn("Stripe: %s", err)
  158. return errHTTPBadRequestBillingRequestInvalid
  159. } else if sess.Customer == nil || sess.Subscription == nil || sess.ClientReferenceID == "" {
  160. return wrapErrHTTP(errHTTPBadRequestBillingRequestInvalid, "customer or subscription not found")
  161. }
  162. sub, err := subscription.Get(sess.Subscription.ID, nil)
  163. if err != nil {
  164. return err
  165. } else if sub.Items == nil || len(sub.Items.Data) != 1 || sub.Items.Data[0].Price == nil {
  166. return wrapErrHTTP(errHTTPBadRequestBillingRequestInvalid, "more than one line item in existing subscription")
  167. }
  168. tier, err := s.userManager.TierByStripePrice(sub.Items.Data[0].Price.ID)
  169. if err != nil {
  170. return err
  171. }
  172. u, err := s.userManager.User(sess.ClientReferenceID)
  173. if err != nil {
  174. return err
  175. }
  176. if err := s.updateSubscriptionAndTier(u, sess.Customer.ID, sub.ID, string(sub.Status), sub.CurrentPeriodEnd, sub.CancelAt, tier.Code); err != nil {
  177. return err
  178. }
  179. http.Redirect(w, r, s.config.BaseURL+accountPath, http.StatusSeeOther)
  180. return nil
  181. }
  182. // handleAccountBillingSubscriptionUpdate updates an existing Stripe subscription to a new price, and updates
  183. // a user's tier accordingly. This endpoint only works if there is an existing subscription.
  184. func (s *Server) handleAccountBillingSubscriptionUpdate(w http.ResponseWriter, r *http.Request, v *visitor) error {
  185. if v.user.Billing.StripeSubscriptionID == "" {
  186. return errNoBillingSubscription
  187. }
  188. req, err := readJSONWithLimit[apiAccountBillingSubscriptionChangeRequest](r.Body, jsonBodyBytesLimit)
  189. if err != nil {
  190. return err
  191. }
  192. tier, err := s.userManager.Tier(req.Tier)
  193. if err != nil {
  194. return err
  195. }
  196. log.Info("Stripe: Changing tier and subscription to %s", tier.Code)
  197. sub, err := subscription.Get(v.user.Billing.StripeSubscriptionID, nil)
  198. if err != nil {
  199. return err
  200. }
  201. params := &stripe.SubscriptionParams{
  202. CancelAtPeriodEnd: stripe.Bool(false),
  203. ProrationBehavior: stripe.String(string(stripe.SubscriptionSchedulePhaseProrationBehaviorCreateProrations)),
  204. Items: []*stripe.SubscriptionItemsParams{
  205. {
  206. ID: stripe.String(sub.Items.Data[0].ID),
  207. Price: stripe.String(tier.StripePriceID),
  208. },
  209. },
  210. }
  211. _, err = subscription.Update(sub.ID, params)
  212. if err != nil {
  213. return err
  214. }
  215. w.Header().Set("Content-Type", "application/json")
  216. w.Header().Set("Access-Control-Allow-Origin", "*") // FIXME remove this
  217. if err := json.NewEncoder(w).Encode(newSuccessResponse()); err != nil {
  218. return err
  219. }
  220. return nil
  221. }
  222. // handleAccountBillingSubscriptionDelete facilitates downgrading a paid user to a tier-less user,
  223. // and cancelling the Stripe subscription entirely
  224. func (s *Server) handleAccountBillingSubscriptionDelete(w http.ResponseWriter, r *http.Request, v *visitor) error {
  225. if v.user.Billing.StripeSubscriptionID != "" {
  226. params := &stripe.SubscriptionParams{
  227. CancelAtPeriodEnd: stripe.Bool(true),
  228. }
  229. _, err := subscription.Update(v.user.Billing.StripeSubscriptionID, params)
  230. if err != nil {
  231. return err
  232. }
  233. }
  234. w.Header().Set("Content-Type", "application/json")
  235. w.Header().Set("Access-Control-Allow-Origin", "*") // FIXME remove this
  236. if err := json.NewEncoder(w).Encode(newSuccessResponse()); err != nil {
  237. return err
  238. }
  239. return nil
  240. }
  241. func (s *Server) handleAccountBillingPortalSessionCreate(w http.ResponseWriter, r *http.Request, v *visitor) error {
  242. if v.user.Billing.StripeCustomerID == "" {
  243. return errHTTPBadRequestNotAPaidUser
  244. }
  245. params := &stripe.BillingPortalSessionParams{
  246. Customer: stripe.String(v.user.Billing.StripeCustomerID),
  247. ReturnURL: stripe.String(s.config.BaseURL),
  248. }
  249. ps, err := portalsession.New(params)
  250. if err != nil {
  251. return err
  252. }
  253. response := &apiAccountBillingPortalRedirectResponse{
  254. RedirectURL: ps.URL,
  255. }
  256. w.Header().Set("Content-Type", "application/json")
  257. w.Header().Set("Access-Control-Allow-Origin", "*") // FIXME remove this
  258. if err := json.NewEncoder(w).Encode(response); err != nil {
  259. return err
  260. }
  261. return nil
  262. }
  263. // handleAccountBillingWebhook handles incoming Stripe webhooks. It mainly keeps the local user database in sync
  264. // with the Stripe view of the world. This endpoint is authorized via the Stripe webhook secret. Note that the
  265. // visitor (v) in this endpoint is the Stripe API, so we don't have v.user available.
  266. func (s *Server) handleAccountBillingWebhook(w http.ResponseWriter, r *http.Request, _ *visitor) error {
  267. stripeSignature := r.Header.Get("Stripe-Signature")
  268. if stripeSignature == "" {
  269. return errHTTPBadRequestBillingRequestInvalid
  270. }
  271. body, err := util.Peek(r.Body, stripeBodyBytesLimit)
  272. if err != nil {
  273. return err
  274. } else if body.LimitReached {
  275. return errHTTPEntityTooLargeJSONBody
  276. }
  277. event, err := webhook.ConstructEvent(body.PeekedBytes, stripeSignature, s.config.StripeWebhookKey)
  278. if err != nil {
  279. return errHTTPBadRequestBillingRequestInvalid
  280. } else if event.Data == nil || event.Data.Raw == nil {
  281. return errHTTPBadRequestBillingRequestInvalid
  282. }
  283. log.Info("Stripe: webhook event %s received", event.Type)
  284. switch event.Type {
  285. case "customer.subscription.updated":
  286. return s.handleAccountBillingWebhookSubscriptionUpdated(event.Data.Raw)
  287. case "customer.subscription.deleted":
  288. return s.handleAccountBillingWebhookSubscriptionDeleted(event.Data.Raw)
  289. default:
  290. return nil
  291. }
  292. }
  293. func (s *Server) handleAccountBillingWebhookSubscriptionUpdated(event json.RawMessage) error {
  294. subscriptionID := gjson.GetBytes(event, "id")
  295. customerID := gjson.GetBytes(event, "customer")
  296. status := gjson.GetBytes(event, "status")
  297. currentPeriodEnd := gjson.GetBytes(event, "current_period_end")
  298. cancelAt := gjson.GetBytes(event, "cancel_at")
  299. priceID := gjson.GetBytes(event, "items.data.0.price.id")
  300. if !subscriptionID.Exists() || !status.Exists() || !currentPeriodEnd.Exists() || !cancelAt.Exists() || !priceID.Exists() {
  301. return errHTTPBadRequestBillingRequestInvalid
  302. }
  303. log.Info("Stripe: customer %s: Updating subscription to status %s, with price %s", customerID.String(), status, priceID)
  304. u, err := s.userManager.UserByStripeCustomer(customerID.String())
  305. if err != nil {
  306. return err
  307. }
  308. tier, err := s.userManager.TierByStripePrice(priceID.String())
  309. if err != nil {
  310. return err
  311. }
  312. if err := s.updateSubscriptionAndTier(u, customerID.String(), subscriptionID.String(), status.String(), currentPeriodEnd.Int(), cancelAt.Int(), tier.Code); err != nil {
  313. return err
  314. }
  315. s.publishSyncEventAsync(s.visitorFromUser(u, netip.IPv4Unspecified()))
  316. return nil
  317. }
  318. func (s *Server) handleAccountBillingWebhookSubscriptionDeleted(event json.RawMessage) error {
  319. customerID := gjson.GetBytes(event, "customer")
  320. if !customerID.Exists() {
  321. return errHTTPBadRequestBillingRequestInvalid
  322. }
  323. log.Info("Stripe: customer %s: subscription deleted, downgrading to unpaid tier", customerID.String())
  324. u, err := s.userManager.UserByStripeCustomer(customerID.String())
  325. if err != nil {
  326. return err
  327. }
  328. if err := s.updateSubscriptionAndTier(u, customerID.String(), "", "", 0, 0, ""); err != nil {
  329. return err
  330. }
  331. s.publishSyncEventAsync(s.visitorFromUser(u, netip.IPv4Unspecified()))
  332. return nil
  333. }
  334. func (s *Server) updateSubscriptionAndTier(u *user.User, customerID, subscriptionID, status string, paidUntil, cancelAt int64, tier string) error {
  335. u.Billing.StripeCustomerID = customerID
  336. u.Billing.StripeSubscriptionID = subscriptionID
  337. u.Billing.StripeSubscriptionStatus = stripe.SubscriptionStatus(status)
  338. u.Billing.StripeSubscriptionPaidUntil = time.Unix(paidUntil, 0)
  339. u.Billing.StripeSubscriptionCancelAt = time.Unix(cancelAt, 0)
  340. if tier == "" {
  341. if err := s.userManager.ResetTier(u.Name); err != nil {
  342. return err
  343. }
  344. } else {
  345. if err := s.userManager.ChangeTier(u.Name, tier); err != nil {
  346. return err
  347. }
  348. }
  349. if err := s.userManager.ChangeBilling(u); err != nil {
  350. return err
  351. }
  352. return nil
  353. }