server_payments.go 9.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287
  1. package server
  2. import (
  3. "encoding/json"
  4. "errors"
  5. "github.com/stripe/stripe-go/v74"
  6. portalsession "github.com/stripe/stripe-go/v74/billingportal/session"
  7. "github.com/stripe/stripe-go/v74/checkout/session"
  8. "github.com/stripe/stripe-go/v74/subscription"
  9. "github.com/stripe/stripe-go/v74/webhook"
  10. "github.com/tidwall/gjson"
  11. "heckel.io/ntfy/log"
  12. "heckel.io/ntfy/user"
  13. "heckel.io/ntfy/util"
  14. "net/http"
  15. "time"
  16. )
  17. const (
  18. stripeBodyBytesLimit = 16384
  19. )
  20. // handleAccountBillingSubscriptionChange facilitates all subscription/tier changes, including payment flows.
  21. //
  22. // FIXME this should be two functions!
  23. //
  24. // It handles two cases:
  25. // - Create subscription: Transition from a user without Stripe subscription to a paid subscription (Checkout flow)
  26. // - Change subscription: Switching between Stripe prices (& tiers) by changing the Stripe subscription
  27. func (s *Server) handleAccountBillingSubscriptionChange(w http.ResponseWriter, r *http.Request, v *visitor) error {
  28. req, err := readJSONWithLimit[apiAccountTierChangeRequest](r.Body, jsonBodyBytesLimit)
  29. if err != nil {
  30. return err
  31. }
  32. tier, err := s.userManager.Tier(req.Tier)
  33. if err != nil {
  34. return err
  35. }
  36. if v.user.Billing.StripeSubscriptionID == "" && tier.StripePriceID != "" {
  37. return s.handleAccountBillingSubscriptionAdd(w, v, tier)
  38. } else if v.user.Billing.StripeSubscriptionID != "" {
  39. return s.handleAccountBillingSubscriptionUpdate(w, v, tier)
  40. }
  41. return errors.New("invalid state")
  42. }
  43. // handleAccountBillingSubscriptionDelete facilitates downgrading a paid user to a tier-less user,
  44. // and cancelling the Stripe subscription entirely
  45. func (s *Server) handleAccountBillingSubscriptionDelete(w http.ResponseWriter, r *http.Request, v *visitor) error {
  46. if v.user.Billing.StripeCustomerID == "" {
  47. return errHTTPBadRequestNotAPaidUser
  48. }
  49. if v.user.Billing.StripeSubscriptionID != "" {
  50. _, err := subscription.Cancel(v.user.Billing.StripeSubscriptionID, nil)
  51. if err != nil {
  52. return err
  53. }
  54. }
  55. if err := s.userManager.ResetTier(v.user.Name); err != nil {
  56. return err
  57. }
  58. v.user.Billing.StripeSubscriptionID = ""
  59. v.user.Billing.StripeSubscriptionStatus = ""
  60. v.user.Billing.StripeSubscriptionPaidUntil = time.Unix(0, 0)
  61. if err := s.userManager.ChangeBilling(v.user); err != nil {
  62. return err
  63. }
  64. return nil
  65. }
  66. func (s *Server) handleAccountBillingSubscriptionAdd(w http.ResponseWriter, v *visitor, tier *user.Tier) error {
  67. log.Info("Stripe: No existing subscription, creating checkout flow")
  68. var stripeCustomerID *string
  69. if v.user.Billing.StripeCustomerID != "" {
  70. stripeCustomerID = &v.user.Billing.StripeCustomerID
  71. }
  72. successURL := s.config.BaseURL + accountBillingSubscriptionCheckoutSuccessTemplate
  73. params := &stripe.CheckoutSessionParams{
  74. Customer: stripeCustomerID, // A user may have previously deleted their subscription
  75. ClientReferenceID: &v.user.Name, // FIXME Should be user ID
  76. SuccessURL: &successURL,
  77. Mode: stripe.String(string(stripe.CheckoutSessionModeSubscription)),
  78. LineItems: []*stripe.CheckoutSessionLineItemParams{
  79. {
  80. Price: stripe.String(tier.StripePriceID),
  81. Quantity: stripe.Int64(1),
  82. },
  83. },
  84. /*AutomaticTax: &stripe.CheckoutSessionAutomaticTaxParams{
  85. Enabled: stripe.Bool(true),
  86. },*/
  87. }
  88. sess, err := session.New(params)
  89. if err != nil {
  90. return err
  91. }
  92. response := &apiAccountCheckoutResponse{
  93. RedirectURL: sess.URL,
  94. }
  95. w.Header().Set("Content-Type", "application/json")
  96. w.Header().Set("Access-Control-Allow-Origin", "*") // FIXME remove this
  97. if err := json.NewEncoder(w).Encode(response); err != nil {
  98. return err
  99. }
  100. return nil
  101. }
  102. func (s *Server) handleAccountBillingSubscriptionUpdate(w http.ResponseWriter, v *visitor, tier *user.Tier) error {
  103. log.Info("Stripe: Changing tier and subscription to %s", tier.Code)
  104. sub, err := subscription.Get(v.user.Billing.StripeSubscriptionID, nil)
  105. if err != nil {
  106. return err
  107. }
  108. params := &stripe.SubscriptionParams{
  109. CancelAtPeriodEnd: stripe.Bool(false),
  110. ProrationBehavior: stripe.String(string(stripe.SubscriptionSchedulePhaseProrationBehaviorCreateProrations)),
  111. Items: []*stripe.SubscriptionItemsParams{
  112. {
  113. ID: stripe.String(sub.Items.Data[0].ID),
  114. Price: stripe.String(tier.StripePriceID),
  115. },
  116. },
  117. }
  118. _, err = subscription.Update(sub.ID, params)
  119. if err != nil {
  120. return err
  121. }
  122. response := &apiAccountCheckoutResponse{}
  123. w.Header().Set("Content-Type", "application/json")
  124. w.Header().Set("Access-Control-Allow-Origin", "*") // FIXME remove this
  125. if err := json.NewEncoder(w).Encode(response); err != nil {
  126. return err
  127. }
  128. return nil
  129. }
  130. func (s *Server) handleAccountCheckoutSessionSuccessGet(w http.ResponseWriter, r *http.Request, v *visitor) error {
  131. // We don't have a v.user in this endpoint, only a userManager!
  132. matches := accountBillingSubscriptionCheckoutSuccessRegex.FindStringSubmatch(r.URL.Path)
  133. if len(matches) != 2 {
  134. return errHTTPInternalErrorInvalidPath
  135. }
  136. sessionID := matches[1]
  137. // FIXME how do I rate limit this?
  138. sess, err := session.Get(sessionID, nil)
  139. if err != nil {
  140. log.Warn("Stripe: %s", err)
  141. return errHTTPBadRequestInvalidStripeRequest
  142. } else if sess.Customer == nil || sess.Subscription == nil || sess.ClientReferenceID == "" {
  143. log.Warn("Stripe: Unexpected session, customer or subscription not found")
  144. return errHTTPBadRequestInvalidStripeRequest
  145. }
  146. sub, err := subscription.Get(sess.Subscription.ID, nil)
  147. if err != nil {
  148. return err
  149. } else if sub.Items == nil || len(sub.Items.Data) != 1 || sub.Items.Data[0].Price == nil {
  150. log.Error("Stripe: Unexpected subscription, expected exactly one line item")
  151. return errHTTPBadRequestInvalidStripeRequest
  152. }
  153. priceID := sub.Items.Data[0].Price.ID
  154. tier, err := s.userManager.TierByStripePrice(priceID)
  155. if err != nil {
  156. return err
  157. }
  158. u, err := s.userManager.User(sess.ClientReferenceID)
  159. if err != nil {
  160. return err
  161. }
  162. u.Billing.StripeCustomerID = sess.Customer.ID
  163. u.Billing.StripeSubscriptionID = sub.ID
  164. u.Billing.StripeSubscriptionStatus = sub.Status
  165. u.Billing.StripeSubscriptionPaidUntil = time.Unix(sub.CurrentPeriodEnd, 0)
  166. if err := s.userManager.ChangeBilling(u); err != nil {
  167. return err
  168. }
  169. if err := s.userManager.ChangeTier(u.Name, tier.Code); err != nil {
  170. return err
  171. }
  172. accountURL := s.config.BaseURL + "/account" // FIXME
  173. http.Redirect(w, r, accountURL, http.StatusSeeOther)
  174. return nil
  175. }
  176. func (s *Server) handleAccountBillingPortalSessionCreate(w http.ResponseWriter, r *http.Request, v *visitor) error {
  177. if v.user.Billing.StripeCustomerID == "" {
  178. return errHTTPBadRequestNotAPaidUser
  179. }
  180. params := &stripe.BillingPortalSessionParams{
  181. Customer: stripe.String(v.user.Billing.StripeCustomerID),
  182. ReturnURL: stripe.String(s.config.BaseURL),
  183. }
  184. ps, err := portalsession.New(params)
  185. if err != nil {
  186. return err
  187. }
  188. response := &apiAccountBillingPortalRedirectResponse{
  189. RedirectURL: ps.URL,
  190. }
  191. w.Header().Set("Content-Type", "application/json")
  192. w.Header().Set("Access-Control-Allow-Origin", "*") // FIXME remove this
  193. if err := json.NewEncoder(w).Encode(response); err != nil {
  194. return err
  195. }
  196. return nil
  197. }
  198. func (s *Server) handleAccountBillingWebhook(w http.ResponseWriter, r *http.Request, v *visitor) error {
  199. // We don't have a v.user in this endpoint, only a userManager!
  200. stripeSignature := r.Header.Get("Stripe-Signature")
  201. if stripeSignature == "" {
  202. return errHTTPBadRequestInvalidStripeRequest
  203. }
  204. body, err := util.Peek(r.Body, stripeBodyBytesLimit)
  205. if err != nil {
  206. return err
  207. } else if body.LimitReached {
  208. return errHTTPEntityTooLargeJSONBody
  209. }
  210. event, err := webhook.ConstructEvent(body.PeekedBytes, stripeSignature, s.config.StripeWebhookKey)
  211. if err != nil {
  212. return errHTTPBadRequestInvalidStripeRequest
  213. } else if event.Data == nil || event.Data.Raw == nil {
  214. return errHTTPBadRequestInvalidStripeRequest
  215. }
  216. log.Info("Stripe: webhook event %s received", event.Type)
  217. stripeCustomerID := gjson.GetBytes(event.Data.Raw, "customer")
  218. if !stripeCustomerID.Exists() {
  219. return errHTTPBadRequestInvalidStripeRequest
  220. }
  221. switch event.Type {
  222. case "customer.subscription.updated":
  223. return s.handleAccountBillingWebhookSubscriptionUpdated(stripeCustomerID.String(), event.Data.Raw)
  224. case "customer.subscription.deleted":
  225. return s.handleAccountBillingWebhookSubscriptionDeleted(stripeCustomerID.String(), event.Data.Raw)
  226. default:
  227. return nil
  228. }
  229. }
  230. func (s *Server) handleAccountBillingWebhookSubscriptionUpdated(stripeCustomerID string, event json.RawMessage) error {
  231. status := gjson.GetBytes(event, "status")
  232. currentPeriodEnd := gjson.GetBytes(event, "current_period_end")
  233. priceID := gjson.GetBytes(event, "items.data.0.price.id")
  234. if !status.Exists() || !currentPeriodEnd.Exists() || !priceID.Exists() {
  235. return errHTTPBadRequestInvalidStripeRequest
  236. }
  237. log.Info("Stripe: customer %s: subscription updated to %s, with price %s", stripeCustomerID, status, priceID)
  238. u, err := s.userManager.UserByStripeCustomer(stripeCustomerID)
  239. if err != nil {
  240. return err
  241. }
  242. tier, err := s.userManager.TierByStripePrice(priceID.String())
  243. if err != nil {
  244. return err
  245. }
  246. if err := s.userManager.ChangeTier(u.Name, tier.Code); err != nil {
  247. return err
  248. }
  249. u.Billing.StripeSubscriptionStatus = stripe.SubscriptionStatus(status.String())
  250. u.Billing.StripeSubscriptionPaidUntil = time.Unix(currentPeriodEnd.Int(), 0)
  251. if err := s.userManager.ChangeBilling(u); err != nil {
  252. return err
  253. }
  254. return nil
  255. }
  256. func (s *Server) handleAccountBillingWebhookSubscriptionDeleted(stripeCustomerID string, event json.RawMessage) error {
  257. status := gjson.GetBytes(event, "status")
  258. if !status.Exists() {
  259. return errHTTPBadRequestInvalidStripeRequest
  260. }
  261. log.Info("Stripe: customer %s: subscription deleted, downgrading to unpaid tier", stripeCustomerID)
  262. u, err := s.userManager.UserByStripeCustomer(stripeCustomerID)
  263. if err != nil {
  264. return err
  265. }
  266. if err := s.userManager.ResetTier(u.Name); err != nil {
  267. return err
  268. }
  269. u.Billing.StripeSubscriptionID = ""
  270. u.Billing.StripeSubscriptionStatus = ""
  271. u.Billing.StripeSubscriptionPaidUntil = time.Unix(0, 0)
  272. if err := s.userManager.ChangeBilling(u); err != nil {
  273. return err
  274. }
  275. return nil
  276. }