server_payments.go 20 KB

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