server_payments.go 22 KB

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