stripe.go 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710
  1. package controller
  2. import (
  3. "context"
  4. "database/sql"
  5. "encoding/json"
  6. "errors"
  7. "fmt"
  8. "github.com/ente-io/museum/pkg/controller/commonbilling"
  9. "net/http"
  10. "strconv"
  11. "github.com/ente-io/museum/pkg/controller/discord"
  12. "github.com/ente-io/museum/pkg/controller/offer"
  13. "github.com/ente-io/museum/pkg/repo/storagebonus"
  14. "github.com/ente-io/museum/ente"
  15. emailCtrl "github.com/ente-io/museum/pkg/controller/email"
  16. "github.com/ente-io/museum/pkg/repo"
  17. "github.com/ente-io/museum/pkg/utils/billing"
  18. "github.com/ente-io/museum/pkg/utils/email"
  19. "github.com/ente-io/stacktrace"
  20. log "github.com/sirupsen/logrus"
  21. "github.com/spf13/viper"
  22. "github.com/stripe/stripe-go/v72"
  23. "github.com/stripe/stripe-go/v72/client"
  24. "github.com/stripe/stripe-go/v72/invoice"
  25. "github.com/stripe/stripe-go/v72/webhook"
  26. "golang.org/x/text/currency"
  27. )
  28. // StripeController provides abstractions for handling billing on Stripe
  29. type StripeController struct {
  30. StripeClients ente.StripeClientPerAccount
  31. BillingPlansPerAccount ente.BillingPlansPerAccount
  32. BillingRepo *repo.BillingRepository
  33. FileRepo *repo.FileRepository
  34. UserRepo *repo.UserRepository
  35. StorageBonusRepo *storagebonus.Repository
  36. DiscordController *discord.DiscordController
  37. EmailNotificationCtrl *emailCtrl.EmailNotificationController
  38. OfferController *offer.OfferController
  39. CommonBillCtrl *commonbilling.Controller
  40. }
  41. // A flag we set on Stripe subscriptions to indicate that we should skip on
  42. // sending out the email when the subscription has been cancelled.
  43. //
  44. // This is needed e.g. if this cancellation was as part of a user initiated
  45. // account deletion.
  46. const SkipMailKey = "skip_mail"
  47. // Return a new instance of StripeController
  48. func NewStripeController(plans ente.BillingPlansPerAccount, stripeClients ente.StripeClientPerAccount, billingRepo *repo.BillingRepository, fileRepo *repo.FileRepository, userRepo *repo.UserRepository, storageBonusRepo *storagebonus.Repository, discordController *discord.DiscordController, emailNotificationController *emailCtrl.EmailNotificationController, offerController *offer.OfferController, commonBillCtrl *commonbilling.Controller) *StripeController {
  49. return &StripeController{
  50. StripeClients: stripeClients,
  51. BillingRepo: billingRepo,
  52. FileRepo: fileRepo,
  53. UserRepo: userRepo,
  54. BillingPlansPerAccount: plans,
  55. StorageBonusRepo: storageBonusRepo,
  56. DiscordController: discordController,
  57. EmailNotificationCtrl: emailNotificationController,
  58. OfferController: offerController,
  59. CommonBillCtrl: commonBillCtrl,
  60. }
  61. }
  62. // GetCheckoutSession handles the creation of stripe checkout session for subscription purchase
  63. func (c *StripeController) GetCheckoutSession(productID string, userID int64, redirectRootURL string) (string, error) {
  64. if productID == "" {
  65. return "", stacktrace.Propagate(ente.ErrBadRequest, "")
  66. }
  67. subscription, err := c.BillingRepo.GetUserSubscription(userID)
  68. if err != nil {
  69. // error sql.ErrNoRows not possible as user must at least have a free subscription
  70. return "", stacktrace.Propagate(err, "")
  71. }
  72. hasActivePaidSubscription := billing.IsActivePaidPlan(subscription)
  73. hasStripeSubscription := subscription.PaymentProvider == ente.Stripe
  74. if hasActivePaidSubscription {
  75. if hasStripeSubscription {
  76. return "", stacktrace.Propagate(ente.ErrBadRequest, "")
  77. } else if !subscription.Attributes.IsCancelled {
  78. return "", stacktrace.Propagate(ente.ErrBadRequest, "")
  79. }
  80. }
  81. if subscription.PaymentProvider == ente.Stripe && !subscription.Attributes.IsCancelled {
  82. // user had bought a stripe subscription earlier,
  83. err := c.cancelExistingStripeSubscription(subscription, userID)
  84. if err != nil {
  85. return "", stacktrace.Propagate(err, "")
  86. }
  87. }
  88. stripeSuccessURL := redirectRootURL + viper.GetString("stripe.path.success")
  89. stripeCancelURL := redirectRootURL + viper.GetString("stripe.path.cancel")
  90. allowPromotionCodes := true
  91. params := &stripe.CheckoutSessionParams{
  92. ClientReferenceID: stripe.String(strconv.FormatInt(userID, 10)),
  93. SuccessURL: stripe.String(stripeSuccessURL),
  94. CancelURL: stripe.String(stripeCancelURL),
  95. Mode: stripe.String(string(stripe.CheckoutSessionModeSubscription)),
  96. LineItems: []*stripe.CheckoutSessionLineItemParams{
  97. {
  98. Price: stripe.String(productID),
  99. Quantity: stripe.Int64(1),
  100. },
  101. },
  102. AllowPromotionCodes: &allowPromotionCodes,
  103. }
  104. var stripeClient *client.API
  105. if subscription.PaymentProvider == ente.Stripe {
  106. stripeClient = c.StripeClients[subscription.Attributes.StripeAccountCountry]
  107. // attach the subscription to existing customerID
  108. params.Customer = stripe.String(subscription.Attributes.CustomerID)
  109. } else {
  110. stripeClient = c.StripeClients[ente.DefaultStripeAccountCountry]
  111. user, err := c.UserRepo.Get(userID)
  112. if err != nil {
  113. return "", stacktrace.Propagate(err, "")
  114. }
  115. // attach user's emailID to the checkout session and subsequent subscription bought
  116. params.CustomerEmail = stripe.String(user.Email)
  117. }
  118. s, err := stripeClient.CheckoutSessions.New(params)
  119. if err != nil {
  120. return "", stacktrace.Propagate(err, "")
  121. }
  122. return s.ID, nil
  123. }
  124. // GetVerifiedSubscription verifies and returns the verified subscription
  125. func (c *StripeController) GetVerifiedSubscription(userID int64, sessionID string) (ente.Subscription, error) {
  126. var stripeSubscription stripe.Subscription
  127. var err error
  128. if sessionID != "" {
  129. log.Info("Received session ID: " + sessionID)
  130. // Get verified subscription request was received from success redirect page
  131. stripeSubscription, err = c.getStripeSubscriptionFromSession(userID, sessionID)
  132. } else {
  133. log.Info("Did not receive a session ID")
  134. // Get verified subscription request for a subscription update
  135. stripeSubscription, err = c.getUserStripeSubscription(userID)
  136. }
  137. if err != nil {
  138. return ente.Subscription{}, stacktrace.Propagate(err, "")
  139. }
  140. log.Info("Received stripe subscription with ID: " + stripeSubscription.ID)
  141. subscription, err := c.getEnteSubscriptionFromStripeSubscription(userID, stripeSubscription)
  142. if err != nil {
  143. return ente.Subscription{}, stacktrace.Propagate(err, "")
  144. }
  145. log.Info("Returning ente subscription with ID: " + strconv.FormatInt(subscription.ID, 10))
  146. return subscription, nil
  147. }
  148. func (c *StripeController) HandleUSNotification(payload []byte, header string) error {
  149. event, err := webhook.ConstructEvent(payload, header, viper.GetString("stripe.us.webhook-secret"))
  150. if err != nil {
  151. return stacktrace.Propagate(err, "")
  152. }
  153. return c.handleWebhookEvent(event)
  154. }
  155. func (c *StripeController) HandleINNotification(payload []byte, header string) error {
  156. event, err := webhook.ConstructEvent(payload, header, viper.GetString("stripe.in.webhook-secret"))
  157. if err != nil {
  158. return stacktrace.Propagate(err, "")
  159. }
  160. return c.handleWebhookEvent(event)
  161. }
  162. func (c *StripeController) handleWebhookEvent(event stripe.Event) error {
  163. // The event body would already have been logged by the upper layers by the
  164. // time we get here, so we can only handle the events that we care about. In
  165. // case we receive an unexpected event, we do log an error though.
  166. handler := c.findHandlerForEvent(event)
  167. if handler == nil {
  168. log.Error("Received an unexpected webhook from stripe:", event.Type)
  169. return nil
  170. }
  171. eventLog, err := handler(event)
  172. if err != nil {
  173. return stacktrace.Propagate(err, "")
  174. }
  175. if eventLog.UserID == 0 {
  176. // Do not try to log if we do not have an associated user. This can
  177. // happen, e.g. with out of order webhooks.
  178. // Or in case of offer application, where events are logged by the Storage Bonus Repo
  179. //
  180. // See: Ignore webhooks received before user has been created
  181. return nil
  182. }
  183. err = c.BillingRepo.LogStripePush(eventLog)
  184. return stacktrace.Propagate(err, "")
  185. }
  186. func (c *StripeController) findHandlerForEvent(event stripe.Event) func(event stripe.Event) (ente.StripeEventLog, error) {
  187. switch event.Type {
  188. case "checkout.session.completed":
  189. return c.handleCheckoutSessionCompleted
  190. case "customer.subscription.deleted":
  191. return c.handleCustomerSubscriptionDeleted
  192. case "customer.subscription.updated":
  193. return c.handleCustomerSubscriptionUpdated
  194. case "invoice.paid":
  195. return c.handleInvoicePaid
  196. default:
  197. return nil
  198. }
  199. }
  200. // Payment is successful and the subscription is created.
  201. // You should provision the subscription.
  202. func (c *StripeController) handleCheckoutSessionCompleted(event stripe.Event) (ente.StripeEventLog, error) {
  203. var session stripe.CheckoutSession
  204. json.Unmarshal(event.Data.Raw, &session)
  205. if session.ClientReferenceID != "" { // via payments.ente.io, where we inserted the userID
  206. userID, _ := strconv.ParseInt(session.ClientReferenceID, 10, 64)
  207. newSubscription, err := c.GetVerifiedSubscription(userID, session.ID)
  208. if err != nil {
  209. return ente.StripeEventLog{}, stacktrace.Propagate(err, "")
  210. }
  211. stripeSubscription, err := c.getStripeSubscriptionFromSession(userID, session.ID)
  212. if err != nil {
  213. return ente.StripeEventLog{}, stacktrace.Propagate(err, "")
  214. }
  215. currentSubscription, err := c.BillingRepo.GetUserSubscription(userID)
  216. if err != nil {
  217. return ente.StripeEventLog{}, stacktrace.Propagate(err, "")
  218. }
  219. if currentSubscription.ExpiryTime >= newSubscription.ExpiryTime &&
  220. currentSubscription.ProductID != ente.FreePlanProductID {
  221. log.Warn("Webhook is reporting an outdated purchase that was already verified stripeSubscription:", stripeSubscription.ID)
  222. return ente.StripeEventLog{UserID: userID, StripeSubscription: stripeSubscription, Event: event}, nil
  223. }
  224. err = c.BillingRepo.ReplaceSubscription(
  225. currentSubscription.ID,
  226. newSubscription,
  227. )
  228. isUpgradingFromFreePlan := currentSubscription.ProductID == ente.FreePlanProductID
  229. if isUpgradingFromFreePlan {
  230. go func() {
  231. cur := currency.MustParseISO(string(session.Currency))
  232. amount := fmt.Sprintf("%v%v", currency.Symbol(cur), float64(session.AmountTotal)/float64(100))
  233. c.DiscordController.NotifyNewSub(userID, "stripe", amount)
  234. }()
  235. go func() {
  236. c.EmailNotificationCtrl.OnAccountUpgrade(userID)
  237. }()
  238. }
  239. if err != nil {
  240. return ente.StripeEventLog{}, stacktrace.Propagate(err, "")
  241. }
  242. return ente.StripeEventLog{UserID: userID, StripeSubscription: stripeSubscription, Event: event}, nil
  243. } else {
  244. priceID, err := c.getPriceIDFromSession(session.ID)
  245. if err != nil {
  246. return ente.StripeEventLog{}, stacktrace.Propagate(err, "")
  247. }
  248. email := session.CustomerDetails.Email
  249. err = c.OfferController.ApplyOffer(email, priceID)
  250. if err != nil {
  251. return ente.StripeEventLog{}, stacktrace.Propagate(err, "")
  252. }
  253. }
  254. return ente.StripeEventLog{}, nil
  255. }
  256. // Occurs whenever a customer's subscription ends.
  257. func (c *StripeController) handleCustomerSubscriptionDeleted(event stripe.Event) (ente.StripeEventLog, error) {
  258. var stripeSubscription stripe.Subscription
  259. json.Unmarshal(event.Data.Raw, &stripeSubscription)
  260. currentSubscription, err := c.BillingRepo.GetSubscriptionForTransaction(stripeSubscription.ID, ente.Stripe)
  261. if err != nil {
  262. // Ignore webhooks received before user has been created
  263. //
  264. // This would happen when we get webhook events out of order, e.g. we
  265. // get a "customer.subscription.updated" before
  266. // "checkout.session.completed", and the customer has not yet been
  267. // created in our database.
  268. if errors.Is(err, sql.ErrNoRows) {
  269. log.Warn("Webhook is reporting an event for un-verified subscription stripeSubscriptionID:", stripeSubscription.ID)
  270. return ente.StripeEventLog{}, nil
  271. }
  272. return ente.StripeEventLog{}, stacktrace.Propagate(err, "")
  273. }
  274. userID := currentSubscription.UserID
  275. user, err := c.UserRepo.Get(userID)
  276. if err != nil {
  277. if errors.Is(err, ente.ErrUserDeleted) {
  278. // no-op user has already been deleted
  279. return ente.StripeEventLog{UserID: userID, StripeSubscription: stripeSubscription, Event: event}, nil
  280. }
  281. return ente.StripeEventLog{}, stacktrace.Propagate(err, "")
  282. }
  283. err = c.BillingRepo.UpdateSubscriptionCancellationStatus(userID, true)
  284. if err != nil {
  285. return ente.StripeEventLog{}, stacktrace.Propagate(err, "")
  286. }
  287. skipMail := stripeSubscription.Metadata[SkipMailKey]
  288. // Send a cancellation notification email for folks who are either on
  289. // individual plan or admin of a family plan.
  290. if skipMail != "true" &&
  291. (user.FamilyAdminID == nil || *user.FamilyAdminID == userID) {
  292. storage, surpErr := c.StorageBonusRepo.GetPaidAddonSurplusStorage(context.Background(), userID)
  293. if surpErr != nil {
  294. return ente.StripeEventLog{}, stacktrace.Propagate(surpErr, "")
  295. }
  296. if storage == nil || *storage <= 0 {
  297. err = email.SendTemplatedEmail([]string{user.Email}, "ente", "support@ente.io",
  298. ente.SubscriptionEndedEmailSubject, ente.SubscriptionEndedEmailTemplate,
  299. map[string]interface{}{}, nil)
  300. if err != nil {
  301. return ente.StripeEventLog{}, stacktrace.Propagate(err, "")
  302. }
  303. } else {
  304. log.WithField("storage", storage).Info("User has surplus storage, not sending email")
  305. }
  306. }
  307. // TODO: Add cron to delete files of users with expired subscriptions
  308. return ente.StripeEventLog{UserID: userID, StripeSubscription: stripeSubscription, Event: event}, nil
  309. }
  310. // Occurs whenever a subscription changes (e.g., switching from one plan to
  311. // another, or changing the status from trial to active).
  312. func (c *StripeController) handleCustomerSubscriptionUpdated(event stripe.Event) (ente.StripeEventLog, error) {
  313. var stripeSubscription stripe.Subscription
  314. json.Unmarshal(event.Data.Raw, &stripeSubscription)
  315. currentSubscription, err := c.BillingRepo.GetSubscriptionForTransaction(stripeSubscription.ID, ente.Stripe)
  316. if err != nil {
  317. if errors.Is(err, sql.ErrNoRows) {
  318. // See: Ignore webhooks received before user has been created
  319. log.Warn("Webhook is reporting an event for un-verified subscription stripeSubscriptionID:", stripeSubscription.ID)
  320. return ente.StripeEventLog{}, nil
  321. }
  322. return ente.StripeEventLog{}, stacktrace.Propagate(err, "")
  323. }
  324. userID := currentSubscription.UserID
  325. switch stripeSubscription.Status {
  326. case stripe.SubscriptionStatusPastDue:
  327. user, err := c.UserRepo.Get(userID)
  328. if err != nil {
  329. return ente.StripeEventLog{}, stacktrace.Propagate(err, "")
  330. }
  331. err = email.SendTemplatedEmail([]string{user.Email}, "ente", "support@ente.io",
  332. ente.AccountOnHoldEmailSubject, ente.OnHoldTemplate, map[string]interface{}{
  333. "PaymentProvider": "Stripe",
  334. }, nil)
  335. if err != nil {
  336. return ente.StripeEventLog{}, stacktrace.Propagate(err, "")
  337. }
  338. case stripe.SubscriptionStatusActive:
  339. newSubscription, err := c.getEnteSubscriptionFromStripeSubscription(userID, stripeSubscription)
  340. if err != nil {
  341. return ente.StripeEventLog{}, stacktrace.Propagate(err, "")
  342. }
  343. if currentSubscription.ProductID == newSubscription.ProductID {
  344. // Webhook is reporting an outdated update that was already verified
  345. // no-op
  346. log.Warn("Webhook is reporting an outdated purchase that was already verified stripeSubscriptionID:", stripeSubscription.ID)
  347. return ente.StripeEventLog{UserID: userID, StripeSubscription: stripeSubscription, Event: event}, nil
  348. }
  349. if newSubscription.ProductID != currentSubscription.ProductID {
  350. c.BillingRepo.ReplaceSubscription(currentSubscription.ID, newSubscription)
  351. }
  352. }
  353. return ente.StripeEventLog{UserID: userID, StripeSubscription: stripeSubscription, Event: event}, nil
  354. }
  355. // Continue to provision the subscription as payments continue to be made.
  356. func (c *StripeController) handleInvoicePaid(event stripe.Event) (ente.StripeEventLog, error) {
  357. var invoice stripe.Invoice
  358. json.Unmarshal(event.Data.Raw, &invoice)
  359. stripeSubscriptionID := invoice.Subscription.ID
  360. currentSubscription, err := c.BillingRepo.GetSubscriptionForTransaction(stripeSubscriptionID, ente.Stripe)
  361. if err != nil {
  362. if errors.Is(err, sql.ErrNoRows) {
  363. // See: Ignore webhooks received before user has been created
  364. log.Warn("Webhook is reporting an event for un-verified subscription stripeSubscriptionID:", stripeSubscriptionID)
  365. return ente.StripeEventLog{}, nil
  366. }
  367. return ente.StripeEventLog{}, stacktrace.Propagate(err, "")
  368. }
  369. userID := currentSubscription.UserID
  370. client := c.StripeClients[currentSubscription.Attributes.StripeAccountCountry]
  371. stripeSubscription, err := client.Subscriptions.Get(stripeSubscriptionID, nil)
  372. if err != nil {
  373. return ente.StripeEventLog{}, stacktrace.Propagate(err, "")
  374. }
  375. newExpiryTime := stripeSubscription.CurrentPeriodEnd * 1000 * 1000
  376. if currentSubscription.ExpiryTime == newExpiryTime {
  377. //outdated invoice
  378. log.Warn("Webhook is reporting an outdated purchase that was already verified stripeSubscriptionID:", stripeSubscription.ID)
  379. return ente.StripeEventLog{UserID: userID, StripeSubscription: *stripeSubscription, Event: event}, nil
  380. }
  381. err = c.BillingRepo.UpdateSubscriptionExpiryTime(
  382. currentSubscription.ID, newExpiryTime)
  383. if err != nil {
  384. return ente.StripeEventLog{}, stacktrace.Propagate(err, "")
  385. }
  386. return ente.StripeEventLog{UserID: userID, StripeSubscription: *stripeSubscription, Event: event}, nil
  387. }
  388. func (c *StripeController) UpdateSubscription(stripeID string, userID int64) (ente.SubscriptionUpdateResponse, error) {
  389. subscription, err := c.BillingRepo.GetUserSubscription(userID)
  390. if err != nil {
  391. return ente.SubscriptionUpdateResponse{}, stacktrace.Propagate(err, "")
  392. }
  393. newPlan, newStripeAccountCountry, err := c.getPlanAndAccount(stripeID)
  394. if err != nil {
  395. return ente.SubscriptionUpdateResponse{}, stacktrace.Propagate(err, "")
  396. }
  397. if subscription.PaymentProvider != ente.Stripe || subscription.ProductID == stripeID || subscription.Attributes.StripeAccountCountry != newStripeAccountCountry {
  398. return ente.SubscriptionUpdateResponse{}, stacktrace.Propagate(ente.ErrBadRequest, "")
  399. }
  400. if newPlan.Storage < subscription.Storage { // Downgrade
  401. canDowngrade, canDowngradeErr := c.CommonBillCtrl.CanDowngradeToGivenStorage(newPlan.Storage, userID)
  402. if canDowngradeErr != nil {
  403. return ente.SubscriptionUpdateResponse{}, stacktrace.Propagate(canDowngradeErr, "")
  404. }
  405. if !canDowngrade {
  406. return ente.SubscriptionUpdateResponse{}, stacktrace.Propagate(ente.ErrCannotDowngrade, "")
  407. }
  408. log.Info("Usage is good")
  409. }
  410. client := c.StripeClients[subscription.Attributes.StripeAccountCountry]
  411. stripeSubscription, err := client.Subscriptions.Get(subscription.OriginalTransactionID, nil)
  412. if err != nil {
  413. return ente.SubscriptionUpdateResponse{}, stacktrace.Propagate(err, "")
  414. }
  415. params := stripe.SubscriptionParams{
  416. ProrationBehavior: stripe.String(string(stripe.SubscriptionProrationBehaviorAlwaysInvoice)),
  417. Items: []*stripe.SubscriptionItemsParams{
  418. {
  419. ID: stripe.String(stripeSubscription.Items.Data[0].ID),
  420. Price: stripe.String(stripeID),
  421. },
  422. },
  423. PaymentBehavior: stripe.String(string(stripe.SubscriptionPaymentBehaviorPendingIfIncomplete)),
  424. }
  425. params.AddExpand("latest_invoice.payment_intent")
  426. newStripeSubscription, err := client.Subscriptions.Update(subscription.OriginalTransactionID, &params)
  427. if err != nil {
  428. stripeError := err.(*stripe.Error)
  429. switch stripeError.Type {
  430. case stripe.ErrorTypeCard:
  431. return ente.SubscriptionUpdateResponse{Status: "requires_payment_method"}, nil
  432. default:
  433. return ente.SubscriptionUpdateResponse{}, stacktrace.Propagate(err, "")
  434. }
  435. }
  436. if newStripeSubscription.PendingUpdate != nil {
  437. switch newStripeSubscription.LatestInvoice.PaymentIntent.Status {
  438. case stripe.PaymentIntentStatusRequiresAction:
  439. return ente.SubscriptionUpdateResponse{Status: "requires_action", ClientSecret: newStripeSubscription.LatestInvoice.PaymentIntent.ClientSecret}, nil
  440. case stripe.PaymentIntentStatusRequiresPaymentMethod:
  441. inv := newStripeSubscription.LatestInvoice
  442. invoice.VoidInvoice(inv.ID, nil)
  443. return ente.SubscriptionUpdateResponse{Status: "requires_payment_method"}, nil
  444. }
  445. return ente.SubscriptionUpdateResponse{}, stacktrace.Propagate(ente.ErrBadRequest, "")
  446. }
  447. return ente.SubscriptionUpdateResponse{Status: "success"}, nil
  448. }
  449. func (c *StripeController) UpdateSubscriptionCancellationStatus(userID int64, status bool) (ente.Subscription, error) {
  450. subscription, err := c.BillingRepo.GetUserSubscription(userID)
  451. if err != nil {
  452. // error sql.ErrNoRows not possible as user must at least have a free subscription
  453. return ente.Subscription{}, stacktrace.Propagate(err, "")
  454. }
  455. if subscription.PaymentProvider != ente.Stripe {
  456. return ente.Subscription{}, stacktrace.Propagate(ente.ErrBadRequest, "")
  457. }
  458. if subscription.Attributes.IsCancelled == status {
  459. // no-op
  460. return subscription, nil
  461. }
  462. client := c.StripeClients[subscription.Attributes.StripeAccountCountry]
  463. params := &stripe.SubscriptionParams{
  464. CancelAtPeriodEnd: stripe.Bool(status),
  465. }
  466. _, err = client.Subscriptions.Update(subscription.OriginalTransactionID, params)
  467. if err != nil {
  468. return ente.Subscription{}, stacktrace.Propagate(err, "")
  469. }
  470. err = c.BillingRepo.UpdateSubscriptionCancellationStatus(userID, status)
  471. if err != nil {
  472. return ente.Subscription{}, stacktrace.Propagate(err, "")
  473. }
  474. subscription.Attributes.IsCancelled = status
  475. return subscription, nil
  476. }
  477. func (c *StripeController) GetStripeCustomerPortal(userID int64, redirectRootURL string) (string, error) {
  478. subscription, err := c.BillingRepo.GetUserSubscription(userID)
  479. if err != nil {
  480. return "", stacktrace.Propagate(err, "")
  481. }
  482. if subscription.PaymentProvider != ente.Stripe {
  483. return "", stacktrace.Propagate(ente.ErrBadRequest, "")
  484. }
  485. client := c.StripeClients[subscription.Attributes.StripeAccountCountry]
  486. params := &stripe.BillingPortalSessionParams{
  487. Customer: stripe.String(subscription.Attributes.CustomerID),
  488. ReturnURL: stripe.String(redirectRootURL),
  489. }
  490. ps, err := client.BillingPortalSessions.New(params)
  491. if err != nil {
  492. return "", stacktrace.Propagate(err, "")
  493. }
  494. return ps.URL, nil
  495. }
  496. func (c *StripeController) getStripeSubscriptionFromSession(userID int64, checkoutSessionID string) (stripe.Subscription, error) {
  497. subscription, err := c.BillingRepo.GetUserSubscription(userID)
  498. if err != nil {
  499. return stripe.Subscription{}, stacktrace.Propagate(err, "")
  500. }
  501. var stripeClient *client.API
  502. if subscription.PaymentProvider == ente.Stripe {
  503. stripeClient = c.StripeClients[subscription.Attributes.StripeAccountCountry]
  504. } else {
  505. stripeClient = c.StripeClients[ente.DefaultStripeAccountCountry]
  506. }
  507. params := &stripe.CheckoutSessionParams{}
  508. params.AddExpand("subscription")
  509. checkoutSession, err := stripeClient.CheckoutSessions.Get(checkoutSessionID, params)
  510. if err != nil {
  511. return stripe.Subscription{}, stacktrace.Propagate(err, "")
  512. }
  513. if (*checkoutSession.Subscription).Status != stripe.SubscriptionStatusActive {
  514. return stripe.Subscription{}, stacktrace.Propagate(&stripe.InvalidRequestError{}, "")
  515. }
  516. return *checkoutSession.Subscription, nil
  517. }
  518. func (c *StripeController) getPriceIDFromSession(sessionID string) (string, error) {
  519. stripeClient := c.StripeClients[ente.DefaultStripeAccountCountry]
  520. params := &stripe.CheckoutSessionListLineItemsParams{}
  521. params.AddExpand("data.price")
  522. items := stripeClient.CheckoutSessions.ListLineItems(sessionID, params)
  523. for items.Next() { // Return the first PriceID that has been fetched
  524. return items.LineItem().Price.ID, nil
  525. }
  526. return "", stacktrace.Propagate(ente.ErrNotFound, "")
  527. }
  528. func (c *StripeController) getUserStripeSubscription(userID int64) (stripe.Subscription, error) {
  529. subscription, err := c.BillingRepo.GetUserSubscription(userID)
  530. if err != nil {
  531. return stripe.Subscription{}, stacktrace.Propagate(err, "")
  532. }
  533. if subscription.PaymentProvider != ente.Stripe {
  534. return stripe.Subscription{}, stacktrace.Propagate(ente.ErrCannotSwitchPaymentProvider, "")
  535. }
  536. client := c.StripeClients[subscription.Attributes.StripeAccountCountry]
  537. stripeSubscription, err := client.Subscriptions.Get(subscription.OriginalTransactionID, nil)
  538. if err != nil {
  539. return stripe.Subscription{}, stacktrace.Propagate(err, "")
  540. }
  541. return *stripeSubscription, nil
  542. }
  543. func (c *StripeController) getPlanAndAccount(stripeID string) (ente.BillingPlan, ente.StripeAccountCountry, error) {
  544. for stripeAccountCountry, billingPlansCountryWise := range c.BillingPlansPerAccount {
  545. for _, plans := range billingPlansCountryWise {
  546. for _, plan := range plans {
  547. if plan.StripeID == stripeID {
  548. return plan, stripeAccountCountry, nil
  549. }
  550. }
  551. }
  552. }
  553. return ente.BillingPlan{}, "", stacktrace.Propagate(ente.ErrNotFound, "")
  554. }
  555. func (c *StripeController) getEnteSubscriptionFromStripeSubscription(userID int64, stripeSubscription stripe.Subscription) (ente.Subscription, error) {
  556. productID := stripeSubscription.Items.Data[0].Price.ID
  557. plan, stripeAccountCountry, err := c.getPlanAndAccount(productID)
  558. if err != nil {
  559. return ente.Subscription{}, stacktrace.Propagate(err, "")
  560. }
  561. s := ente.Subscription{
  562. UserID: userID,
  563. PaymentProvider: ente.Stripe,
  564. ProductID: productID,
  565. Storage: plan.Storage,
  566. Attributes: ente.SubscriptionAttributes{CustomerID: stripeSubscription.Customer.ID, IsCancelled: false, StripeAccountCountry: stripeAccountCountry},
  567. OriginalTransactionID: stripeSubscription.ID,
  568. ExpiryTime: stripeSubscription.CurrentPeriodEnd * 1000 * 1000,
  569. }
  570. return s, nil
  571. }
  572. func (c *StripeController) UpdateBillingEmail(subscription ente.Subscription, newEmail string) error {
  573. params := &stripe.CustomerParams{Email: &newEmail}
  574. client := c.StripeClients[subscription.Attributes.StripeAccountCountry]
  575. _, err := client.Customers.Update(
  576. subscription.Attributes.CustomerID,
  577. params,
  578. )
  579. if err != nil {
  580. return stacktrace.Propagate(err, "failed to update stripe customer emailID")
  581. }
  582. return nil
  583. }
  584. func (c *StripeController) CancelSubAndDeleteCustomer(subscription ente.Subscription, logger *log.Entry) error {
  585. client := c.StripeClients[subscription.Attributes.StripeAccountCountry]
  586. if !subscription.Attributes.IsCancelled {
  587. prorateRefund := true
  588. logger.Info("cancelling sub with prorated refund")
  589. updateParams := &stripe.SubscriptionParams{}
  590. updateParams.AddMetadata(SkipMailKey, "true")
  591. _, err := client.Subscriptions.Update(subscription.OriginalTransactionID, updateParams)
  592. if err != nil {
  593. stripeError := err.(*stripe.Error)
  594. errorMsg := fmt.Sprintf("subscription updation failed during account deletion: %s, %s", stripeError.Msg, stripeError.Code)
  595. log.Error(errorMsg)
  596. c.DiscordController.Notify(errorMsg)
  597. if stripeError.HTTPStatusCode == http.StatusNotFound {
  598. log.Error("Ignoring error since an active subscription could not be found")
  599. return nil
  600. } else if stripeError.HTTPStatusCode == http.StatusBadRequest {
  601. log.Error("Bad request while trying to delete account")
  602. return nil
  603. }
  604. return stacktrace.Propagate(err, "")
  605. }
  606. _, err = client.Subscriptions.Cancel(subscription.OriginalTransactionID, &stripe.SubscriptionCancelParams{
  607. Prorate: &prorateRefund,
  608. })
  609. if err != nil {
  610. stripeError := err.(*stripe.Error)
  611. logger.Error(fmt.Sprintf("subscription cancel failed msg= %s for userID=%d"+stripeError.Msg, subscription.UserID))
  612. // ignore if subscription doesn't exist, already deleted
  613. if stripeError.HTTPStatusCode != 404 {
  614. return stacktrace.Propagate(err, "")
  615. }
  616. }
  617. err = c.BillingRepo.UpdateSubscriptionCancellationStatus(subscription.UserID, true)
  618. if err != nil {
  619. return stacktrace.Propagate(err, "")
  620. }
  621. }
  622. logger.Info("deleting customer from stripe")
  623. _, err := client.Customers.Del(
  624. subscription.Attributes.CustomerID,
  625. &stripe.CustomerParams{},
  626. )
  627. if err != nil {
  628. stripeError := err.(*stripe.Error)
  629. switch stripeError.Type {
  630. case stripe.ErrorTypeInvalidRequest:
  631. if stripe.ErrorCodeResourceMissing == stripeError.Code {
  632. return nil
  633. }
  634. return stacktrace.Propagate(err, fmt.Sprintf("failed to delete customer %s", subscription.Attributes.CustomerID))
  635. default:
  636. return stacktrace.Propagate(err, fmt.Sprintf("failed to delete customer %s", subscription.Attributes.CustomerID))
  637. }
  638. }
  639. return nil
  640. }
  641. // cancel the earlier past_due subscription
  642. // and add skip mail metadata entry to avoid sending account deletion mail while re-subscription
  643. func (c *StripeController) cancelExistingStripeSubscription(subscription ente.Subscription, userID int64) error {
  644. updateParams := &stripe.SubscriptionParams{}
  645. updateParams.AddMetadata(SkipMailKey, "true")
  646. client := c.StripeClients[subscription.Attributes.StripeAccountCountry]
  647. _, err := client.Subscriptions.Update(subscription.OriginalTransactionID, updateParams)
  648. if err != nil {
  649. stripeError := err.(*stripe.Error)
  650. log.Warn(fmt.Sprintf("subscription updation failed msg= %s for userID=%d", stripeError.Msg, userID))
  651. // ignore if subscription doesn't exist, already deleted
  652. if stripeError.HTTPStatusCode != 404 {
  653. return stacktrace.Propagate(err, "")
  654. }
  655. } else {
  656. _, err = client.Subscriptions.Cancel(subscription.OriginalTransactionID, nil)
  657. if err != nil {
  658. stripeError := err.(*stripe.Error)
  659. log.Warn(fmt.Sprintf("subscription cancel failed msg= %s for userID=%d", stripeError.Msg, userID))
  660. // ignore if subscription doesn't exist, already deleted
  661. if stripeError.HTTPStatusCode != 404 {
  662. return stacktrace.Propagate(err, "")
  663. }
  664. }
  665. err = c.BillingRepo.UpdateSubscriptionCancellationStatus(userID, true)
  666. if err != nil {
  667. return stacktrace.Propagate(err, "")
  668. }
  669. }
  670. return nil
  671. }