stripe.go 33 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800
  1. package controller
  2. import (
  3. "context"
  4. "database/sql"
  5. "encoding/json"
  6. "errors"
  7. "fmt"
  8. "net/http"
  9. "strconv"
  10. "time"
  11. "github.com/ente-io/museum/pkg/controller/commonbilling"
  12. "github.com/ente-io/museum/pkg/controller/discord"
  13. "github.com/ente-io/museum/pkg/controller/offer"
  14. "github.com/ente-io/museum/pkg/repo/storagebonus"
  15. "github.com/ente-io/museum/ente"
  16. emailCtrl "github.com/ente-io/museum/pkg/controller/email"
  17. "github.com/ente-io/museum/pkg/repo"
  18. "github.com/ente-io/museum/pkg/utils/billing"
  19. "github.com/ente-io/museum/pkg/utils/email"
  20. "github.com/ente-io/stacktrace"
  21. log "github.com/sirupsen/logrus"
  22. "github.com/spf13/viper"
  23. "github.com/stripe/stripe-go/v72"
  24. "github.com/stripe/stripe-go/v72/client"
  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, ente.StripeUS)
  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, ente.StripeIN)
  161. }
  162. func (c *StripeController) handleWebhookEvent(event stripe.Event, country ente.StripeAccountCountry) 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, country)
  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, country ente.StripeAccountCountry) (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. case "payment_intent.payment_failed":
  197. return c.handlePaymentIntentFailed
  198. default:
  199. return nil
  200. }
  201. }
  202. // Payment is successful and the subscription is created.
  203. // You should provision the subscription.
  204. func (c *StripeController) handleCheckoutSessionCompleted(event stripe.Event, country ente.StripeAccountCountry) (ente.StripeEventLog, error) {
  205. var session stripe.CheckoutSession
  206. json.Unmarshal(event.Data.Raw, &session)
  207. if session.ClientReferenceID != "" { // via payments.ente.io, where we inserted the userID
  208. userID, _ := strconv.ParseInt(session.ClientReferenceID, 10, 64)
  209. newSubscription, err := c.GetVerifiedSubscription(userID, session.ID)
  210. if err != nil {
  211. return ente.StripeEventLog{}, stacktrace.Propagate(err, "")
  212. }
  213. stripeSubscription, err := c.getStripeSubscriptionFromSession(userID, session.ID)
  214. if err != nil {
  215. return ente.StripeEventLog{}, stacktrace.Propagate(err, "")
  216. }
  217. currentSubscription, err := c.BillingRepo.GetUserSubscription(userID)
  218. if err != nil {
  219. return ente.StripeEventLog{}, stacktrace.Propagate(err, "")
  220. }
  221. if currentSubscription.ExpiryTime >= newSubscription.ExpiryTime &&
  222. currentSubscription.ProductID != ente.FreePlanProductID {
  223. log.Warn("Webhook is reporting an outdated purchase that was already verified stripeSubscription:", stripeSubscription.ID)
  224. return ente.StripeEventLog{UserID: userID, StripeSubscription: stripeSubscription, Event: event}, nil
  225. }
  226. err = c.BillingRepo.ReplaceSubscription(
  227. currentSubscription.ID,
  228. newSubscription,
  229. )
  230. isUpgradingFromFreePlan := currentSubscription.ProductID == ente.FreePlanProductID
  231. if isUpgradingFromFreePlan {
  232. go func() {
  233. cur := currency.MustParseISO(string(session.Currency))
  234. amount := fmt.Sprintf("%v%v", currency.Symbol(cur), float64(session.AmountTotal)/float64(100))
  235. c.DiscordController.NotifyNewSub(userID, "stripe", amount)
  236. }()
  237. go func() {
  238. c.EmailNotificationCtrl.OnAccountUpgrade(userID)
  239. }()
  240. }
  241. if err != nil {
  242. return ente.StripeEventLog{}, stacktrace.Propagate(err, "")
  243. }
  244. return ente.StripeEventLog{UserID: userID, StripeSubscription: stripeSubscription, Event: event}, nil
  245. } else {
  246. priceID, err := c.getPriceIDFromSession(session.ID)
  247. if err != nil {
  248. return ente.StripeEventLog{}, stacktrace.Propagate(err, "")
  249. }
  250. email := session.CustomerDetails.Email
  251. err = c.OfferController.ApplyOffer(email, priceID)
  252. if err != nil {
  253. return ente.StripeEventLog{}, stacktrace.Propagate(err, "")
  254. }
  255. }
  256. return ente.StripeEventLog{}, nil
  257. }
  258. // Occurs whenever a customer's subscription ends.
  259. func (c *StripeController) handleCustomerSubscriptionDeleted(event stripe.Event, country ente.StripeAccountCountry) (ente.StripeEventLog, error) {
  260. var stripeSubscription stripe.Subscription
  261. json.Unmarshal(event.Data.Raw, &stripeSubscription)
  262. currentSubscription, err := c.BillingRepo.GetSubscriptionForTransaction(stripeSubscription.ID, ente.Stripe)
  263. if err != nil {
  264. // Ignore webhooks received before user has been created
  265. //
  266. // This would happen when we get webhook events out of order, e.g. we
  267. // get a "customer.subscription.updated" before
  268. // "checkout.session.completed", and the customer has not yet been
  269. // created in our database.
  270. if errors.Is(err, sql.ErrNoRows) {
  271. log.Warn("Webhook is reporting an event for un-verified subscription stripeSubscriptionID:", stripeSubscription.ID)
  272. return ente.StripeEventLog{}, nil
  273. }
  274. return ente.StripeEventLog{}, stacktrace.Propagate(err, "")
  275. }
  276. userID := currentSubscription.UserID
  277. user, err := c.UserRepo.Get(userID)
  278. if err != nil {
  279. if errors.Is(err, ente.ErrUserDeleted) {
  280. // no-op user has already been deleted
  281. return ente.StripeEventLog{UserID: userID, StripeSubscription: stripeSubscription, Event: event}, nil
  282. }
  283. return ente.StripeEventLog{}, stacktrace.Propagate(err, "")
  284. }
  285. err = c.BillingRepo.UpdateSubscriptionCancellationStatus(userID, true)
  286. if err != nil {
  287. return ente.StripeEventLog{}, stacktrace.Propagate(err, "")
  288. }
  289. skipMail := stripeSubscription.Metadata[SkipMailKey]
  290. // Send a cancellation notification email for folks who are either on
  291. // individual plan or admin of a family plan.
  292. if skipMail != "true" &&
  293. (user.FamilyAdminID == nil || *user.FamilyAdminID == userID) {
  294. storage, surpErr := c.StorageBonusRepo.GetPaidAddonSurplusStorage(context.Background(), userID)
  295. if surpErr != nil {
  296. return ente.StripeEventLog{}, stacktrace.Propagate(surpErr, "")
  297. }
  298. if storage == nil || *storage <= 0 {
  299. err = email.SendTemplatedEmail([]string{user.Email}, "ente", "support@ente.io",
  300. ente.SubscriptionEndedEmailSubject, ente.SubscriptionEndedEmailTemplate,
  301. map[string]interface{}{}, nil)
  302. if err != nil {
  303. return ente.StripeEventLog{}, stacktrace.Propagate(err, "")
  304. }
  305. } else {
  306. log.WithField("storage", storage).Info("User has surplus storage, not sending email")
  307. }
  308. }
  309. // TODO: Add cron to delete files of users with expired subscriptions
  310. return ente.StripeEventLog{UserID: userID, StripeSubscription: stripeSubscription, Event: event}, nil
  311. }
  312. // Stripe fires this when a subscription starts or changes. For example,
  313. // renewing a subscription, adding a coupon, applying a discount, adding an
  314. // invoice item, and changing plans all trigger this event. In our case, we use
  315. // this only to track plan changes or subscriptions going past due. The rest
  316. // (subscription creations, deletions, renewals and failures) are tracked by
  317. // individual events.
  318. func (c *StripeController) handleCustomerSubscriptionUpdated(event stripe.Event, country ente.StripeAccountCountry) (ente.StripeEventLog, error) {
  319. var stripeSubscription stripe.Subscription
  320. json.Unmarshal(event.Data.Raw, &stripeSubscription)
  321. currentSubscription, err := c.BillingRepo.GetSubscriptionForTransaction(stripeSubscription.ID, ente.Stripe)
  322. if err != nil {
  323. if errors.Is(err, sql.ErrNoRows) {
  324. // See: Ignore webhooks received before user has been created
  325. log.Warn("Webhook is reporting an event for un-verified subscription stripeSubscriptionID:", stripeSubscription.ID)
  326. return ente.StripeEventLog{}, nil
  327. }
  328. return ente.StripeEventLog{}, stacktrace.Propagate(err, "")
  329. }
  330. userID := currentSubscription.UserID
  331. newSubscription, err := c.getEnteSubscriptionFromStripeSubscription(userID, stripeSubscription)
  332. if err != nil {
  333. return ente.StripeEventLog{}, stacktrace.Propagate(err, "")
  334. }
  335. if stripeSubscription.Status == stripe.SubscriptionStatusPastDue {
  336. user, err := c.UserRepo.Get(userID)
  337. if err != nil {
  338. return ente.StripeEventLog{}, stacktrace.Propagate(err, "")
  339. }
  340. err = email.SendTemplatedEmail([]string{user.Email}, "ente", "support@ente.io",
  341. ente.AccountOnHoldEmailSubject, ente.OnHoldTemplate, map[string]interface{}{
  342. "PaymentProvider": "Stripe",
  343. }, nil)
  344. if err != nil {
  345. return ente.StripeEventLog{}, stacktrace.Propagate(err, "")
  346. }
  347. }
  348. // If the customer has changed the plan, we update state in the database. If
  349. // the plan has not changed, we will ignore this webhook and rely on other
  350. // events to update the state
  351. if currentSubscription.ProductID != newSubscription.ProductID {
  352. c.BillingRepo.ReplaceSubscription(currentSubscription.ID, newSubscription)
  353. }
  354. return ente.StripeEventLog{UserID: userID, StripeSubscription: stripeSubscription, Event: event}, nil
  355. }
  356. // Continue to provision the subscription as payments continue to be made.
  357. func (c *StripeController) handleInvoicePaid(event stripe.Event, country ente.StripeAccountCountry) (ente.StripeEventLog, error) {
  358. var invoice stripe.Invoice
  359. json.Unmarshal(event.Data.Raw, &invoice)
  360. stripeSubscriptionID := invoice.Subscription.ID
  361. currentSubscription, err := c.BillingRepo.GetSubscriptionForTransaction(stripeSubscriptionID, ente.Stripe)
  362. if err != nil {
  363. if errors.Is(err, sql.ErrNoRows) {
  364. // See: Ignore webhooks received before user has been created
  365. log.Warn("Webhook is reporting an event for un-verified subscription stripeSubscriptionID:", stripeSubscriptionID)
  366. return ente.StripeEventLog{}, nil
  367. }
  368. return ente.StripeEventLog{}, stacktrace.Propagate(err, "")
  369. }
  370. userID := currentSubscription.UserID
  371. client := c.StripeClients[currentSubscription.Attributes.StripeAccountCountry]
  372. stripeSubscription, err := client.Subscriptions.Get(stripeSubscriptionID, nil)
  373. if err != nil {
  374. return ente.StripeEventLog{}, stacktrace.Propagate(err, "")
  375. }
  376. newExpiryTime := stripeSubscription.CurrentPeriodEnd * 1000 * 1000
  377. if currentSubscription.ExpiryTime == newExpiryTime {
  378. //outdated invoice
  379. log.Warn("Webhook is reporting an outdated purchase that was already verified stripeSubscriptionID:", stripeSubscription.ID)
  380. return ente.StripeEventLog{UserID: userID, StripeSubscription: *stripeSubscription, Event: event}, nil
  381. }
  382. err = c.BillingRepo.UpdateSubscriptionExpiryTime(
  383. currentSubscription.ID, newExpiryTime)
  384. if err != nil {
  385. return ente.StripeEventLog{}, stacktrace.Propagate(err, "")
  386. }
  387. return ente.StripeEventLog{UserID: userID, StripeSubscription: *stripeSubscription, Event: event}, nil
  388. }
  389. func (c *StripeController) handlePaymentIntentFailed(event stripe.Event, country ente.StripeAccountCountry) (ente.StripeEventLog, error) {
  390. var paymentIntent stripe.PaymentIntent
  391. json.Unmarshal(event.Data.Raw, &paymentIntent)
  392. // Figure out the user
  393. invoiceID := paymentIntent.Invoice.ID
  394. client := c.StripeClients[country]
  395. invoice, err := client.Invoices.Get(invoiceID, nil)
  396. if err != nil {
  397. return ente.StripeEventLog{}, stacktrace.Propagate(err, "")
  398. }
  399. // void the invoice, in case the payment intent failed
  400. // _, err = client.Invoices.VoidInvoice(invoiceID, nil)
  401. // if err != nil {
  402. // return ente.StripeEventLog{}, stacktrace.Propagate(err, "")
  403. // }
  404. stripeSubscriptionID := invoice.Subscription.ID
  405. currentSubscription, err := c.BillingRepo.GetSubscriptionForTransaction(stripeSubscriptionID, ente.Stripe)
  406. if err != nil {
  407. if errors.Is(err, sql.ErrNoRows) {
  408. // See: Ignore webhooks received before user has been created
  409. log.Warn("Webhook is reporting an event for un-verified subscription stripeSubscriptionID:", stripeSubscriptionID)
  410. }
  411. return ente.StripeEventLog{}, stacktrace.Propagate(err, "")
  412. }
  413. userID := currentSubscription.UserID
  414. stripeSubscription, err := client.Subscriptions.Get(stripeSubscriptionID, nil)
  415. if err != nil {
  416. return ente.StripeEventLog{}, stacktrace.Propagate(err, "")
  417. }
  418. productID := stripeSubscription.Items.Data[0].Price.ID
  419. // If the current subscription is not the same as the one in the webhook, then
  420. // we don't need to do anything.
  421. fmt.Printf("productID: %s, currentSubscription.ProductID: %s\n", productID, currentSubscription.ProductID)
  422. if currentSubscription.ProductID != productID {
  423. // Webhook is reporting an update failure that has not been verified
  424. // no-op
  425. log.Warn("Webhook is reporting un-verified subscription update", stripeSubscription.ID, "invoiceID:", invoiceID)
  426. return ente.StripeEventLog{UserID: userID, StripeSubscription: *stripeSubscription, Event: event}, nil
  427. }
  428. // If the current subscription is the same as the one in the webhook, then
  429. // we need to expire the subscription, and send an email to the user.
  430. newExpiryTime := time.Now().UnixMicro() // Set the expiry time to now
  431. err = c.BillingRepo.UpdateSubscriptionExpiryTime(
  432. currentSubscription.ID, newExpiryTime)
  433. if err != nil {
  434. return ente.StripeEventLog{}, stacktrace.Propagate(err, "")
  435. }
  436. // Send an email to the user
  437. user, err := c.UserRepo.Get(userID)
  438. if err != nil {
  439. return ente.StripeEventLog{}, stacktrace.Propagate(err, "")
  440. }
  441. err = email.SendTemplatedEmail([]string{user.Email}, "ente", "support@ente.io",
  442. ente.AccountOnHoldEmailSubject, ente.OnHoldTemplate, map[string]interface{}{
  443. "PaymentProvider": "Stripe",
  444. }, nil)
  445. if err != nil {
  446. return ente.StripeEventLog{}, stacktrace.Propagate(err, "")
  447. }
  448. return ente.StripeEventLog{UserID: userID, StripeSubscription: *stripeSubscription, Event: event}, nil
  449. }
  450. func (c *StripeController) UpdateSubscription(stripeID string, userID int64) (ente.SubscriptionUpdateResponse, error) {
  451. subscription, err := c.BillingRepo.GetUserSubscription(userID)
  452. if err != nil {
  453. return ente.SubscriptionUpdateResponse{}, stacktrace.Propagate(err, "")
  454. }
  455. newPlan, newStripeAccountCountry, err := c.getPlanAndAccount(stripeID)
  456. if err != nil {
  457. return ente.SubscriptionUpdateResponse{}, stacktrace.Propagate(err, "")
  458. }
  459. if subscription.PaymentProvider != ente.Stripe || subscription.ProductID == stripeID || subscription.Attributes.StripeAccountCountry != newStripeAccountCountry {
  460. return ente.SubscriptionUpdateResponse{}, stacktrace.Propagate(ente.ErrBadRequest, "")
  461. }
  462. if newPlan.Storage < subscription.Storage { // Downgrade
  463. canDowngrade, canDowngradeErr := c.CommonBillCtrl.CanDowngradeToGivenStorage(newPlan.Storage, userID)
  464. if canDowngradeErr != nil {
  465. return ente.SubscriptionUpdateResponse{}, stacktrace.Propagate(canDowngradeErr, "")
  466. }
  467. if !canDowngrade {
  468. return ente.SubscriptionUpdateResponse{}, stacktrace.Propagate(ente.ErrCannotDowngrade, "")
  469. }
  470. log.Info("Usage is good")
  471. }
  472. client := c.StripeClients[subscription.Attributes.StripeAccountCountry]
  473. params := stripe.SubscriptionParams{}
  474. params.AddExpand("default_payment_method")
  475. stripeSubscription, err := client.Subscriptions.Get(subscription.OriginalTransactionID, &params)
  476. if err != nil {
  477. return ente.SubscriptionUpdateResponse{}, stacktrace.Propagate(err, "")
  478. }
  479. isSEPA := stripeSubscription.DefaultPaymentMethod.Type == stripe.PaymentMethodTypeSepaDebit
  480. var paymentBehavior stripe.SubscriptionPaymentBehavior
  481. if isSEPA {
  482. paymentBehavior = stripe.SubscriptionPaymentBehaviorAllowIncomplete
  483. } else {
  484. paymentBehavior = stripe.SubscriptionPaymentBehaviorPendingIfIncomplete
  485. }
  486. params = stripe.SubscriptionParams{
  487. ProrationBehavior: stripe.String(string(stripe.SubscriptionProrationBehaviorAlwaysInvoice)),
  488. Items: []*stripe.SubscriptionItemsParams{
  489. {
  490. ID: stripe.String(stripeSubscription.Items.Data[0].ID),
  491. Price: stripe.String(stripeID),
  492. },
  493. },
  494. PaymentBehavior: stripe.String(string(paymentBehavior)),
  495. }
  496. params.AddExpand("latest_invoice.payment_intent")
  497. newStripeSubscription, err := client.Subscriptions.Update(subscription.OriginalTransactionID, &params)
  498. if err != nil {
  499. stripeError := err.(*stripe.Error)
  500. switch stripeError.Type {
  501. case stripe.ErrorTypeCard:
  502. return ente.SubscriptionUpdateResponse{Status: "requires_payment_method"}, nil
  503. default:
  504. return ente.SubscriptionUpdateResponse{}, stacktrace.Propagate(err, "")
  505. }
  506. }
  507. if isSEPA {
  508. if newStripeSubscription.Status == stripe.SubscriptionStatusPastDue {
  509. if newStripeSubscription.LatestInvoice.PaymentIntent.Status == stripe.PaymentIntentStatusRequiresAction {
  510. return ente.SubscriptionUpdateResponse{Status: "requires_action", ClientSecret: newStripeSubscription.LatestInvoice.PaymentIntent.ClientSecret}, nil
  511. } else if newStripeSubscription.LatestInvoice.PaymentIntent.Status == stripe.PaymentIntentStatusRequiresPaymentMethod {
  512. // inv := newStripeSubscription.LatestInvoice
  513. // client.Invoices.VoidInvoice(inv.ID, nil)
  514. return ente.SubscriptionUpdateResponse{Status: "requires_payment_method"}, nil
  515. } else if newStripeSubscription.LatestInvoice.PaymentIntent.Status == stripe.PaymentIntentStatusProcessing {
  516. return ente.SubscriptionUpdateResponse{Status: "success"}, nil
  517. }
  518. return ente.SubscriptionUpdateResponse{}, stacktrace.Propagate(ente.ErrBadRequest, "")
  519. }
  520. } else {
  521. if newStripeSubscription.PendingUpdate != nil {
  522. switch newStripeSubscription.LatestInvoice.PaymentIntent.Status {
  523. case stripe.PaymentIntentStatusRequiresAction:
  524. return ente.SubscriptionUpdateResponse{Status: "requires_action", ClientSecret: newStripeSubscription.LatestInvoice.PaymentIntent.ClientSecret}, nil
  525. case stripe.PaymentIntentStatusRequiresPaymentMethod:
  526. inv := newStripeSubscription.LatestInvoice
  527. client.Invoices.VoidInvoice(inv.ID, nil)
  528. return ente.SubscriptionUpdateResponse{Status: "requires_payment_method"}, nil
  529. }
  530. return ente.SubscriptionUpdateResponse{}, stacktrace.Propagate(ente.ErrBadRequest, "")
  531. }
  532. }
  533. return ente.SubscriptionUpdateResponse{Status: "success"}, nil
  534. }
  535. func (c *StripeController) UpdateSubscriptionCancellationStatus(userID int64, status bool) (ente.Subscription, error) {
  536. subscription, err := c.BillingRepo.GetUserSubscription(userID)
  537. if err != nil {
  538. // error sql.ErrNoRows not possible as user must at least have a free subscription
  539. return ente.Subscription{}, stacktrace.Propagate(err, "")
  540. }
  541. if subscription.PaymentProvider != ente.Stripe {
  542. return ente.Subscription{}, stacktrace.Propagate(ente.ErrBadRequest, "")
  543. }
  544. if subscription.Attributes.IsCancelled == status {
  545. // no-op
  546. return subscription, nil
  547. }
  548. client := c.StripeClients[subscription.Attributes.StripeAccountCountry]
  549. params := &stripe.SubscriptionParams{
  550. CancelAtPeriodEnd: stripe.Bool(status),
  551. }
  552. _, err = client.Subscriptions.Update(subscription.OriginalTransactionID, params)
  553. if err != nil {
  554. return ente.Subscription{}, stacktrace.Propagate(err, "")
  555. }
  556. err = c.BillingRepo.UpdateSubscriptionCancellationStatus(userID, status)
  557. if err != nil {
  558. return ente.Subscription{}, stacktrace.Propagate(err, "")
  559. }
  560. subscription.Attributes.IsCancelled = status
  561. return subscription, nil
  562. }
  563. func (c *StripeController) GetStripeCustomerPortal(userID int64, redirectRootURL string) (string, error) {
  564. subscription, err := c.BillingRepo.GetUserSubscription(userID)
  565. if err != nil {
  566. return "", stacktrace.Propagate(err, "")
  567. }
  568. if subscription.PaymentProvider != ente.Stripe {
  569. return "", stacktrace.Propagate(ente.ErrBadRequest, "")
  570. }
  571. client := c.StripeClients[subscription.Attributes.StripeAccountCountry]
  572. params := &stripe.BillingPortalSessionParams{
  573. Customer: stripe.String(subscription.Attributes.CustomerID),
  574. ReturnURL: stripe.String(redirectRootURL),
  575. }
  576. ps, err := client.BillingPortalSessions.New(params)
  577. if err != nil {
  578. return "", stacktrace.Propagate(err, "")
  579. }
  580. return ps.URL, nil
  581. }
  582. func (c *StripeController) getStripeSubscriptionFromSession(userID int64, checkoutSessionID string) (stripe.Subscription, error) {
  583. subscription, err := c.BillingRepo.GetUserSubscription(userID)
  584. if err != nil {
  585. return stripe.Subscription{}, stacktrace.Propagate(err, "")
  586. }
  587. var stripeClient *client.API
  588. if subscription.PaymentProvider == ente.Stripe {
  589. stripeClient = c.StripeClients[subscription.Attributes.StripeAccountCountry]
  590. } else {
  591. stripeClient = c.StripeClients[ente.DefaultStripeAccountCountry]
  592. }
  593. params := &stripe.CheckoutSessionParams{}
  594. params.AddExpand("subscription")
  595. checkoutSession, err := stripeClient.CheckoutSessions.Get(checkoutSessionID, params)
  596. if err != nil {
  597. return stripe.Subscription{}, stacktrace.Propagate(err, "")
  598. }
  599. if (*checkoutSession.Subscription).Status != stripe.SubscriptionStatusActive {
  600. return stripe.Subscription{}, stacktrace.Propagate(&stripe.InvalidRequestError{}, "")
  601. }
  602. return *checkoutSession.Subscription, nil
  603. }
  604. func (c *StripeController) getPriceIDFromSession(sessionID string) (string, error) {
  605. stripeClient := c.StripeClients[ente.DefaultStripeAccountCountry]
  606. params := &stripe.CheckoutSessionListLineItemsParams{}
  607. params.AddExpand("data.price")
  608. items := stripeClient.CheckoutSessions.ListLineItems(sessionID, params)
  609. for items.Next() { // Return the first PriceID that has been fetched
  610. return items.LineItem().Price.ID, nil
  611. }
  612. return "", stacktrace.Propagate(ente.ErrNotFound, "")
  613. }
  614. func (c *StripeController) getUserStripeSubscription(userID int64) (stripe.Subscription, error) {
  615. subscription, err := c.BillingRepo.GetUserSubscription(userID)
  616. if err != nil {
  617. return stripe.Subscription{}, stacktrace.Propagate(err, "")
  618. }
  619. if subscription.PaymentProvider != ente.Stripe {
  620. return stripe.Subscription{}, stacktrace.Propagate(ente.ErrCannotSwitchPaymentProvider, "")
  621. }
  622. client := c.StripeClients[subscription.Attributes.StripeAccountCountry]
  623. stripeSubscription, err := client.Subscriptions.Get(subscription.OriginalTransactionID, nil)
  624. if err != nil {
  625. return stripe.Subscription{}, stacktrace.Propagate(err, "")
  626. }
  627. return *stripeSubscription, nil
  628. }
  629. func (c *StripeController) getPlanAndAccount(stripeID string) (ente.BillingPlan, ente.StripeAccountCountry, error) {
  630. for stripeAccountCountry, billingPlansCountryWise := range c.BillingPlansPerAccount {
  631. for _, plans := range billingPlansCountryWise {
  632. for _, plan := range plans {
  633. if plan.StripeID == stripeID {
  634. return plan, stripeAccountCountry, nil
  635. }
  636. }
  637. }
  638. }
  639. return ente.BillingPlan{}, "", stacktrace.Propagate(ente.ErrNotFound, "")
  640. }
  641. func (c *StripeController) getEnteSubscriptionFromStripeSubscription(userID int64, stripeSubscription stripe.Subscription) (ente.Subscription, error) {
  642. productID := stripeSubscription.Items.Data[0].Price.ID
  643. plan, stripeAccountCountry, err := c.getPlanAndAccount(productID)
  644. if err != nil {
  645. return ente.Subscription{}, stacktrace.Propagate(err, "")
  646. }
  647. s := ente.Subscription{
  648. UserID: userID,
  649. PaymentProvider: ente.Stripe,
  650. ProductID: productID,
  651. Storage: plan.Storage,
  652. Attributes: ente.SubscriptionAttributes{CustomerID: stripeSubscription.Customer.ID, IsCancelled: false, StripeAccountCountry: stripeAccountCountry},
  653. OriginalTransactionID: stripeSubscription.ID,
  654. ExpiryTime: stripeSubscription.CurrentPeriodEnd * 1000 * 1000,
  655. }
  656. return s, nil
  657. }
  658. func (c *StripeController) UpdateBillingEmail(subscription ente.Subscription, newEmail string) error {
  659. params := &stripe.CustomerParams{Email: &newEmail}
  660. client := c.StripeClients[subscription.Attributes.StripeAccountCountry]
  661. _, err := client.Customers.Update(
  662. subscription.Attributes.CustomerID,
  663. params,
  664. )
  665. if err != nil {
  666. return stacktrace.Propagate(err, "failed to update stripe customer emailID")
  667. }
  668. return nil
  669. }
  670. func (c *StripeController) CancelSubAndDeleteCustomer(subscription ente.Subscription, logger *log.Entry) error {
  671. client := c.StripeClients[subscription.Attributes.StripeAccountCountry]
  672. if !subscription.Attributes.IsCancelled {
  673. prorateRefund := true
  674. logger.Info("cancelling sub with prorated refund")
  675. updateParams := &stripe.SubscriptionParams{}
  676. updateParams.AddMetadata(SkipMailKey, "true")
  677. _, err := client.Subscriptions.Update(subscription.OriginalTransactionID, updateParams)
  678. if err != nil {
  679. stripeError := err.(*stripe.Error)
  680. errorMsg := fmt.Sprintf("subscription updation failed during account deletion: %s, %s", stripeError.Msg, stripeError.Code)
  681. log.Error(errorMsg)
  682. c.DiscordController.Notify(errorMsg)
  683. if stripeError.HTTPStatusCode == http.StatusNotFound {
  684. log.Error("Ignoring error since an active subscription could not be found")
  685. return nil
  686. } else if stripeError.HTTPStatusCode == http.StatusBadRequest {
  687. log.Error("Bad request while trying to delete account")
  688. return nil
  689. }
  690. return stacktrace.Propagate(err, "")
  691. }
  692. _, err = client.Subscriptions.Cancel(subscription.OriginalTransactionID, &stripe.SubscriptionCancelParams{
  693. Prorate: &prorateRefund,
  694. })
  695. if err != nil {
  696. stripeError := err.(*stripe.Error)
  697. logger.Error(fmt.Sprintf("subscription cancel failed msg= %s for userID=%d"+stripeError.Msg, subscription.UserID))
  698. // ignore if subscription doesn't exist, already deleted
  699. if stripeError.HTTPStatusCode != 404 {
  700. return stacktrace.Propagate(err, "")
  701. }
  702. }
  703. err = c.BillingRepo.UpdateSubscriptionCancellationStatus(subscription.UserID, true)
  704. if err != nil {
  705. return stacktrace.Propagate(err, "")
  706. }
  707. }
  708. logger.Info("deleting customer from stripe")
  709. _, err := client.Customers.Del(
  710. subscription.Attributes.CustomerID,
  711. &stripe.CustomerParams{},
  712. )
  713. if err != nil {
  714. stripeError := err.(*stripe.Error)
  715. switch stripeError.Type {
  716. case stripe.ErrorTypeInvalidRequest:
  717. if stripe.ErrorCodeResourceMissing == stripeError.Code {
  718. return nil
  719. }
  720. return stacktrace.Propagate(err, fmt.Sprintf("failed to delete customer %s", subscription.Attributes.CustomerID))
  721. default:
  722. return stacktrace.Propagate(err, fmt.Sprintf("failed to delete customer %s", subscription.Attributes.CustomerID))
  723. }
  724. }
  725. return nil
  726. }
  727. // cancel the earlier past_due subscription
  728. // and add skip mail metadata entry to avoid sending account deletion mail while re-subscription
  729. func (c *StripeController) cancelExistingStripeSubscription(subscription ente.Subscription, userID int64) error {
  730. updateParams := &stripe.SubscriptionParams{}
  731. updateParams.AddMetadata(SkipMailKey, "true")
  732. client := c.StripeClients[subscription.Attributes.StripeAccountCountry]
  733. _, err := client.Subscriptions.Update(subscription.OriginalTransactionID, updateParams)
  734. if err != nil {
  735. stripeError := err.(*stripe.Error)
  736. log.Warn(fmt.Sprintf("subscription updation failed msg= %s for userID=%d", stripeError.Msg, userID))
  737. // ignore if subscription doesn't exist, already deleted
  738. if stripeError.HTTPStatusCode != 404 {
  739. return stacktrace.Propagate(err, "")
  740. }
  741. } else {
  742. _, err = client.Subscriptions.Cancel(subscription.OriginalTransactionID, nil)
  743. if err != nil {
  744. stripeError := err.(*stripe.Error)
  745. log.Warn(fmt.Sprintf("subscription cancel failed msg= %s for userID=%d", stripeError.Msg, userID))
  746. // ignore if subscription doesn't exist, already deleted
  747. if stripeError.HTTPStatusCode != 404 {
  748. return stacktrace.Propagate(err, "")
  749. }
  750. }
  751. err = c.BillingRepo.UpdateSubscriptionCancellationStatus(userID, true)
  752. if err != nil {
  753. return stacktrace.Propagate(err, "")
  754. }
  755. }
  756. return nil
  757. }