stripe.go 33 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797
  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. // Occurs whenever a subscription changes (e.g., switching from one plan to
  313. // another, or changing the status from trial to active).
  314. func (c *StripeController) handleCustomerSubscriptionUpdated(event stripe.Event, country ente.StripeAccountCountry) (ente.StripeEventLog, error) {
  315. var stripeSubscription stripe.Subscription
  316. json.Unmarshal(event.Data.Raw, &stripeSubscription)
  317. currentSubscription, err := c.BillingRepo.GetSubscriptionForTransaction(stripeSubscription.ID, ente.Stripe)
  318. if err != nil {
  319. if errors.Is(err, sql.ErrNoRows) {
  320. // See: Ignore webhooks received before user has been created
  321. log.Warn("Webhook is reporting an event for un-verified subscription stripeSubscriptionID:", stripeSubscription.ID)
  322. return ente.StripeEventLog{}, nil
  323. }
  324. return ente.StripeEventLog{}, stacktrace.Propagate(err, "")
  325. }
  326. userID := currentSubscription.UserID
  327. newSubscription, err := c.getEnteSubscriptionFromStripeSubscription(userID, stripeSubscription)
  328. if err != nil {
  329. return ente.StripeEventLog{}, stacktrace.Propagate(err, "")
  330. }
  331. if currentSubscription.ProductID == newSubscription.ProductID {
  332. // Webhook is reporting an outdated update that was already verified
  333. // no-op
  334. log.Warn("Webhook is reporting an outdated purchase that was already verified stripeSubscriptionID:", stripeSubscription.ID)
  335. return ente.StripeEventLog{UserID: userID, StripeSubscription: stripeSubscription, Event: event}, nil
  336. }
  337. c.BillingRepo.ReplaceSubscription(currentSubscription.ID, newSubscription)
  338. if stripeSubscription.Status == stripe.SubscriptionStatusPastDue {
  339. user, err := c.UserRepo.Get(userID)
  340. if err != nil {
  341. return ente.StripeEventLog{}, stacktrace.Propagate(err, "")
  342. }
  343. err = email.SendTemplatedEmail([]string{user.Email}, "ente", "support@ente.io",
  344. ente.AccountOnHoldEmailSubject, ente.OnHoldTemplate, map[string]interface{}{
  345. "PaymentProvider": "Stripe",
  346. }, nil)
  347. if err != nil {
  348. return ente.StripeEventLog{}, stacktrace.Propagate(err, "")
  349. }
  350. }
  351. return ente.StripeEventLog{UserID: userID, StripeSubscription: stripeSubscription, Event: event}, nil
  352. }
  353. // Continue to provision the subscription as payments continue to be made.
  354. func (c *StripeController) handleInvoicePaid(event stripe.Event, country ente.StripeAccountCountry) (ente.StripeEventLog, error) {
  355. var invoice stripe.Invoice
  356. json.Unmarshal(event.Data.Raw, &invoice)
  357. stripeSubscriptionID := invoice.Subscription.ID
  358. currentSubscription, err := c.BillingRepo.GetSubscriptionForTransaction(stripeSubscriptionID, ente.Stripe)
  359. if err != nil {
  360. if errors.Is(err, sql.ErrNoRows) {
  361. // See: Ignore webhooks received before user has been created
  362. log.Warn("Webhook is reporting an event for un-verified subscription stripeSubscriptionID:", stripeSubscriptionID)
  363. return ente.StripeEventLog{}, nil
  364. }
  365. return ente.StripeEventLog{}, stacktrace.Propagate(err, "")
  366. }
  367. userID := currentSubscription.UserID
  368. client := c.StripeClients[currentSubscription.Attributes.StripeAccountCountry]
  369. stripeSubscription, err := client.Subscriptions.Get(stripeSubscriptionID, nil)
  370. if err != nil {
  371. return ente.StripeEventLog{}, stacktrace.Propagate(err, "")
  372. }
  373. newExpiryTime := stripeSubscription.CurrentPeriodEnd * 1000 * 1000
  374. if currentSubscription.ExpiryTime == newExpiryTime {
  375. //outdated invoice
  376. log.Warn("Webhook is reporting an outdated purchase that was already verified stripeSubscriptionID:", stripeSubscription.ID)
  377. return ente.StripeEventLog{UserID: userID, StripeSubscription: *stripeSubscription, Event: event}, nil
  378. }
  379. err = c.BillingRepo.UpdateSubscriptionExpiryTime(
  380. currentSubscription.ID, newExpiryTime)
  381. if err != nil {
  382. return ente.StripeEventLog{}, stacktrace.Propagate(err, "")
  383. }
  384. return ente.StripeEventLog{UserID: userID, StripeSubscription: *stripeSubscription, Event: event}, nil
  385. }
  386. func (c *StripeController) handlePaymentIntentFailed(event stripe.Event, country ente.StripeAccountCountry) (ente.StripeEventLog, error) {
  387. var paymentIntent stripe.PaymentIntent
  388. json.Unmarshal(event.Data.Raw, &paymentIntent)
  389. // Figure out the user
  390. invoiceID := paymentIntent.Invoice.ID
  391. client := c.StripeClients[country]
  392. invoice, err := client.Invoices.Get(invoiceID, nil)
  393. if err != nil {
  394. return ente.StripeEventLog{}, stacktrace.Propagate(err, "")
  395. }
  396. // void the invoice, in case the payment intent failed
  397. // _, err = client.Invoices.VoidInvoice(invoiceID, nil)
  398. // if err != nil {
  399. // return ente.StripeEventLog{}, stacktrace.Propagate(err, "")
  400. // }
  401. stripeSubscriptionID := invoice.Subscription.ID
  402. currentSubscription, err := c.BillingRepo.GetSubscriptionForTransaction(stripeSubscriptionID, ente.Stripe)
  403. if err != nil {
  404. if errors.Is(err, sql.ErrNoRows) {
  405. // See: Ignore webhooks received before user has been created
  406. log.Warn("Webhook is reporting an event for un-verified subscription stripeSubscriptionID:", stripeSubscriptionID)
  407. }
  408. return ente.StripeEventLog{}, stacktrace.Propagate(err, "")
  409. }
  410. userID := currentSubscription.UserID
  411. stripeSubscription, err := client.Subscriptions.Get(stripeSubscriptionID, nil)
  412. if err != nil {
  413. return ente.StripeEventLog{}, stacktrace.Propagate(err, "")
  414. }
  415. productID := stripeSubscription.Items.Data[0].Price.ID
  416. // If the current subscription is not the same as the one in the webhook, then
  417. // we don't need to do anything.
  418. fmt.Printf("productID: %s, currentSubscription.ProductID: %s\n", productID, currentSubscription.ProductID)
  419. if currentSubscription.ProductID != productID {
  420. // Webhook is reporting an update failure that has not been verified
  421. // no-op
  422. log.Warn("Webhook is reporting un-verified subscription update", stripeSubscription.ID, "invoiceID:", invoiceID)
  423. return ente.StripeEventLog{UserID: userID, StripeSubscription: *stripeSubscription, Event: event}, nil
  424. }
  425. // If the current subscription is the same as the one in the webhook, then
  426. // we need to expire the subscription, and send an email to the user.
  427. newExpiryTime := time.Now().UnixMicro() // Set the expiry time to now
  428. err = c.BillingRepo.UpdateSubscriptionExpiryTime(
  429. currentSubscription.ID, newExpiryTime)
  430. if err != nil {
  431. return ente.StripeEventLog{}, stacktrace.Propagate(err, "")
  432. }
  433. // Send an email to the user
  434. user, err := c.UserRepo.Get(userID)
  435. if err != nil {
  436. return ente.StripeEventLog{}, stacktrace.Propagate(err, "")
  437. }
  438. err = email.SendTemplatedEmail([]string{user.Email}, "ente", "support@ente.io",
  439. ente.AccountOnHoldEmailSubject, ente.OnHoldTemplate, map[string]interface{}{
  440. "PaymentProvider": "Stripe",
  441. }, nil)
  442. if err != nil {
  443. return ente.StripeEventLog{}, stacktrace.Propagate(err, "")
  444. }
  445. return ente.StripeEventLog{UserID: userID, StripeSubscription: *stripeSubscription, Event: event}, nil
  446. }
  447. func (c *StripeController) UpdateSubscription(stripeID string, userID int64) (ente.SubscriptionUpdateResponse, error) {
  448. subscription, err := c.BillingRepo.GetUserSubscription(userID)
  449. if err != nil {
  450. return ente.SubscriptionUpdateResponse{}, stacktrace.Propagate(err, "")
  451. }
  452. newPlan, newStripeAccountCountry, err := c.getPlanAndAccount(stripeID)
  453. if err != nil {
  454. return ente.SubscriptionUpdateResponse{}, stacktrace.Propagate(err, "")
  455. }
  456. if subscription.PaymentProvider != ente.Stripe || subscription.ProductID == stripeID || subscription.Attributes.StripeAccountCountry != newStripeAccountCountry {
  457. return ente.SubscriptionUpdateResponse{}, stacktrace.Propagate(ente.ErrBadRequest, "")
  458. }
  459. if newPlan.Storage < subscription.Storage { // Downgrade
  460. canDowngrade, canDowngradeErr := c.CommonBillCtrl.CanDowngradeToGivenStorage(newPlan.Storage, userID)
  461. if canDowngradeErr != nil {
  462. return ente.SubscriptionUpdateResponse{}, stacktrace.Propagate(canDowngradeErr, "")
  463. }
  464. if !canDowngrade {
  465. return ente.SubscriptionUpdateResponse{}, stacktrace.Propagate(ente.ErrCannotDowngrade, "")
  466. }
  467. log.Info("Usage is good")
  468. }
  469. client := c.StripeClients[subscription.Attributes.StripeAccountCountry]
  470. params := stripe.SubscriptionParams{}
  471. params.AddExpand("default_payment_method")
  472. stripeSubscription, err := client.Subscriptions.Get(subscription.OriginalTransactionID, &params)
  473. if err != nil {
  474. return ente.SubscriptionUpdateResponse{}, stacktrace.Propagate(err, "")
  475. }
  476. isSEPA := stripeSubscription.DefaultPaymentMethod.Type == stripe.PaymentMethodTypeSepaDebit
  477. var paymentBehavior stripe.SubscriptionPaymentBehavior
  478. if isSEPA {
  479. paymentBehavior = stripe.SubscriptionPaymentBehaviorAllowIncomplete
  480. } else {
  481. paymentBehavior = stripe.SubscriptionPaymentBehaviorPendingIfIncomplete
  482. }
  483. params = stripe.SubscriptionParams{
  484. ProrationBehavior: stripe.String(string(stripe.SubscriptionProrationBehaviorAlwaysInvoice)),
  485. Items: []*stripe.SubscriptionItemsParams{
  486. {
  487. ID: stripe.String(stripeSubscription.Items.Data[0].ID),
  488. Price: stripe.String(stripeID),
  489. },
  490. },
  491. PaymentBehavior: stripe.String(string(paymentBehavior)),
  492. }
  493. params.AddExpand("latest_invoice.payment_intent")
  494. newStripeSubscription, err := client.Subscriptions.Update(subscription.OriginalTransactionID, &params)
  495. if err != nil {
  496. stripeError := err.(*stripe.Error)
  497. switch stripeError.Type {
  498. case stripe.ErrorTypeCard:
  499. return ente.SubscriptionUpdateResponse{Status: "requires_payment_method"}, nil
  500. default:
  501. return ente.SubscriptionUpdateResponse{}, stacktrace.Propagate(err, "")
  502. }
  503. }
  504. if isSEPA {
  505. if newStripeSubscription.Status == stripe.SubscriptionStatusPastDue {
  506. if newStripeSubscription.LatestInvoice.PaymentIntent.Status == stripe.PaymentIntentStatusRequiresAction {
  507. return ente.SubscriptionUpdateResponse{Status: "requires_action", ClientSecret: newStripeSubscription.LatestInvoice.PaymentIntent.ClientSecret}, nil
  508. } else if newStripeSubscription.LatestInvoice.PaymentIntent.Status == stripe.PaymentIntentStatusRequiresPaymentMethod {
  509. // inv := newStripeSubscription.LatestInvoice
  510. // client.Invoices.VoidInvoice(inv.ID, nil)
  511. return ente.SubscriptionUpdateResponse{Status: "requires_payment_method"}, nil
  512. } else if newStripeSubscription.LatestInvoice.PaymentIntent.Status == stripe.PaymentIntentStatusProcessing {
  513. return ente.SubscriptionUpdateResponse{Status: "success"}, nil
  514. }
  515. return ente.SubscriptionUpdateResponse{}, stacktrace.Propagate(ente.ErrBadRequest, "")
  516. }
  517. } else {
  518. if newStripeSubscription.PendingUpdate != nil {
  519. switch newStripeSubscription.LatestInvoice.PaymentIntent.Status {
  520. case stripe.PaymentIntentStatusRequiresAction:
  521. return ente.SubscriptionUpdateResponse{Status: "requires_action", ClientSecret: newStripeSubscription.LatestInvoice.PaymentIntent.ClientSecret}, nil
  522. case stripe.PaymentIntentStatusRequiresPaymentMethod:
  523. inv := newStripeSubscription.LatestInvoice
  524. client.Invoices.VoidInvoice(inv.ID, nil)
  525. return ente.SubscriptionUpdateResponse{Status: "requires_payment_method"}, nil
  526. }
  527. return ente.SubscriptionUpdateResponse{}, stacktrace.Propagate(ente.ErrBadRequest, "")
  528. }
  529. }
  530. return ente.SubscriptionUpdateResponse{Status: "success"}, nil
  531. }
  532. func (c *StripeController) UpdateSubscriptionCancellationStatus(userID int64, status bool) (ente.Subscription, error) {
  533. subscription, err := c.BillingRepo.GetUserSubscription(userID)
  534. if err != nil {
  535. // error sql.ErrNoRows not possible as user must at least have a free subscription
  536. return ente.Subscription{}, stacktrace.Propagate(err, "")
  537. }
  538. if subscription.PaymentProvider != ente.Stripe {
  539. return ente.Subscription{}, stacktrace.Propagate(ente.ErrBadRequest, "")
  540. }
  541. if subscription.Attributes.IsCancelled == status {
  542. // no-op
  543. return subscription, nil
  544. }
  545. client := c.StripeClients[subscription.Attributes.StripeAccountCountry]
  546. params := &stripe.SubscriptionParams{
  547. CancelAtPeriodEnd: stripe.Bool(status),
  548. }
  549. _, err = client.Subscriptions.Update(subscription.OriginalTransactionID, params)
  550. if err != nil {
  551. return ente.Subscription{}, stacktrace.Propagate(err, "")
  552. }
  553. err = c.BillingRepo.UpdateSubscriptionCancellationStatus(userID, status)
  554. if err != nil {
  555. return ente.Subscription{}, stacktrace.Propagate(err, "")
  556. }
  557. subscription.Attributes.IsCancelled = status
  558. return subscription, nil
  559. }
  560. func (c *StripeController) GetStripeCustomerPortal(userID int64, redirectRootURL string) (string, error) {
  561. subscription, err := c.BillingRepo.GetUserSubscription(userID)
  562. if err != nil {
  563. return "", stacktrace.Propagate(err, "")
  564. }
  565. if subscription.PaymentProvider != ente.Stripe {
  566. return "", stacktrace.Propagate(ente.ErrBadRequest, "")
  567. }
  568. client := c.StripeClients[subscription.Attributes.StripeAccountCountry]
  569. params := &stripe.BillingPortalSessionParams{
  570. Customer: stripe.String(subscription.Attributes.CustomerID),
  571. ReturnURL: stripe.String(redirectRootURL),
  572. }
  573. ps, err := client.BillingPortalSessions.New(params)
  574. if err != nil {
  575. return "", stacktrace.Propagate(err, "")
  576. }
  577. return ps.URL, nil
  578. }
  579. func (c *StripeController) getStripeSubscriptionFromSession(userID int64, checkoutSessionID string) (stripe.Subscription, error) {
  580. subscription, err := c.BillingRepo.GetUserSubscription(userID)
  581. if err != nil {
  582. return stripe.Subscription{}, stacktrace.Propagate(err, "")
  583. }
  584. var stripeClient *client.API
  585. if subscription.PaymentProvider == ente.Stripe {
  586. stripeClient = c.StripeClients[subscription.Attributes.StripeAccountCountry]
  587. } else {
  588. stripeClient = c.StripeClients[ente.DefaultStripeAccountCountry]
  589. }
  590. params := &stripe.CheckoutSessionParams{}
  591. params.AddExpand("subscription")
  592. checkoutSession, err := stripeClient.CheckoutSessions.Get(checkoutSessionID, params)
  593. if err != nil {
  594. return stripe.Subscription{}, stacktrace.Propagate(err, "")
  595. }
  596. if (*checkoutSession.Subscription).Status != stripe.SubscriptionStatusActive {
  597. return stripe.Subscription{}, stacktrace.Propagate(&stripe.InvalidRequestError{}, "")
  598. }
  599. return *checkoutSession.Subscription, nil
  600. }
  601. func (c *StripeController) getPriceIDFromSession(sessionID string) (string, error) {
  602. stripeClient := c.StripeClients[ente.DefaultStripeAccountCountry]
  603. params := &stripe.CheckoutSessionListLineItemsParams{}
  604. params.AddExpand("data.price")
  605. items := stripeClient.CheckoutSessions.ListLineItems(sessionID, params)
  606. for items.Next() { // Return the first PriceID that has been fetched
  607. return items.LineItem().Price.ID, nil
  608. }
  609. return "", stacktrace.Propagate(ente.ErrNotFound, "")
  610. }
  611. func (c *StripeController) getUserStripeSubscription(userID int64) (stripe.Subscription, error) {
  612. subscription, err := c.BillingRepo.GetUserSubscription(userID)
  613. if err != nil {
  614. return stripe.Subscription{}, stacktrace.Propagate(err, "")
  615. }
  616. if subscription.PaymentProvider != ente.Stripe {
  617. return stripe.Subscription{}, stacktrace.Propagate(ente.ErrCannotSwitchPaymentProvider, "")
  618. }
  619. client := c.StripeClients[subscription.Attributes.StripeAccountCountry]
  620. stripeSubscription, err := client.Subscriptions.Get(subscription.OriginalTransactionID, nil)
  621. if err != nil {
  622. return stripe.Subscription{}, stacktrace.Propagate(err, "")
  623. }
  624. return *stripeSubscription, nil
  625. }
  626. func (c *StripeController) getPlanAndAccount(stripeID string) (ente.BillingPlan, ente.StripeAccountCountry, error) {
  627. for stripeAccountCountry, billingPlansCountryWise := range c.BillingPlansPerAccount {
  628. for _, plans := range billingPlansCountryWise {
  629. for _, plan := range plans {
  630. if plan.StripeID == stripeID {
  631. return plan, stripeAccountCountry, nil
  632. }
  633. }
  634. }
  635. }
  636. return ente.BillingPlan{}, "", stacktrace.Propagate(ente.ErrNotFound, "")
  637. }
  638. func (c *StripeController) getEnteSubscriptionFromStripeSubscription(userID int64, stripeSubscription stripe.Subscription) (ente.Subscription, error) {
  639. productID := stripeSubscription.Items.Data[0].Price.ID
  640. plan, stripeAccountCountry, err := c.getPlanAndAccount(productID)
  641. if err != nil {
  642. return ente.Subscription{}, stacktrace.Propagate(err, "")
  643. }
  644. s := ente.Subscription{
  645. UserID: userID,
  646. PaymentProvider: ente.Stripe,
  647. ProductID: productID,
  648. Storage: plan.Storage,
  649. Attributes: ente.SubscriptionAttributes{CustomerID: stripeSubscription.Customer.ID, IsCancelled: false, StripeAccountCountry: stripeAccountCountry},
  650. OriginalTransactionID: stripeSubscription.ID,
  651. ExpiryTime: stripeSubscription.CurrentPeriodEnd * 1000 * 1000,
  652. }
  653. return s, nil
  654. }
  655. func (c *StripeController) UpdateBillingEmail(subscription ente.Subscription, newEmail string) error {
  656. params := &stripe.CustomerParams{Email: &newEmail}
  657. client := c.StripeClients[subscription.Attributes.StripeAccountCountry]
  658. _, err := client.Customers.Update(
  659. subscription.Attributes.CustomerID,
  660. params,
  661. )
  662. if err != nil {
  663. return stacktrace.Propagate(err, "failed to update stripe customer emailID")
  664. }
  665. return nil
  666. }
  667. func (c *StripeController) CancelSubAndDeleteCustomer(subscription ente.Subscription, logger *log.Entry) error {
  668. client := c.StripeClients[subscription.Attributes.StripeAccountCountry]
  669. if !subscription.Attributes.IsCancelled {
  670. prorateRefund := true
  671. logger.Info("cancelling sub with prorated refund")
  672. updateParams := &stripe.SubscriptionParams{}
  673. updateParams.AddMetadata(SkipMailKey, "true")
  674. _, err := client.Subscriptions.Update(subscription.OriginalTransactionID, updateParams)
  675. if err != nil {
  676. stripeError := err.(*stripe.Error)
  677. errorMsg := fmt.Sprintf("subscription updation failed during account deletion: %s, %s", stripeError.Msg, stripeError.Code)
  678. log.Error(errorMsg)
  679. c.DiscordController.Notify(errorMsg)
  680. if stripeError.HTTPStatusCode == http.StatusNotFound {
  681. log.Error("Ignoring error since an active subscription could not be found")
  682. return nil
  683. } else if stripeError.HTTPStatusCode == http.StatusBadRequest {
  684. log.Error("Bad request while trying to delete account")
  685. return nil
  686. }
  687. return stacktrace.Propagate(err, "")
  688. }
  689. _, err = client.Subscriptions.Cancel(subscription.OriginalTransactionID, &stripe.SubscriptionCancelParams{
  690. Prorate: &prorateRefund,
  691. })
  692. if err != nil {
  693. stripeError := err.(*stripe.Error)
  694. logger.Error(fmt.Sprintf("subscription cancel failed msg= %s for userID=%d"+stripeError.Msg, subscription.UserID))
  695. // ignore if subscription doesn't exist, already deleted
  696. if stripeError.HTTPStatusCode != 404 {
  697. return stacktrace.Propagate(err, "")
  698. }
  699. }
  700. err = c.BillingRepo.UpdateSubscriptionCancellationStatus(subscription.UserID, true)
  701. if err != nil {
  702. return stacktrace.Propagate(err, "")
  703. }
  704. }
  705. logger.Info("deleting customer from stripe")
  706. _, err := client.Customers.Del(
  707. subscription.Attributes.CustomerID,
  708. &stripe.CustomerParams{},
  709. )
  710. if err != nil {
  711. stripeError := err.(*stripe.Error)
  712. switch stripeError.Type {
  713. case stripe.ErrorTypeInvalidRequest:
  714. if stripe.ErrorCodeResourceMissing == stripeError.Code {
  715. return nil
  716. }
  717. return stacktrace.Propagate(err, fmt.Sprintf("failed to delete customer %s", subscription.Attributes.CustomerID))
  718. default:
  719. return stacktrace.Propagate(err, fmt.Sprintf("failed to delete customer %s", subscription.Attributes.CustomerID))
  720. }
  721. }
  722. return nil
  723. }
  724. // cancel the earlier past_due subscription
  725. // and add skip mail metadata entry to avoid sending account deletion mail while re-subscription
  726. func (c *StripeController) cancelExistingStripeSubscription(subscription ente.Subscription, userID int64) error {
  727. updateParams := &stripe.SubscriptionParams{}
  728. updateParams.AddMetadata(SkipMailKey, "true")
  729. client := c.StripeClients[subscription.Attributes.StripeAccountCountry]
  730. _, err := client.Subscriptions.Update(subscription.OriginalTransactionID, updateParams)
  731. if err != nil {
  732. stripeError := err.(*stripe.Error)
  733. log.Warn(fmt.Sprintf("subscription updation failed msg= %s for userID=%d", stripeError.Msg, userID))
  734. // ignore if subscription doesn't exist, already deleted
  735. if stripeError.HTTPStatusCode != 404 {
  736. return stacktrace.Propagate(err, "")
  737. }
  738. } else {
  739. _, err = client.Subscriptions.Cancel(subscription.OriginalTransactionID, nil)
  740. if err != nil {
  741. stripeError := err.(*stripe.Error)
  742. log.Warn(fmt.Sprintf("subscription cancel failed msg= %s for userID=%d", stripeError.Msg, userID))
  743. // ignore if subscription doesn't exist, already deleted
  744. if stripeError.HTTPStatusCode != 404 {
  745. return stacktrace.Propagate(err, "")
  746. }
  747. }
  748. err = c.BillingRepo.UpdateSubscriptionCancellationStatus(userID, true)
  749. if err != nil {
  750. return stacktrace.Propagate(err, "")
  751. }
  752. }
  753. return nil
  754. }