server_payments.go 22 KB

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