server_payments.go 22 KB

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