server_payments.go 13 KB

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