server_payments.go 20 KB

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