2023-01-10 15:58:41 -05:00
|
|
|
|
using Bit.Billing.Constants;
|
2022-01-11 10:40:51 +01:00
|
|
|
|
using Bit.Core.Entities;
|
2021-02-22 15:35:16 -06:00
|
|
|
|
using Bit.Core.Enums;
|
2022-05-10 17:12:09 -04:00
|
|
|
|
using Bit.Core.OrganizationFeatures.OrganizationSponsorships.FamiliesForEnterprise.Interfaces;
|
2018-05-11 08:29:23 -04:00
|
|
|
|
using Bit.Core.Repositories;
|
|
|
|
|
|
using Bit.Core.Services;
|
2021-02-22 15:35:16 -06:00
|
|
|
|
using Bit.Core.Settings;
|
2023-04-18 14:05:17 +02:00
|
|
|
|
using Bit.Core.Tools.Enums;
|
|
|
|
|
|
using Bit.Core.Tools.Models.Business;
|
|
|
|
|
|
using Bit.Core.Tools.Services;
|
2019-08-09 23:56:26 -04:00
|
|
|
|
using Bit.Core.Utilities;
|
2017-04-26 16:14:15 -04:00
|
|
|
|
using Microsoft.AspNetCore.Mvc;
|
2023-01-10 15:58:41 -05:00
|
|
|
|
using Microsoft.Data.SqlClient;
|
2017-04-26 14:29:25 -04:00
|
|
|
|
using Microsoft.Extensions.Options;
|
2017-04-26 16:14:15 -04:00
|
|
|
|
using Stripe;
|
2022-01-11 10:40:51 +01:00
|
|
|
|
using TaxRate = Bit.Core.Entities.TaxRate;
|
2017-03-18 18:52:44 -04:00
|
|
|
|
|
|
|
|
|
|
namespace Bit.Billing.Controllers;
|
2022-08-29 16:06:55 -04:00
|
|
|
|
|
2017-03-18 18:52:44 -04:00
|
|
|
|
[Route("stripe")]
|
|
|
|
|
|
public class StripeController : Controller
|
|
|
|
|
|
{
|
2017-04-26 14:29:25 -04:00
|
|
|
|
private const decimal PremiumPlanAppleIapPrice = 14.99M;
|
2017-03-18 18:52:44 -04:00
|
|
|
|
private const string PremiumPlanId = "premium-annually";
|
2022-06-24 14:20:32 -07:00
|
|
|
|
private const string PremiumPlanIdAppStore = "premium-annually-app";
|
2022-08-29 16:06:55 -04:00
|
|
|
|
|
2017-04-26 14:29:25 -04:00
|
|
|
|
private readonly BillingSettings _billingSettings;
|
2017-03-18 18:52:44 -04:00
|
|
|
|
private readonly IWebHostEnvironment _hostingEnvironment;
|
2017-04-26 16:14:15 -04:00
|
|
|
|
private readonly IOrganizationService _organizationService;
|
2017-03-18 18:52:44 -04:00
|
|
|
|
private readonly IValidateSponsorshipCommand _validateSponsorshipCommand;
|
2022-05-10 17:12:09 -04:00
|
|
|
|
private readonly IOrganizationSponsorshipRenewCommand _organizationSponsorshipRenewCommand;
|
2018-05-11 08:29:23 -04:00
|
|
|
|
private readonly IOrganizationRepository _organizationRepository;
|
2019-02-01 23:04:51 -05:00
|
|
|
|
private readonly ITransactionRepository _transactionRepository;
|
2017-07-25 09:04:22 -04:00
|
|
|
|
private readonly IUserService _userService;
|
2019-09-23 09:03:18 -04:00
|
|
|
|
private readonly IAppleIapService _appleIapService;
|
2019-02-22 09:31:05 -05:00
|
|
|
|
private readonly IMailService _mailService;
|
2017-03-18 18:52:44 -04:00
|
|
|
|
private readonly ILogger<StripeController> _logger;
|
2019-02-03 00:00:21 -05:00
|
|
|
|
private readonly Braintree.BraintreeGateway _btGateway;
|
2020-07-15 12:38:45 -04:00
|
|
|
|
private readonly IReferenceEventService _referenceEventService;
|
2021-03-24 15:27:16 -04:00
|
|
|
|
private readonly ITaxRateRepository _taxRateRepository;
|
|
|
|
|
|
private readonly IUserRepository _userRepository;
|
2022-08-29 16:06:55 -04:00
|
|
|
|
|
2017-03-18 18:52:44 -04:00
|
|
|
|
public StripeController(
|
|
|
|
|
|
GlobalSettings globalSettings,
|
2019-02-03 00:00:21 -05:00
|
|
|
|
IOptions<BillingSettings> billingSettings,
|
|
|
|
|
|
IWebHostEnvironment hostingEnvironment,
|
|
|
|
|
|
IOrganizationService organizationService,
|
|
|
|
|
|
IValidateSponsorshipCommand validateSponsorshipCommand,
|
2022-05-10 17:12:09 -04:00
|
|
|
|
IOrganizationSponsorshipRenewCommand organizationSponsorshipRenewCommand,
|
2018-05-11 08:29:23 -04:00
|
|
|
|
IOrganizationRepository organizationRepository,
|
2019-02-03 00:00:21 -05:00
|
|
|
|
ITransactionRepository transactionRepository,
|
2018-05-11 08:29:23 -04:00
|
|
|
|
IUserService userService,
|
2019-09-23 09:03:18 -04:00
|
|
|
|
IAppleIapService appleIapService,
|
2019-02-03 00:00:21 -05:00
|
|
|
|
IMailService mailService,
|
|
|
|
|
|
IReferenceEventService referenceEventService,
|
|
|
|
|
|
ILogger<StripeController> logger,
|
2021-03-24 15:27:16 -04:00
|
|
|
|
ITaxRateRepository taxRateRepository,
|
|
|
|
|
|
IUserRepository userRepository)
|
2017-03-18 18:52:44 -04:00
|
|
|
|
{
|
2017-04-26 14:29:25 -04:00
|
|
|
|
_billingSettings = billingSettings?.Value;
|
2020-01-10 08:47:58 -05:00
|
|
|
|
_hostingEnvironment = hostingEnvironment;
|
2017-04-26 16:14:15 -04:00
|
|
|
|
_organizationService = organizationService;
|
2022-05-10 17:12:09 -04:00
|
|
|
|
_validateSponsorshipCommand = validateSponsorshipCommand;
|
|
|
|
|
|
_organizationSponsorshipRenewCommand = organizationSponsorshipRenewCommand;
|
2018-05-11 08:29:23 -04:00
|
|
|
|
_organizationRepository = organizationRepository;
|
2019-02-01 23:04:51 -05:00
|
|
|
|
_transactionRepository = transactionRepository;
|
2017-07-25 09:04:22 -04:00
|
|
|
|
_userService = userService;
|
2019-09-23 09:03:18 -04:00
|
|
|
|
_appleIapService = appleIapService;
|
2019-02-03 00:00:21 -05:00
|
|
|
|
_mailService = mailService;
|
|
|
|
|
|
_referenceEventService = referenceEventService;
|
2021-03-24 15:27:16 -04:00
|
|
|
|
_taxRateRepository = taxRateRepository;
|
|
|
|
|
|
_userRepository = userRepository;
|
2019-02-03 00:00:21 -05:00
|
|
|
|
_logger = logger;
|
|
|
|
|
|
_btGateway = new Braintree.BraintreeGateway
|
2022-08-29 16:06:55 -04:00
|
|
|
|
{
|
2017-08-12 22:30:44 -04:00
|
|
|
|
Environment = globalSettings.Braintree.Production ?
|
2021-11-08 15:55:42 -05:00
|
|
|
|
Braintree.Environment.PRODUCTION : Braintree.Environment.SANDBOX,
|
|
|
|
|
|
MerchantId = globalSettings.Braintree.MerchantId,
|
|
|
|
|
|
PublicKey = globalSettings.Braintree.PublicKey,
|
2022-08-09 09:32:18 -04:00
|
|
|
|
PrivateKey = globalSettings.Braintree.PrivateKey
|
|
|
|
|
|
};
|
2017-08-12 22:30:44 -04:00
|
|
|
|
}
|
|
|
|
|
|
|
2017-03-18 18:52:44 -04:00
|
|
|
|
[HttpPost("webhook")]
|
2020-03-27 14:36:37 -04:00
|
|
|
|
public async Task<IActionResult> PostWebhook([FromQuery] string key)
|
2022-08-29 16:06:55 -04:00
|
|
|
|
{
|
2019-02-22 09:31:05 -05:00
|
|
|
|
if (!CoreHelpers.FixedTimeEquals(key, _billingSettings.StripeWebhookKey))
|
2017-04-26 16:14:15 -04:00
|
|
|
|
{
|
|
|
|
|
|
return new BadRequestResult();
|
|
|
|
|
|
}
|
|
|
|
|
|
|
2019-01-29 14:41:37 -05:00
|
|
|
|
Stripe.Event parsedEvent;
|
2020-03-27 14:36:37 -04:00
|
|
|
|
using (var sr = new StreamReader(HttpContext.Request.Body))
|
2022-08-29 15:53:48 -04:00
|
|
|
|
{
|
2020-03-27 14:36:37 -04:00
|
|
|
|
var json = await sr.ReadToEndAsync();
|
|
|
|
|
|
parsedEvent = EventUtility.ConstructEvent(json, Request.Headers["Stripe-Signature"],
|
2019-02-22 09:31:05 -05:00
|
|
|
|
_billingSettings.StripeWebhookSecret,
|
|
|
|
|
|
throwOnApiVersionMismatch: _billingSettings.StripeEventParseThrowMismatch);
|
2017-04-26 16:14:15 -04:00
|
|
|
|
}
|
|
|
|
|
|
|
2022-05-31 10:55:56 -04:00
|
|
|
|
if (string.IsNullOrWhiteSpace(parsedEvent?.Id))
|
2022-08-29 15:53:48 -04:00
|
|
|
|
{
|
2022-05-31 10:55:56 -04:00
|
|
|
|
_logger.LogWarning("No event id.");
|
|
|
|
|
|
return new BadRequestResult();
|
2022-08-29 15:53:48 -04:00
|
|
|
|
}
|
2018-04-05 21:56:36 -04:00
|
|
|
|
|
2019-08-20 11:09:02 -04:00
|
|
|
|
if (_hostingEnvironment.IsProduction() && !parsedEvent.Livemode)
|
2022-08-29 15:53:48 -04:00
|
|
|
|
{
|
2017-08-12 22:16:42 -04:00
|
|
|
|
_logger.LogWarning("Getting test events in production.");
|
|
|
|
|
|
return new BadRequestResult();
|
2022-08-29 15:53:48 -04:00
|
|
|
|
}
|
2017-08-12 22:16:42 -04:00
|
|
|
|
|
2018-04-05 21:56:36 -04:00
|
|
|
|
var subDeleted = parsedEvent.Type.Equals(HandledStripeWebhook.SubscriptionDeleted);
|
2019-08-12 10:45:05 -04:00
|
|
|
|
var subUpdated = parsedEvent.Type.Equals(HandledStripeWebhook.SubscriptionUpdated);
|
2018-04-05 21:56:36 -04:00
|
|
|
|
|
2020-03-27 14:36:37 -04:00
|
|
|
|
if (subDeleted || subUpdated)
|
2022-08-29 14:53:16 -04:00
|
|
|
|
{
|
2020-03-27 14:36:37 -04:00
|
|
|
|
var subscription = await GetSubscriptionAsync(parsedEvent, true);
|
|
|
|
|
|
var ids = GetIdsFromMetaData(subscription.Metadata);
|
2023-04-11 17:09:38 +01:00
|
|
|
|
var organizationId = ids.Item1 ?? Guid.Empty;
|
|
|
|
|
|
var userId = ids.Item2 ?? Guid.Empty;
|
2018-04-05 21:56:36 -04:00
|
|
|
|
var subCanceled = subDeleted && subscription.Status == "canceled";
|
|
|
|
|
|
var subUnpaid = subUpdated && subscription.Status == "unpaid";
|
2023-04-11 17:09:38 +01:00
|
|
|
|
var subActive = subUpdated && subscription.Status == "active";
|
2018-04-05 21:56:36 -04:00
|
|
|
|
var subIncompleteExpired = subUpdated && subscription.Status == "incomplete_expired";
|
2022-08-29 15:53:48 -04:00
|
|
|
|
|
2020-03-27 14:36:37 -04:00
|
|
|
|
if (subCanceled || subUnpaid || subIncompleteExpired)
|
2022-08-29 16:06:55 -04:00
|
|
|
|
{
|
|
|
|
|
|
// org
|
2023-04-11 17:09:38 +01:00
|
|
|
|
if (organizationId != null && organizationId != Guid.Empty)
|
2017-08-12 22:16:42 -04:00
|
|
|
|
{
|
2023-04-11 17:09:38 +01:00
|
|
|
|
await _organizationService.DisableAsync(organizationId, subscription.CurrentPeriodEnd);
|
2017-08-12 22:16:42 -04:00
|
|
|
|
}
|
2022-08-29 16:06:55 -04:00
|
|
|
|
// user
|
2023-04-11 17:09:38 +01:00
|
|
|
|
else if (userId != null && userId != Guid.Empty)
|
|
|
|
|
|
{
|
|
|
|
|
|
await _userService.DisablePremiumAsync(userId, subscription.CurrentPeriodEnd);
|
|
|
|
|
|
}
|
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
if (subActive)
|
|
|
|
|
|
{
|
|
|
|
|
|
|
|
|
|
|
|
if (organizationId != null && organizationId != Guid.Empty)
|
2017-04-26 16:14:15 -04:00
|
|
|
|
{
|
2023-04-11 17:09:38 +01:00
|
|
|
|
await _organizationService.EnableAsync(organizationId);
|
|
|
|
|
|
}
|
|
|
|
|
|
else if (userId != null && userId != Guid.Empty)
|
|
|
|
|
|
{
|
|
|
|
|
|
await _userService.EnablePremiumAsync(userId,
|
|
|
|
|
|
subscription.CurrentPeriodEnd);
|
2017-04-26 16:14:15 -04:00
|
|
|
|
}
|
|
|
|
|
|
}
|
2022-08-29 15:53:48 -04:00
|
|
|
|
|
2019-08-09 23:56:26 -04:00
|
|
|
|
if (subUpdated)
|
2022-08-29 16:06:55 -04:00
|
|
|
|
{
|
2018-04-05 21:56:36 -04:00
|
|
|
|
// org
|
2023-04-11 17:09:38 +01:00
|
|
|
|
if (organizationId != null && organizationId != Guid.Empty)
|
2018-04-05 21:56:36 -04:00
|
|
|
|
{
|
2023-04-11 17:09:38 +01:00
|
|
|
|
await _organizationService.UpdateExpirationDateAsync(organizationId,
|
Families for Enterprise (#1714)
* Create common test infrastructure project
* Add helpers to further type PlanTypes
* Enable testing of ASP.net MVC controllers
Controller properties have all kinds of validations in the background.
In general, we don't user properties on our Controllers, so the easiest
way to allow for Autofixture-based testing of our Controllers is to just
omit setting all properties on them.
* Workaround for broken MemberAutoDataAttribute
https://github.com/AutoFixture/AutoFixture/pull/1164 shows that only
the first test case is pulled for this attribute.
This is a workaround that populates the provided parameters, left to
right, using AutoFixture to populate any remaining.
* WIP: Organization sponsorship flow
* Add Attribute to use the Bit Autodata dependency chain
BitAutoDataAttribute is used to mark a Theory as autopopulating
parameters.
Extract common attribute methods to to a helper class. Cannot
inherit a common base, since both require inheriting from different
Xunit base classes to work.
* WIP: scaffolding for families for enterprise sponsorship flow
* Fix broken tests
* Create sponsorship offer (#1688)
* Initial db work (#1687)
* Add organization sponsorship databases to all providers
* Generalize create and update for database, specialize in code
* Add PlanSponsorshipType to db model
* Write valid json for test entries
* Initial scaffolding of emails (#1686)
* Initial scaffolding of emails
* Work on adding models for FamilyForEnterprise emails
* Switch verbage
* Put preliminary copy in emails
* Skip test
* Families for enterprise/stripe integrations (#1699)
* Add PlanSponsorshipType to static store
* Add sponsorship type to token and creates sponsorship
* PascalCase properties
* Require sponsorship for remove
* Create subscription sponsorship helper class
* Handle Sponsored subscription changes
* Add sponsorship id to subscription metadata
* Make sponsoring references nullable
This state indicates that a sponsorship has lapsed, but was not able to
be reverted for billing reasons
* WIP: Validate and remove subscriptions
* Update sponsorships on organization and org user delete
* Add friendly name to organization sponsorship
* Add sponsorship available boolean to orgDetails
* Add sponsorship service to DI
* Use userId to find org users
* Send f4e offer email
* Simplify names of f4e mail messages
* Fix Stripe org default tax rates
* Universal sponsorship redeem api
* Populate user in current context
* Add product type to organization details
* Use upgrade path to change sponsorship
Sponsorships need to be annual to match the GB add-on charge rate
* Use organization and auth to find organization sponsorship
* Add resend sponsorship offer api endpoint
* Fix double email send
* Fix sponsorship upgrade options
* Add is sponsored item to subscription response
* Add sponsorship validation to upcoming invoice webhook
* Add sponsorship validation to upcoming invoice webhook
* Fix organization delete sponsorship hooks
* Test org sponsorship service
* Fix sproc
* Create common test infrastructure project
* Add helpers to further type PlanTypes
* Enable testing of ASP.net MVC controllers
Controller properties have all kinds of validations in the background.
In general, we don't user properties on our Controllers, so the easiest
way to allow for Autofixture-based testing of our Controllers is to just
omit setting all properties on them.
* Workaround for broken MemberAutoDataAttribute
https://github.com/AutoFixture/AutoFixture/pull/1164 shows that only
the first test case is pulled for this attribute.
This is a workaround that populates the provided parameters, left to
right, using AutoFixture to populate any remaining.
* WIP: Organization sponsorship flow
* Add Attribute to use the Bit Autodata dependency chain
BitAutoDataAttribute is used to mark a Theory as autopopulating
parameters.
Extract common attribute methods to to a helper class. Cannot
inherit a common base, since both require inheriting from different
Xunit base classes to work.
* WIP: scaffolding for families for enterprise sponsorship flow
* Fix broken tests
* Create sponsorship offer (#1688)
* Initial db work (#1687)
* Add organization sponsorship databases to all providers
* Generalize create and update for database, specialize in code
* Add PlanSponsorshipType to db model
* Write valid json for test entries
* Initial scaffolding of emails (#1686)
* Initial scaffolding of emails
* Work on adding models for FamilyForEnterprise emails
* Switch verbage
* Put preliminary copy in emails
* Skip test
* Families for enterprise/stripe integrations (#1699)
* Add PlanSponsorshipType to static store
* Add sponsorship type to token and creates sponsorship
* PascalCase properties
* Require sponsorship for remove
* Create subscription sponsorship helper class
* Handle Sponsored subscription changes
* Add sponsorship id to subscription metadata
* Make sponsoring references nullable
This state indicates that a sponsorship has lapsed, but was not able to
be reverted for billing reasons
* WIP: Validate and remove subscriptions
* Update sponsorships on organization and org user delete
* Add friendly name to organization sponsorship
* Add sponsorship available boolean to orgDetails
* Add sponsorship service to DI
* Use userId to find org users
* Send f4e offer email
* Simplify names of f4e mail messages
* Fix Stripe org default tax rates
* Universal sponsorship redeem api
* Populate user in current context
* Add product type to organization details
* Use upgrade path to change sponsorship
Sponsorships need to be annual to match the GB add-on charge rate
* Use organization and auth to find organization sponsorship
* Add resend sponsorship offer api endpoint
* Fix double email send
* Fix sponsorship upgrade options
* Add is sponsored item to subscription response
* Add sponsorship validation to upcoming invoice webhook
* Add sponsorship validation to upcoming invoice webhook
* Fix organization delete sponsorship hooks
* Test org sponsorship service
* Fix sproc
* Fix build error
* Update emails
* Fix tests
* Skip local test
* Add newline
* Fix stripe subscription update
* Finish emails
* Skip test
* Fix unit tests
* Remove unused variable
* Fix unit tests
* Switch to handlebars ifs
* Remove ending email
* Remove reconfirmation template
* Switch naming convention
* Switch naming convention
* Fix migration
* Update copy and links
* Switch to using Guid in the method
* Remove unneeded css styles
* Add sql files to Sql.sqlproj
* Removed old comments
* Made name more verbose
* Fix SQL error
* Move unit tests to service
* Fix sp
* Revert "Move unit tests to service"
This reverts commit 1185bf3ec8ca36ccd75717ed2463adf8885159a6.
* Do repository validation in service layer
* Fix tests
* Fix merge conflicts and remove TODO
* Remove unneeded models
* Fix spacing and formatting
* Switch Org -> Organization
* Remove single use variables
* Switch method name
* Fix Controller
* Switch to obfuscating email
* Fix unit tests
Co-authored-by: Justin Baur <admin@justinbaur.com>
2021-11-19 16:25:06 -06:00
|
|
|
|
subscription.CurrentPeriodEnd);
|
2022-05-10 17:12:09 -04:00
|
|
|
|
if (IsSponsoredSubscription(subscription))
|
Families for Enterprise (#1714)
* Create common test infrastructure project
* Add helpers to further type PlanTypes
* Enable testing of ASP.net MVC controllers
Controller properties have all kinds of validations in the background.
In general, we don't user properties on our Controllers, so the easiest
way to allow for Autofixture-based testing of our Controllers is to just
omit setting all properties on them.
* Workaround for broken MemberAutoDataAttribute
https://github.com/AutoFixture/AutoFixture/pull/1164 shows that only
the first test case is pulled for this attribute.
This is a workaround that populates the provided parameters, left to
right, using AutoFixture to populate any remaining.
* WIP: Organization sponsorship flow
* Add Attribute to use the Bit Autodata dependency chain
BitAutoDataAttribute is used to mark a Theory as autopopulating
parameters.
Extract common attribute methods to to a helper class. Cannot
inherit a common base, since both require inheriting from different
Xunit base classes to work.
* WIP: scaffolding for families for enterprise sponsorship flow
* Fix broken tests
* Create sponsorship offer (#1688)
* Initial db work (#1687)
* Add organization sponsorship databases to all providers
* Generalize create and update for database, specialize in code
* Add PlanSponsorshipType to db model
* Write valid json for test entries
* Initial scaffolding of emails (#1686)
* Initial scaffolding of emails
* Work on adding models for FamilyForEnterprise emails
* Switch verbage
* Put preliminary copy in emails
* Skip test
* Families for enterprise/stripe integrations (#1699)
* Add PlanSponsorshipType to static store
* Add sponsorship type to token and creates sponsorship
* PascalCase properties
* Require sponsorship for remove
* Create subscription sponsorship helper class
* Handle Sponsored subscription changes
* Add sponsorship id to subscription metadata
* Make sponsoring references nullable
This state indicates that a sponsorship has lapsed, but was not able to
be reverted for billing reasons
* WIP: Validate and remove subscriptions
* Update sponsorships on organization and org user delete
* Add friendly name to organization sponsorship
* Add sponsorship available boolean to orgDetails
* Add sponsorship service to DI
* Use userId to find org users
* Send f4e offer email
* Simplify names of f4e mail messages
* Fix Stripe org default tax rates
* Universal sponsorship redeem api
* Populate user in current context
* Add product type to organization details
* Use upgrade path to change sponsorship
Sponsorships need to be annual to match the GB add-on charge rate
* Use organization and auth to find organization sponsorship
* Add resend sponsorship offer api endpoint
* Fix double email send
* Fix sponsorship upgrade options
* Add is sponsored item to subscription response
* Add sponsorship validation to upcoming invoice webhook
* Add sponsorship validation to upcoming invoice webhook
* Fix organization delete sponsorship hooks
* Test org sponsorship service
* Fix sproc
* Create common test infrastructure project
* Add helpers to further type PlanTypes
* Enable testing of ASP.net MVC controllers
Controller properties have all kinds of validations in the background.
In general, we don't user properties on our Controllers, so the easiest
way to allow for Autofixture-based testing of our Controllers is to just
omit setting all properties on them.
* Workaround for broken MemberAutoDataAttribute
https://github.com/AutoFixture/AutoFixture/pull/1164 shows that only
the first test case is pulled for this attribute.
This is a workaround that populates the provided parameters, left to
right, using AutoFixture to populate any remaining.
* WIP: Organization sponsorship flow
* Add Attribute to use the Bit Autodata dependency chain
BitAutoDataAttribute is used to mark a Theory as autopopulating
parameters.
Extract common attribute methods to to a helper class. Cannot
inherit a common base, since both require inheriting from different
Xunit base classes to work.
* WIP: scaffolding for families for enterprise sponsorship flow
* Fix broken tests
* Create sponsorship offer (#1688)
* Initial db work (#1687)
* Add organization sponsorship databases to all providers
* Generalize create and update for database, specialize in code
* Add PlanSponsorshipType to db model
* Write valid json for test entries
* Initial scaffolding of emails (#1686)
* Initial scaffolding of emails
* Work on adding models for FamilyForEnterprise emails
* Switch verbage
* Put preliminary copy in emails
* Skip test
* Families for enterprise/stripe integrations (#1699)
* Add PlanSponsorshipType to static store
* Add sponsorship type to token and creates sponsorship
* PascalCase properties
* Require sponsorship for remove
* Create subscription sponsorship helper class
* Handle Sponsored subscription changes
* Add sponsorship id to subscription metadata
* Make sponsoring references nullable
This state indicates that a sponsorship has lapsed, but was not able to
be reverted for billing reasons
* WIP: Validate and remove subscriptions
* Update sponsorships on organization and org user delete
* Add friendly name to organization sponsorship
* Add sponsorship available boolean to orgDetails
* Add sponsorship service to DI
* Use userId to find org users
* Send f4e offer email
* Simplify names of f4e mail messages
* Fix Stripe org default tax rates
* Universal sponsorship redeem api
* Populate user in current context
* Add product type to organization details
* Use upgrade path to change sponsorship
Sponsorships need to be annual to match the GB add-on charge rate
* Use organization and auth to find organization sponsorship
* Add resend sponsorship offer api endpoint
* Fix double email send
* Fix sponsorship upgrade options
* Add is sponsored item to subscription response
* Add sponsorship validation to upcoming invoice webhook
* Add sponsorship validation to upcoming invoice webhook
* Fix organization delete sponsorship hooks
* Test org sponsorship service
* Fix sproc
* Fix build error
* Update emails
* Fix tests
* Skip local test
* Add newline
* Fix stripe subscription update
* Finish emails
* Skip test
* Fix unit tests
* Remove unused variable
* Fix unit tests
* Switch to handlebars ifs
* Remove ending email
* Remove reconfirmation template
* Switch naming convention
* Switch naming convention
* Fix migration
* Update copy and links
* Switch to using Guid in the method
* Remove unneeded css styles
* Add sql files to Sql.sqlproj
* Removed old comments
* Made name more verbose
* Fix SQL error
* Move unit tests to service
* Fix sp
* Revert "Move unit tests to service"
This reverts commit 1185bf3ec8ca36ccd75717ed2463adf8885159a6.
* Do repository validation in service layer
* Fix tests
* Fix merge conflicts and remove TODO
* Remove unneeded models
* Fix spacing and formatting
* Switch Org -> Organization
* Remove single use variables
* Switch method name
* Fix Controller
* Switch to obfuscating email
* Fix unit tests
Co-authored-by: Justin Baur <admin@justinbaur.com>
2021-11-19 16:25:06 -06:00
|
|
|
|
{
|
2023-04-11 17:09:38 +01:00
|
|
|
|
await _organizationSponsorshipRenewCommand.UpdateExpirationDateAsync(organizationId, subscription.CurrentPeriodEnd);
|
2018-05-11 08:29:23 -04:00
|
|
|
|
}
|
2018-04-05 21:56:36 -04:00
|
|
|
|
}
|
|
|
|
|
|
// user
|
2023-04-11 17:09:38 +01:00
|
|
|
|
else if (userId != null && userId != Guid.Empty)
|
2018-04-05 21:56:36 -04:00
|
|
|
|
{
|
2023-04-11 17:09:38 +01:00
|
|
|
|
await _userService.UpdatePremiumExpirationAsync(userId,
|
2018-04-05 21:56:36 -04:00
|
|
|
|
subscription.CurrentPeriodEnd);
|
2022-08-29 16:06:55 -04:00
|
|
|
|
}
|
|
|
|
|
|
}
|
|
|
|
|
|
}
|
2018-05-11 08:29:23 -04:00
|
|
|
|
else if (parsedEvent.Type.Equals(HandledStripeWebhook.UpcomingInvoice))
|
2022-08-29 16:06:55 -04:00
|
|
|
|
{
|
2019-08-20 11:09:02 -04:00
|
|
|
|
var invoice = await GetInvoiceAsync(parsedEvent);
|
2018-05-11 08:29:23 -04:00
|
|
|
|
var subscriptionService = new SubscriptionService();
|
|
|
|
|
|
var subscription = await subscriptionService.GetAsync(invoice.SubscriptionId);
|
|
|
|
|
|
if (subscription == null)
|
|
|
|
|
|
{
|
2019-02-28 20:49:39 -05:00
|
|
|
|
throw new Exception("Invoice subscription is null. " + invoice.Id);
|
2022-08-29 16:06:55 -04:00
|
|
|
|
}
|
|
|
|
|
|
|
2018-05-11 08:29:23 -04:00
|
|
|
|
subscription = await VerifyCorrectTaxRateForCharge(invoice, subscription);
|
2022-08-29 16:06:55 -04:00
|
|
|
|
|
2018-05-11 08:29:23 -04:00
|
|
|
|
string email = null;
|
2019-08-09 23:56:26 -04:00
|
|
|
|
var ids = GetIdsFromMetaData(subscription.Metadata);
|
2022-08-29 16:06:55 -04:00
|
|
|
|
// org
|
2020-03-27 14:36:37 -04:00
|
|
|
|
if (ids.Item1.HasValue)
|
2022-08-29 16:06:55 -04:00
|
|
|
|
{
|
2019-02-16 22:08:04 -05:00
|
|
|
|
// sponsored org
|
2022-05-10 17:12:09 -04:00
|
|
|
|
if (IsSponsoredSubscription(subscription))
|
2022-08-29 16:06:55 -04:00
|
|
|
|
{
|
2018-05-11 08:29:23 -04:00
|
|
|
|
await _validateSponsorshipCommand.ValidateSponsorshipAsync(ids.Item1.Value);
|
|
|
|
|
|
}
|
|
|
|
|
|
|
2020-03-27 14:36:37 -04:00
|
|
|
|
var org = await _organizationRepository.GetByIdAsync(ids.Item1.Value);
|
|
|
|
|
|
if (org != null && OrgPlanForInvoiceNotifications(org))
|
2018-05-11 08:29:23 -04:00
|
|
|
|
{
|
|
|
|
|
|
email = org.BillingEmail;
|
2018-04-05 21:56:36 -04:00
|
|
|
|
}
|
|
|
|
|
|
}
|
2022-05-31 10:55:56 -04:00
|
|
|
|
// user
|
|
|
|
|
|
else if (ids.Item2.HasValue)
|
2019-02-01 23:04:51 -05:00
|
|
|
|
{
|
2019-02-15 16:18:53 -05:00
|
|
|
|
var user = await _userService.GetUserByIdAsync(ids.Item2.Value);
|
2020-03-27 14:36:37 -04:00
|
|
|
|
if (user.Premium)
|
2019-02-01 23:04:51 -05:00
|
|
|
|
{
|
2019-02-22 09:31:05 -05:00
|
|
|
|
email = user.Email;
|
2019-02-01 23:04:51 -05:00
|
|
|
|
}
|
2022-08-29 16:06:55 -04:00
|
|
|
|
}
|
2019-02-01 23:04:51 -05:00
|
|
|
|
|
2019-02-03 00:00:21 -05:00
|
|
|
|
if (!string.IsNullOrWhiteSpace(email) && invoice.NextPaymentAttempt.HasValue)
|
2022-08-29 16:06:55 -04:00
|
|
|
|
{
|
2019-01-29 14:41:37 -05:00
|
|
|
|
var items = invoice.Lines.Select(i => i.Description).ToList();
|
|
|
|
|
|
await _mailService.SendInvoiceUpcomingAsync(email, invoice.AmountDue / 100M,
|
|
|
|
|
|
invoice.NextPaymentAttempt.Value, items, true);
|
2022-08-29 16:06:55 -04:00
|
|
|
|
}
|
|
|
|
|
|
}
|
2019-01-29 14:41:37 -05:00
|
|
|
|
else if (parsedEvent.Type.Equals(HandledStripeWebhook.ChargeSucceeded))
|
2022-08-29 16:06:55 -04:00
|
|
|
|
{
|
2019-02-15 16:18:53 -05:00
|
|
|
|
var charge = await GetChargeAsync(parsedEvent);
|
2019-01-29 14:41:37 -05:00
|
|
|
|
var chargeTransaction = await _transactionRepository.GetByGatewayIdAsync(
|
2019-02-15 16:18:53 -05:00
|
|
|
|
GatewayType.Stripe, charge.Id);
|
2019-01-29 14:41:37 -05:00
|
|
|
|
if (chargeTransaction != null)
|
2022-08-29 16:06:55 -04:00
|
|
|
|
{
|
2019-01-29 14:41:37 -05:00
|
|
|
|
_logger.LogWarning("Charge success already processed. " + charge.Id);
|
|
|
|
|
|
return new OkResult();
|
2022-08-29 16:06:55 -04:00
|
|
|
|
}
|
2022-08-29 14:53:16 -04:00
|
|
|
|
|
2019-02-15 16:18:53 -05:00
|
|
|
|
Tuple<Guid?, Guid?> ids = null;
|
2019-08-20 11:09:02 -04:00
|
|
|
|
Subscription subscription = null;
|
2018-05-11 08:29:23 -04:00
|
|
|
|
var subscriptionService = new SubscriptionService();
|
2022-08-29 16:06:55 -04:00
|
|
|
|
|
2020-03-27 14:36:37 -04:00
|
|
|
|
if (charge.InvoiceId != null)
|
2022-08-29 16:06:55 -04:00
|
|
|
|
{
|
2019-02-01 23:04:51 -05:00
|
|
|
|
var invoiceService = new InvoiceService();
|
|
|
|
|
|
var invoice = await invoiceService.GetAsync(charge.InvoiceId);
|
2020-03-27 14:36:37 -04:00
|
|
|
|
if (invoice?.SubscriptionId != null)
|
2019-02-01 23:04:51 -05:00
|
|
|
|
{
|
2019-02-15 16:18:53 -05:00
|
|
|
|
subscription = await subscriptionService.GetAsync(invoice.SubscriptionId);
|
|
|
|
|
|
ids = GetIdsFromMetaData(subscription?.Metadata);
|
|
|
|
|
|
}
|
2022-08-29 16:06:55 -04:00
|
|
|
|
}
|
2019-02-01 23:04:51 -05:00
|
|
|
|
|
2020-03-27 14:36:37 -04:00
|
|
|
|
if (subscription == null || ids == null || (ids.Item1.HasValue && ids.Item2.HasValue))
|
2022-08-29 16:06:55 -04:00
|
|
|
|
{
|
2019-02-15 16:18:53 -05:00
|
|
|
|
var subscriptions = await subscriptionService.ListAsync(new SubscriptionListOptions
|
|
|
|
|
|
{
|
2020-05-13 09:58:17 -04:00
|
|
|
|
Customer = charge.CustomerId
|
2019-02-15 16:18:53 -05:00
|
|
|
|
});
|
2020-03-27 14:36:37 -04:00
|
|
|
|
foreach (var sub in subscriptions)
|
2022-08-29 16:06:55 -04:00
|
|
|
|
{
|
2020-03-27 14:36:37 -04:00
|
|
|
|
if (sub.Status != "canceled" && sub.Status != "incomplete_expired")
|
2019-02-01 23:04:51 -05:00
|
|
|
|
{
|
2020-03-27 14:36:37 -04:00
|
|
|
|
ids = GetIdsFromMetaData(sub.Metadata);
|
|
|
|
|
|
if (ids.Item1.HasValue || ids.Item2.HasValue)
|
2019-02-01 23:04:51 -05:00
|
|
|
|
{
|
2019-02-16 16:08:12 -05:00
|
|
|
|
subscription = sub;
|
|
|
|
|
|
break;
|
2019-02-01 23:04:51 -05:00
|
|
|
|
}
|
2019-02-15 16:18:53 -05:00
|
|
|
|
}
|
|
|
|
|
|
}
|
2022-08-29 16:06:55 -04:00
|
|
|
|
}
|
2019-02-15 16:18:53 -05:00
|
|
|
|
|
2019-02-16 22:08:04 -05:00
|
|
|
|
if (!ids.Item1.HasValue && !ids.Item2.HasValue)
|
2022-08-29 15:53:48 -04:00
|
|
|
|
{
|
2019-02-16 22:08:04 -05:00
|
|
|
|
_logger.LogWarning("Charge success has no subscriber ids. " + charge.Id);
|
|
|
|
|
|
return new BadRequestResult();
|
|
|
|
|
|
}
|
2022-08-29 14:53:16 -04:00
|
|
|
|
|
2019-02-16 22:08:04 -05:00
|
|
|
|
var tx = new Transaction
|
2022-08-29 15:53:48 -04:00
|
|
|
|
{
|
2020-03-27 14:36:37 -04:00
|
|
|
|
Amount = charge.Amount / 100M,
|
|
|
|
|
|
CreationDate = charge.Created,
|
|
|
|
|
|
OrganizationId = ids.Item1,
|
|
|
|
|
|
UserId = ids.Item2,
|
2019-02-16 22:08:04 -05:00
|
|
|
|
Type = TransactionType.Charge,
|
|
|
|
|
|
Gateway = GatewayType.Stripe,
|
2019-02-15 16:18:53 -05:00
|
|
|
|
GatewayId = charge.Id
|
2022-08-29 14:53:16 -04:00
|
|
|
|
};
|
2022-08-29 16:06:55 -04:00
|
|
|
|
|
2020-03-27 14:36:37 -04:00
|
|
|
|
if (charge.Source != null && charge.Source is Card card)
|
2022-08-29 16:06:55 -04:00
|
|
|
|
{
|
2019-02-16 22:08:04 -05:00
|
|
|
|
tx.PaymentMethodType = PaymentMethodType.Card;
|
|
|
|
|
|
tx.Details = $"{card.Brand}, *{card.Last4}";
|
2022-08-29 16:06:55 -04:00
|
|
|
|
}
|
2020-03-27 14:36:37 -04:00
|
|
|
|
else if (charge.Source != null && charge.Source is BankAccount bankAccount)
|
2022-08-29 16:06:55 -04:00
|
|
|
|
{
|
2019-02-16 22:08:04 -05:00
|
|
|
|
tx.PaymentMethodType = PaymentMethodType.BankAccount;
|
|
|
|
|
|
tx.Details = $"{bankAccount.BankName}, *{bankAccount.Last4}";
|
2022-08-29 16:06:55 -04:00
|
|
|
|
}
|
2020-03-27 14:36:37 -04:00
|
|
|
|
else if (charge.Source != null && charge.Source is Source source)
|
2022-08-29 16:06:55 -04:00
|
|
|
|
{
|
2020-03-27 14:36:37 -04:00
|
|
|
|
if (source.Card != null)
|
2019-02-16 22:08:04 -05:00
|
|
|
|
{
|
|
|
|
|
|
tx.PaymentMethodType = PaymentMethodType.Card;
|
|
|
|
|
|
tx.Details = $"{source.Card.Brand}, *{source.Card.Last4}";
|
|
|
|
|
|
}
|
2020-03-27 14:36:37 -04:00
|
|
|
|
else if (source.AchDebit != null)
|
2019-02-16 22:08:04 -05:00
|
|
|
|
{
|
|
|
|
|
|
tx.PaymentMethodType = PaymentMethodType.BankAccount;
|
|
|
|
|
|
tx.Details = $"{source.AchDebit.BankName}, *{source.AchDebit.Last4}";
|
|
|
|
|
|
}
|
2020-03-27 14:36:37 -04:00
|
|
|
|
else if (source.AchCreditTransfer != null)
|
2019-02-27 10:11:45 -05:00
|
|
|
|
{
|
|
|
|
|
|
tx.PaymentMethodType = PaymentMethodType.BankAccount;
|
|
|
|
|
|
tx.Details = $"ACH => {source.AchCreditTransfer.BankName}, " +
|
|
|
|
|
|
$"{source.AchCreditTransfer.AccountNumber}";
|
|
|
|
|
|
}
|
2022-08-29 16:06:55 -04:00
|
|
|
|
}
|
2020-03-27 14:36:37 -04:00
|
|
|
|
else if (charge.PaymentMethodDetails != null)
|
2022-08-29 16:06:55 -04:00
|
|
|
|
{
|
2020-03-27 14:36:37 -04:00
|
|
|
|
if (charge.PaymentMethodDetails.Card != null)
|
2019-09-03 17:00:05 -04:00
|
|
|
|
{
|
|
|
|
|
|
tx.PaymentMethodType = PaymentMethodType.Card;
|
2019-09-05 20:45:01 -04:00
|
|
|
|
tx.Details = $"{charge.PaymentMethodDetails.Card.Brand?.ToUpperInvariant()}, " +
|
2019-09-03 17:00:05 -04:00
|
|
|
|
$"*{charge.PaymentMethodDetails.Card.Last4}";
|
|
|
|
|
|
}
|
2020-03-27 14:36:37 -04:00
|
|
|
|
else if (charge.PaymentMethodDetails.AchDebit != null)
|
2019-02-16 22:08:04 -05:00
|
|
|
|
{
|
2019-09-03 17:00:05 -04:00
|
|
|
|
tx.PaymentMethodType = PaymentMethodType.BankAccount;
|
|
|
|
|
|
tx.Details = $"{charge.PaymentMethodDetails.AchDebit.BankName}, " +
|
|
|
|
|
|
$"*{charge.PaymentMethodDetails.AchDebit.Last4}";
|
2019-02-16 22:08:04 -05:00
|
|
|
|
}
|
|
|
|
|
|
else if (charge.PaymentMethodDetails.AchCreditTransfer != null)
|
|
|
|
|
|
{
|
|
|
|
|
|
tx.PaymentMethodType = PaymentMethodType.BankAccount;
|
|
|
|
|
|
tx.Details = $"ACH => {charge.PaymentMethodDetails.AchCreditTransfer.BankName}, " +
|
|
|
|
|
|
$"{charge.PaymentMethodDetails.AchCreditTransfer.AccountNumber}";
|
2019-02-01 23:04:51 -05:00
|
|
|
|
}
|
|
|
|
|
|
}
|
2022-08-29 16:06:55 -04:00
|
|
|
|
|
2022-05-31 10:55:56 -04:00
|
|
|
|
if (!tx.PaymentMethodType.HasValue)
|
2022-08-29 16:06:55 -04:00
|
|
|
|
{
|
2022-05-31 10:55:56 -04:00
|
|
|
|
_logger.LogWarning("Charge success from unsupported source/method. " + charge.Id);
|
|
|
|
|
|
return new OkResult();
|
2022-08-29 16:06:55 -04:00
|
|
|
|
}
|
|
|
|
|
|
|
2022-05-31 10:55:56 -04:00
|
|
|
|
try
|
2019-02-01 23:04:51 -05:00
|
|
|
|
{
|
2019-02-01 23:29:12 -05:00
|
|
|
|
await _transactionRepository.CreateAsync(tx);
|
2022-08-29 16:06:55 -04:00
|
|
|
|
}
|
2019-02-16 22:08:04 -05:00
|
|
|
|
// Catch foreign key violations because user/org could have been deleted.
|
2020-03-27 14:36:37 -04:00
|
|
|
|
catch (SqlException e) when (e.Number == 547) { }
|
2022-08-29 16:06:55 -04:00
|
|
|
|
}
|
2022-05-31 10:55:56 -04:00
|
|
|
|
else if (parsedEvent.Type.Equals(HandledStripeWebhook.ChargeRefunded))
|
2022-08-29 16:06:55 -04:00
|
|
|
|
{
|
2019-08-20 11:09:02 -04:00
|
|
|
|
var charge = await GetChargeAsync(parsedEvent);
|
2019-02-01 23:04:51 -05:00
|
|
|
|
var chargeTransaction = await _transactionRepository.GetByGatewayIdAsync(
|
|
|
|
|
|
GatewayType.Stripe, charge.Id);
|
2020-03-27 14:36:37 -04:00
|
|
|
|
if (chargeTransaction == null)
|
2022-08-29 16:06:55 -04:00
|
|
|
|
{
|
2019-02-28 20:49:39 -05:00
|
|
|
|
throw new Exception("Cannot find refunded charge. " + charge.Id);
|
2022-08-29 16:06:55 -04:00
|
|
|
|
}
|
|
|
|
|
|
|
2019-02-01 23:29:12 -05:00
|
|
|
|
var amountRefunded = charge.AmountRefunded / 100M;
|
2022-08-29 16:06:55 -04:00
|
|
|
|
|
2019-02-01 23:29:12 -05:00
|
|
|
|
if (!chargeTransaction.Refunded.GetValueOrDefault() &&
|
|
|
|
|
|
chargeTransaction.RefundedAmount.GetValueOrDefault() < amountRefunded)
|
2022-08-29 16:06:55 -04:00
|
|
|
|
{
|
2019-02-01 23:29:12 -05:00
|
|
|
|
chargeTransaction.RefundedAmount = amountRefunded;
|
2020-03-27 14:36:37 -04:00
|
|
|
|
if (charge.Refunded)
|
2019-02-01 23:04:51 -05:00
|
|
|
|
{
|
2019-02-28 20:49:39 -05:00
|
|
|
|
chargeTransaction.Refunded = true;
|
2019-02-01 23:04:51 -05:00
|
|
|
|
}
|
2019-02-01 23:29:12 -05:00
|
|
|
|
await _transactionRepository.ReplaceAsync(chargeTransaction);
|
2019-02-01 23:04:51 -05:00
|
|
|
|
|
2019-02-01 23:29:12 -05:00
|
|
|
|
foreach (var refund in charge.Refunds)
|
2019-02-01 23:04:51 -05:00
|
|
|
|
{
|
2019-02-01 23:29:12 -05:00
|
|
|
|
var refundTransaction = await _transactionRepository.GetByGatewayIdAsync(
|
|
|
|
|
|
GatewayType.Stripe, refund.Id);
|
2020-03-27 14:36:37 -04:00
|
|
|
|
if (refundTransaction != null)
|
2019-02-01 23:04:51 -05:00
|
|
|
|
{
|
2019-02-01 23:29:12 -05:00
|
|
|
|
continue;
|
2019-02-01 23:04:51 -05:00
|
|
|
|
}
|
|
|
|
|
|
|
2020-03-27 14:36:37 -04:00
|
|
|
|
await _transactionRepository.CreateAsync(new Transaction
|
2019-02-01 23:04:51 -05:00
|
|
|
|
{
|
2019-02-01 23:29:12 -05:00
|
|
|
|
Amount = refund.Amount / 100M,
|
|
|
|
|
|
CreationDate = refund.Created,
|
|
|
|
|
|
OrganizationId = chargeTransaction.OrganizationId,
|
|
|
|
|
|
UserId = chargeTransaction.UserId,
|
|
|
|
|
|
Type = TransactionType.Refund,
|
|
|
|
|
|
Gateway = GatewayType.Stripe,
|
|
|
|
|
|
GatewayId = refund.Id,
|
|
|
|
|
|
PaymentMethodType = chargeTransaction.PaymentMethodType,
|
|
|
|
|
|
Details = chargeTransaction.Details
|
|
|
|
|
|
});
|
2019-02-22 09:31:05 -05:00
|
|
|
|
}
|
2019-02-01 23:04:51 -05:00
|
|
|
|
}
|
2022-05-31 10:55:56 -04:00
|
|
|
|
else
|
2022-08-29 14:53:16 -04:00
|
|
|
|
{
|
2019-02-22 09:31:05 -05:00
|
|
|
|
_logger.LogWarning("Charge refund amount doesn't seem correct. " + charge.Id);
|
2022-08-29 16:06:55 -04:00
|
|
|
|
}
|
|
|
|
|
|
}
|
2022-05-31 10:55:56 -04:00
|
|
|
|
else if (parsedEvent.Type.Equals(HandledStripeWebhook.PaymentSucceeded))
|
2022-08-29 16:06:55 -04:00
|
|
|
|
{
|
2019-08-09 23:56:26 -04:00
|
|
|
|
var invoice = await GetInvoiceAsync(parsedEvent, true);
|
2020-03-27 14:36:37 -04:00
|
|
|
|
if (invoice.Paid && invoice.BillingReason == "subscription_create")
|
2022-08-29 16:06:55 -04:00
|
|
|
|
{
|
2019-08-09 23:56:26 -04:00
|
|
|
|
var subscriptionService = new SubscriptionService();
|
|
|
|
|
|
var subscription = await subscriptionService.GetAsync(invoice.SubscriptionId);
|
|
|
|
|
|
if (subscription?.Status == "active")
|
|
|
|
|
|
{
|
|
|
|
|
|
if (DateTime.UtcNow - invoice.Created < TimeSpan.FromMinutes(1))
|
|
|
|
|
|
{
|
2019-09-02 08:41:06 -04:00
|
|
|
|
await Task.Delay(5000);
|
|
|
|
|
|
}
|
|
|
|
|
|
|
2019-08-09 23:56:26 -04:00
|
|
|
|
var ids = GetIdsFromMetaData(subscription.Metadata);
|
|
|
|
|
|
// org
|
2020-03-27 14:36:37 -04:00
|
|
|
|
if (ids.Item1.HasValue)
|
2022-08-29 16:06:55 -04:00
|
|
|
|
{
|
2020-03-27 14:36:37 -04:00
|
|
|
|
if (subscription.Items.Any(i => StaticStore.Plans.Any(p => p.StripePlanId == i.Plan.Id)))
|
2019-08-09 23:56:26 -04:00
|
|
|
|
{
|
|
|
|
|
|
await _organizationService.EnableAsync(ids.Item1.Value, subscription.CurrentPeriodEnd);
|
2022-08-29 16:06:55 -04:00
|
|
|
|
|
2021-03-24 15:27:16 -04:00
|
|
|
|
var organization = await _organizationRepository.GetByIdAsync(ids.Item1.Value);
|
|
|
|
|
|
await _referenceEventService.RaiseEventAsync(
|
|
|
|
|
|
new ReferenceEvent(ReferenceEventType.Rebilled, organization)
|
|
|
|
|
|
{
|
|
|
|
|
|
PlanName = organization?.Plan,
|
|
|
|
|
|
PlanType = organization?.PlanType,
|
|
|
|
|
|
Seats = organization?.Seats,
|
|
|
|
|
|
Storage = organization?.MaxStorageGb,
|
|
|
|
|
|
});
|
2019-08-09 23:56:26 -04:00
|
|
|
|
}
|
2022-08-29 16:06:55 -04:00
|
|
|
|
}
|
2019-08-09 23:56:26 -04:00
|
|
|
|
// user
|
2020-03-27 14:36:37 -04:00
|
|
|
|
else if (ids.Item2.HasValue)
|
2022-08-29 16:06:55 -04:00
|
|
|
|
{
|
2021-03-24 15:27:16 -04:00
|
|
|
|
if (subscription.Items.Any(i => i.Plan.Id == PremiumPlanId))
|
2019-08-09 23:56:26 -04:00
|
|
|
|
{
|
|
|
|
|
|
await _userService.EnablePremiumAsync(ids.Item2.Value, subscription.CurrentPeriodEnd);
|
2022-08-29 16:06:55 -04:00
|
|
|
|
|
2021-03-24 15:27:16 -04:00
|
|
|
|
var user = await _userRepository.GetByIdAsync(ids.Item2.Value);
|
|
|
|
|
|
await _referenceEventService.RaiseEventAsync(
|
|
|
|
|
|
new ReferenceEvent(ReferenceEventType.Rebilled, user)
|
|
|
|
|
|
{
|
|
|
|
|
|
PlanName = PremiumPlanId,
|
|
|
|
|
|
Storage = user?.MaxStorageGb,
|
|
|
|
|
|
});
|
2019-08-09 23:56:26 -04:00
|
|
|
|
}
|
|
|
|
|
|
}
|
|
|
|
|
|
}
|
|
|
|
|
|
}
|
2022-08-29 16:06:55 -04:00
|
|
|
|
}
|
2022-05-31 10:55:56 -04:00
|
|
|
|
else if (parsedEvent.Type.Equals(HandledStripeWebhook.PaymentFailed))
|
2019-02-22 09:31:05 -05:00
|
|
|
|
{
|
2022-06-24 14:20:32 -07:00
|
|
|
|
await HandlePaymentFailed(await GetInvoiceAsync(parsedEvent, true));
|
2022-08-29 15:53:48 -04:00
|
|
|
|
}
|
2022-05-31 10:55:56 -04:00
|
|
|
|
else if (parsedEvent.Type.Equals(HandledStripeWebhook.InvoiceCreated))
|
2022-08-29 15:53:48 -04:00
|
|
|
|
{
|
2019-08-20 11:09:02 -04:00
|
|
|
|
var invoice = await GetInvoiceAsync(parsedEvent, true);
|
2020-03-27 14:36:37 -04:00
|
|
|
|
if (!invoice.Paid && UnpaidAutoChargeInvoiceForSubscriptionCycle(invoice))
|
2022-08-29 15:53:48 -04:00
|
|
|
|
{
|
2019-02-22 09:31:05 -05:00
|
|
|
|
await AttemptToPayInvoiceAsync(invoice);
|
|
|
|
|
|
}
|
2018-04-05 21:56:36 -04:00
|
|
|
|
}
|
2022-08-29 16:06:55 -04:00
|
|
|
|
else
|
|
|
|
|
|
{
|
2019-02-22 09:31:05 -05:00
|
|
|
|
_logger.LogWarning("Unsupported event received. " + parsedEvent.Type);
|
2022-08-29 16:06:55 -04:00
|
|
|
|
}
|
|
|
|
|
|
|
2018-04-05 21:56:36 -04:00
|
|
|
|
return new OkResult();
|
2022-08-29 16:06:55 -04:00
|
|
|
|
}
|
2018-04-05 21:56:36 -04:00
|
|
|
|
|
2020-03-27 14:36:37 -04:00
|
|
|
|
private Tuple<Guid?, Guid?> GetIdsFromMetaData(IDictionary<string, string> metaData)
|
2022-08-29 16:06:55 -04:00
|
|
|
|
{
|
2020-03-27 14:36:37 -04:00
|
|
|
|
if (metaData == null || !metaData.Any())
|
2017-04-26 16:14:15 -04:00
|
|
|
|
{
|
2017-08-12 22:16:42 -04:00
|
|
|
|
return new Tuple<Guid?, Guid?>(null, null);
|
2022-08-29 14:53:16 -04:00
|
|
|
|
}
|
|
|
|
|
|
|
2020-03-27 14:36:37 -04:00
|
|
|
|
Guid? orgId = null;
|
|
|
|
|
|
Guid? userId = null;
|
2022-08-29 15:53:48 -04:00
|
|
|
|
|
2018-04-05 21:56:36 -04:00
|
|
|
|
if (metaData.ContainsKey("organizationId"))
|
2017-08-12 22:16:42 -04:00
|
|
|
|
{
|
|
|
|
|
|
orgId = new Guid(metaData["organizationId"]);
|
2017-04-26 16:14:15 -04:00
|
|
|
|
}
|
2020-03-27 14:36:37 -04:00
|
|
|
|
else if (metaData.ContainsKey("userId"))
|
2022-08-29 16:06:55 -04:00
|
|
|
|
{
|
2018-04-05 21:56:36 -04:00
|
|
|
|
userId = new Guid(metaData["userId"]);
|
2022-08-29 16:06:55 -04:00
|
|
|
|
}
|
|
|
|
|
|
|
2020-12-09 14:04:46 -05:00
|
|
|
|
if (userId == null && orgId == null)
|
2022-08-29 16:06:55 -04:00
|
|
|
|
{
|
2018-04-05 21:56:36 -04:00
|
|
|
|
var orgIdKey = metaData.Keys.FirstOrDefault(k => k.ToLowerInvariant() == "organizationid");
|
2020-03-27 14:36:37 -04:00
|
|
|
|
if (!string.IsNullOrWhiteSpace(orgIdKey))
|
2022-08-29 15:53:48 -04:00
|
|
|
|
{
|
2018-04-05 21:56:36 -04:00
|
|
|
|
orgId = new Guid(metaData[orgIdKey]);
|
2022-08-29 15:53:48 -04:00
|
|
|
|
}
|
2020-12-09 14:04:46 -05:00
|
|
|
|
else
|
2018-04-05 21:56:36 -04:00
|
|
|
|
{
|
|
|
|
|
|
var userIdKey = metaData.Keys.FirstOrDefault(k => k.ToLowerInvariant() == "userid");
|
2020-03-27 14:36:37 -04:00
|
|
|
|
if (!string.IsNullOrWhiteSpace(userIdKey))
|
2018-04-05 21:56:36 -04:00
|
|
|
|
{
|
|
|
|
|
|
userId = new Guid(metaData[userIdKey]);
|
|
|
|
|
|
}
|
|
|
|
|
|
}
|
2022-08-29 16:06:55 -04:00
|
|
|
|
}
|
|
|
|
|
|
|
2018-05-11 08:29:23 -04:00
|
|
|
|
return new Tuple<Guid?, Guid?>(orgId, userId);
|
2022-08-29 16:06:55 -04:00
|
|
|
|
}
|
2018-04-05 21:56:36 -04:00
|
|
|
|
|
2018-05-11 08:29:23 -04:00
|
|
|
|
private bool OrgPlanForInvoiceNotifications(Organization org)
|
2022-08-29 16:06:55 -04:00
|
|
|
|
{
|
2020-03-27 14:36:37 -04:00
|
|
|
|
switch (org.PlanType)
|
2022-08-29 16:06:55 -04:00
|
|
|
|
{
|
2019-02-02 23:04:14 -05:00
|
|
|
|
case PlanType.FamiliesAnnually:
|
|
|
|
|
|
case PlanType.TeamsAnnually:
|
2018-05-11 08:29:23 -04:00
|
|
|
|
case PlanType.EnterpriseAnnually:
|
|
|
|
|
|
return true;
|
2022-08-29 16:06:55 -04:00
|
|
|
|
default:
|
2018-05-11 08:29:23 -04:00
|
|
|
|
return false;
|
2022-08-29 14:53:16 -04:00
|
|
|
|
}
|
2022-08-29 16:06:55 -04:00
|
|
|
|
}
|
2019-02-03 00:00:21 -05:00
|
|
|
|
|
2019-09-23 09:03:18 -04:00
|
|
|
|
private async Task<bool> AttemptToPayInvoiceAsync(Invoice invoice)
|
2022-08-29 16:06:55 -04:00
|
|
|
|
{
|
2019-02-03 00:00:21 -05:00
|
|
|
|
var customerService = new CustomerService();
|
2019-09-23 09:03:18 -04:00
|
|
|
|
var customer = await customerService.GetAsync(invoice.CustomerId);
|
|
|
|
|
|
if (customer?.Metadata?.ContainsKey("appleReceipt") ?? false)
|
2019-02-03 00:00:21 -05:00
|
|
|
|
{
|
2017-08-12 22:16:42 -04:00
|
|
|
|
return await AttemptToPayInvoiceWithAppleReceiptAsync(invoice, customer);
|
2019-09-23 09:03:18 -04:00
|
|
|
|
}
|
2020-03-27 14:36:37 -04:00
|
|
|
|
else if (customer?.Metadata?.ContainsKey("btCustomerId") ?? false)
|
2022-08-29 16:06:55 -04:00
|
|
|
|
{
|
2019-09-23 09:03:18 -04:00
|
|
|
|
return await AttemptToPayInvoiceWithBraintreeAsync(invoice, customer);
|
2022-08-29 16:06:55 -04:00
|
|
|
|
}
|
2019-09-23 09:03:18 -04:00
|
|
|
|
return false;
|
2022-08-29 16:06:55 -04:00
|
|
|
|
}
|
2019-09-23 09:03:18 -04:00
|
|
|
|
|
|
|
|
|
|
private async Task<bool> AttemptToPayInvoiceWithAppleReceiptAsync(Invoice invoice, Customer customer)
|
2022-08-29 16:06:55 -04:00
|
|
|
|
{
|
2019-09-23 09:03:18 -04:00
|
|
|
|
if (!customer?.Metadata?.ContainsKey("appleReceipt") ?? true)
|
|
|
|
|
|
{
|
|
|
|
|
|
return false;
|
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
var originalAppleReceiptTransactionId = customer.Metadata["appleReceipt"];
|
|
|
|
|
|
var appleReceiptRecord = await _appleIapService.GetReceiptAsync(originalAppleReceiptTransactionId);
|
|
|
|
|
|
if (string.IsNullOrWhiteSpace(appleReceiptRecord?.Item1) || !appleReceiptRecord.Item2.HasValue)
|
2022-08-29 14:53:16 -04:00
|
|
|
|
{
|
2019-09-23 09:03:18 -04:00
|
|
|
|
return false;
|
|
|
|
|
|
}
|
|
|
|
|
|
|
2020-03-27 14:36:37 -04:00
|
|
|
|
var subscriptionService = new SubscriptionService();
|
2019-09-23 09:03:18 -04:00
|
|
|
|
var subscription = await subscriptionService.GetAsync(invoice.SubscriptionId);
|
2020-03-27 14:36:37 -04:00
|
|
|
|
var ids = GetIdsFromMetaData(subscription?.Metadata);
|
|
|
|
|
|
if (!ids.Item2.HasValue)
|
2022-08-29 16:06:55 -04:00
|
|
|
|
{
|
2020-03-27 14:36:37 -04:00
|
|
|
|
// Apple receipt is only for user subscriptions
|
2019-09-23 09:03:18 -04:00
|
|
|
|
return false;
|
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
if (appleReceiptRecord.Item2.Value != ids.Item2.Value)
|
2022-08-29 14:53:16 -04:00
|
|
|
|
{
|
2019-09-23 09:03:18 -04:00
|
|
|
|
_logger.LogError("User Ids for Apple Receipt and subscription do not match: {0} != {1}.",
|
|
|
|
|
|
appleReceiptRecord.Item2.Value, ids.Item2.Value);
|
|
|
|
|
|
return false;
|
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
var appleReceiptStatus = await _appleIapService.GetVerifiedReceiptStatusAsync(appleReceiptRecord.Item1);
|
|
|
|
|
|
if (appleReceiptStatus == null)
|
2022-08-29 16:06:55 -04:00
|
|
|
|
{
|
2019-09-23 09:03:18 -04:00
|
|
|
|
// TODO: cancel sub if receipt is cancelled?
|
|
|
|
|
|
return false;
|
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
var receiptExpiration = appleReceiptStatus.GetLastExpiresDate().GetValueOrDefault(DateTime.MinValue);
|
|
|
|
|
|
var invoiceDue = invoice.DueDate.GetValueOrDefault(DateTime.MinValue);
|
|
|
|
|
|
if (receiptExpiration <= invoiceDue)
|
2022-08-29 16:06:55 -04:00
|
|
|
|
{
|
2019-09-23 09:03:18 -04:00
|
|
|
|
_logger.LogWarning("Apple receipt expiration is before invoice due date. {0} <= {1}",
|
|
|
|
|
|
receiptExpiration, invoiceDue);
|
|
|
|
|
|
return false;
|
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
var receiptLastTransactionId = appleReceiptStatus.GetLastTransactionId();
|
|
|
|
|
|
var existingTransaction = await _transactionRepository.GetByGatewayIdAsync(
|
|
|
|
|
|
GatewayType.AppStore, receiptLastTransactionId);
|
|
|
|
|
|
if (existingTransaction != null)
|
2022-08-29 15:53:48 -04:00
|
|
|
|
{
|
2019-09-23 09:03:18 -04:00
|
|
|
|
_logger.LogWarning("There is already an existing transaction for this Apple receipt.",
|
|
|
|
|
|
receiptLastTransactionId);
|
|
|
|
|
|
return false;
|
2022-08-29 15:53:48 -04:00
|
|
|
|
}
|
2019-09-23 09:03:18 -04:00
|
|
|
|
|
|
|
|
|
|
var appleTransaction = appleReceiptStatus.BuildTransactionFromLastTransaction(
|
|
|
|
|
|
PremiumPlanAppleIapPrice, ids.Item2.Value);
|
|
|
|
|
|
appleTransaction.Type = TransactionType.Charge;
|
|
|
|
|
|
|
|
|
|
|
|
var invoiceService = new InvoiceService();
|
2022-08-29 16:06:55 -04:00
|
|
|
|
try
|
|
|
|
|
|
{
|
2019-09-23 09:03:18 -04:00
|
|
|
|
await invoiceService.UpdateAsync(invoice.Id, new InvoiceUpdateOptions
|
2022-08-29 16:06:55 -04:00
|
|
|
|
{
|
2019-09-23 09:03:18 -04:00
|
|
|
|
Metadata = new Dictionary<string, string>
|
2022-08-29 16:06:55 -04:00
|
|
|
|
{
|
2019-09-23 09:03:18 -04:00
|
|
|
|
["appleReceipt"] = appleReceiptStatus.GetOriginalTransactionId(),
|
|
|
|
|
|
["appleReceiptTransactionId"] = receiptLastTransactionId
|
2022-08-29 16:06:55 -04:00
|
|
|
|
}
|
2019-09-23 09:03:18 -04:00
|
|
|
|
});
|
2022-08-29 15:53:48 -04:00
|
|
|
|
|
2019-02-01 23:29:12 -05:00
|
|
|
|
await _transactionRepository.CreateAsync(appleTransaction);
|
2019-09-23 09:03:18 -04:00
|
|
|
|
await invoiceService.PayAsync(invoice.Id, new InvoicePayOptions { PaidOutOfBand = true });
|
2022-08-29 16:06:55 -04:00
|
|
|
|
}
|
2020-03-27 14:36:37 -04:00
|
|
|
|
catch (Exception e)
|
2022-08-29 16:06:55 -04:00
|
|
|
|
{
|
2019-09-23 09:03:18 -04:00
|
|
|
|
if (e.Message.Contains("Invoice is already paid"))
|
|
|
|
|
|
{
|
|
|
|
|
|
await invoiceService.UpdateAsync(invoice.Id, new InvoiceUpdateOptions
|
|
|
|
|
|
{
|
|
|
|
|
|
Metadata = invoice.Metadata
|
|
|
|
|
|
});
|
|
|
|
|
|
}
|
2020-03-27 14:36:37 -04:00
|
|
|
|
else
|
2019-09-23 09:03:18 -04:00
|
|
|
|
{
|
2021-12-16 15:35:07 -05:00
|
|
|
|
throw;
|
2019-09-23 09:03:18 -04:00
|
|
|
|
}
|
2019-02-03 00:00:21 -05:00
|
|
|
|
}
|
|
|
|
|
|
|
2019-09-23 09:03:18 -04:00
|
|
|
|
return true;
|
2022-08-29 16:06:55 -04:00
|
|
|
|
}
|
|
|
|
|
|
|
2019-02-03 00:00:21 -05:00
|
|
|
|
private async Task<bool> AttemptToPayInvoiceWithBraintreeAsync(Invoice invoice, Customer customer)
|
2022-08-29 16:06:55 -04:00
|
|
|
|
{
|
2020-01-17 21:11:48 -05:00
|
|
|
|
if (!customer?.Metadata?.ContainsKey("btCustomerId") ?? true)
|
2019-02-03 00:00:21 -05:00
|
|
|
|
{
|
2020-01-17 21:11:48 -05:00
|
|
|
|
return false;
|
|
|
|
|
|
}
|
|
|
|
|
|
|
2019-02-03 00:00:21 -05:00
|
|
|
|
var subscriptionService = new SubscriptionService();
|
|
|
|
|
|
var subscription = await subscriptionService.GetAsync(invoice.SubscriptionId);
|
|
|
|
|
|
var ids = GetIdsFromMetaData(subscription?.Metadata);
|
|
|
|
|
|
if (!ids.Item1.HasValue && !ids.Item2.HasValue)
|
2022-08-29 14:53:16 -04:00
|
|
|
|
{
|
2019-02-03 00:00:21 -05:00
|
|
|
|
return false;
|
2022-08-29 15:53:48 -04:00
|
|
|
|
}
|
|
|
|
|
|
|
2020-01-17 21:11:48 -05:00
|
|
|
|
var orgTransaction = ids.Item1.HasValue;
|
|
|
|
|
|
var btObjIdField = orgTransaction ? "organization_id" : "user_id";
|
2019-02-03 00:00:21 -05:00
|
|
|
|
var btObjId = ids.Item1 ?? ids.Item2.Value;
|
|
|
|
|
|
var btInvoiceAmount = (invoice.AmountDue / 100M);
|
2022-08-29 16:06:55 -04:00
|
|
|
|
|
2019-02-03 00:00:21 -05:00
|
|
|
|
var existingTransactions = orgTransaction ?
|
2020-01-17 21:11:48 -05:00
|
|
|
|
await _transactionRepository.GetManyByOrganizationIdAsync(ids.Item1.Value) :
|
|
|
|
|
|
await _transactionRepository.GetManyByUserIdAsync(ids.Item2.Value);
|
|
|
|
|
|
var duplicateTimeSpan = TimeSpan.FromHours(24);
|
|
|
|
|
|
var now = DateTime.UtcNow;
|
|
|
|
|
|
var duplicateTransaction = existingTransactions?
|
|
|
|
|
|
.FirstOrDefault(t => (now - t.CreationDate) < duplicateTimeSpan);
|
2020-03-27 14:36:37 -04:00
|
|
|
|
if (duplicateTransaction != null)
|
2022-08-29 15:53:48 -04:00
|
|
|
|
{
|
2020-01-17 21:11:48 -05:00
|
|
|
|
_logger.LogWarning("There is already a recent PayPal transaction ({0}). " +
|
2019-02-03 00:00:21 -05:00
|
|
|
|
"Do not charge again to prevent possible duplicate.", duplicateTransaction.GatewayId);
|
|
|
|
|
|
return false;
|
2022-08-29 15:53:48 -04:00
|
|
|
|
}
|
|
|
|
|
|
|
2019-02-03 00:05:35 -05:00
|
|
|
|
var transactionResult = await _btGateway.Transaction.SaleAsync(
|
2019-02-03 00:00:21 -05:00
|
|
|
|
new Braintree.TransactionRequest
|
2022-08-29 16:06:55 -04:00
|
|
|
|
{
|
2019-02-03 00:00:21 -05:00
|
|
|
|
Amount = btInvoiceAmount,
|
|
|
|
|
|
CustomerId = customer.Metadata["btCustomerId"],
|
2022-05-31 10:55:56 -04:00
|
|
|
|
Options = new Braintree.TransactionOptionsRequest
|
2019-02-03 00:00:21 -05:00
|
|
|
|
{
|
|
|
|
|
|
SubmitForSettlement = true,
|
|
|
|
|
|
PayPal = new Braintree.TransactionOptionsPayPalRequest
|
|
|
|
|
|
{
|
|
|
|
|
|
CustomField = $"{btObjIdField}:{btObjId}"
|
|
|
|
|
|
}
|
2022-08-29 14:53:16 -04:00
|
|
|
|
},
|
2019-02-03 00:05:35 -05:00
|
|
|
|
CustomFields = new Dictionary<string, string>
|
2022-08-29 14:53:16 -04:00
|
|
|
|
{
|
2019-02-03 00:05:35 -05:00
|
|
|
|
[btObjIdField] = btObjId.ToString()
|
2022-08-29 14:53:16 -04:00
|
|
|
|
}
|
2022-08-29 16:06:55 -04:00
|
|
|
|
});
|
|
|
|
|
|
|
2022-08-29 14:53:16 -04:00
|
|
|
|
if (!transactionResult.IsSuccess())
|
2022-08-29 16:06:55 -04:00
|
|
|
|
{
|
2019-02-03 00:05:35 -05:00
|
|
|
|
if (invoice.AttemptCount < 4)
|
2022-08-29 16:06:55 -04:00
|
|
|
|
{
|
2022-08-29 14:53:16 -04:00
|
|
|
|
await _mailService.SendPaymentFailedAsync(customer.Email, btInvoiceAmount, true);
|
2019-02-03 00:05:35 -05:00
|
|
|
|
}
|
2019-09-23 09:03:18 -04:00
|
|
|
|
return false;
|
2022-08-29 16:06:55 -04:00
|
|
|
|
}
|
2022-08-29 15:53:48 -04:00
|
|
|
|
|
2019-02-03 00:05:35 -05:00
|
|
|
|
var invoiceService = new InvoiceService();
|
|
|
|
|
|
try
|
2022-08-29 16:06:55 -04:00
|
|
|
|
{
|
2019-02-03 00:05:35 -05:00
|
|
|
|
await invoiceService.UpdateAsync(invoice.Id, new InvoiceUpdateOptions
|
2022-08-29 16:06:55 -04:00
|
|
|
|
{
|
2019-02-03 00:05:35 -05:00
|
|
|
|
Metadata = new Dictionary<string, string>
|
2022-08-29 16:06:55 -04:00
|
|
|
|
{
|
2019-02-03 00:05:35 -05:00
|
|
|
|
["btTransactionId"] = transactionResult.Target.Id,
|
|
|
|
|
|
["btPayPalTransactionId"] =
|
|
|
|
|
|
transactionResult.Target.PayPalDetails?.AuthorizationId
|
2022-08-29 16:06:55 -04:00
|
|
|
|
}
|
|
|
|
|
|
});
|
2019-02-03 00:05:35 -05:00
|
|
|
|
await invoiceService.PayAsync(invoice.Id, new InvoicePayOptions { PaidOutOfBand = true });
|
2022-08-29 16:06:55 -04:00
|
|
|
|
}
|
2020-03-27 14:36:37 -04:00
|
|
|
|
catch (Exception e)
|
2022-08-29 16:06:55 -04:00
|
|
|
|
{
|
2019-02-03 00:05:35 -05:00
|
|
|
|
await _btGateway.Transaction.RefundAsync(transactionResult.Target.Id);
|
2020-03-27 14:36:37 -04:00
|
|
|
|
if (e.Message.Contains("Invoice is already paid"))
|
2019-02-03 00:00:21 -05:00
|
|
|
|
{
|
2019-02-03 00:05:35 -05:00
|
|
|
|
await invoiceService.UpdateAsync(invoice.Id, new InvoiceUpdateOptions
|
2019-02-03 00:00:21 -05:00
|
|
|
|
{
|
2019-02-03 00:05:35 -05:00
|
|
|
|
Metadata = invoice.Metadata
|
|
|
|
|
|
});
|
|
|
|
|
|
}
|
2020-03-27 14:36:37 -04:00
|
|
|
|
else
|
2019-02-03 00:05:35 -05:00
|
|
|
|
{
|
2021-12-16 15:35:07 -05:00
|
|
|
|
throw;
|
2019-02-03 00:05:35 -05:00
|
|
|
|
}
|
2019-02-03 00:00:21 -05:00
|
|
|
|
}
|
2019-08-20 11:09:02 -04:00
|
|
|
|
|
2019-02-03 00:00:21 -05:00
|
|
|
|
return true;
|
2022-08-29 16:06:55 -04:00
|
|
|
|
}
|
|
|
|
|
|
|
2019-08-20 11:09:02 -04:00
|
|
|
|
private bool UnpaidAutoChargeInvoiceForSubscriptionCycle(Invoice invoice)
|
2022-08-29 16:06:55 -04:00
|
|
|
|
{
|
2019-08-20 11:09:02 -04:00
|
|
|
|
return invoice.AmountDue > 0 && !invoice.Paid && invoice.CollectionMethod == "charge_automatically" &&
|
|
|
|
|
|
invoice.BillingReason == "subscription_cycle" && invoice.SubscriptionId != null;
|
2022-08-29 16:06:55 -04:00
|
|
|
|
}
|
|
|
|
|
|
|
2022-05-10 17:12:09 -04:00
|
|
|
|
private async Task<Charge> GetChargeAsync(Stripe.Event parsedEvent, bool fresh = false)
|
2022-08-29 16:06:55 -04:00
|
|
|
|
{
|
2020-03-27 14:36:37 -04:00
|
|
|
|
if (!(parsedEvent.Data.Object is Charge eventCharge))
|
2019-08-20 11:09:02 -04:00
|
|
|
|
{
|
|
|
|
|
|
throw new Exception("Charge is null (from parsed event). " + parsedEvent.Id);
|
|
|
|
|
|
}
|
2022-05-10 17:12:09 -04:00
|
|
|
|
if (!fresh)
|
2022-08-29 14:53:16 -04:00
|
|
|
|
{
|
Families for Enterprise (#1714)
* Create common test infrastructure project
* Add helpers to further type PlanTypes
* Enable testing of ASP.net MVC controllers
Controller properties have all kinds of validations in the background.
In general, we don't user properties on our Controllers, so the easiest
way to allow for Autofixture-based testing of our Controllers is to just
omit setting all properties on them.
* Workaround for broken MemberAutoDataAttribute
https://github.com/AutoFixture/AutoFixture/pull/1164 shows that only
the first test case is pulled for this attribute.
This is a workaround that populates the provided parameters, left to
right, using AutoFixture to populate any remaining.
* WIP: Organization sponsorship flow
* Add Attribute to use the Bit Autodata dependency chain
BitAutoDataAttribute is used to mark a Theory as autopopulating
parameters.
Extract common attribute methods to to a helper class. Cannot
inherit a common base, since both require inheriting from different
Xunit base classes to work.
* WIP: scaffolding for families for enterprise sponsorship flow
* Fix broken tests
* Create sponsorship offer (#1688)
* Initial db work (#1687)
* Add organization sponsorship databases to all providers
* Generalize create and update for database, specialize in code
* Add PlanSponsorshipType to db model
* Write valid json for test entries
* Initial scaffolding of emails (#1686)
* Initial scaffolding of emails
* Work on adding models for FamilyForEnterprise emails
* Switch verbage
* Put preliminary copy in emails
* Skip test
* Families for enterprise/stripe integrations (#1699)
* Add PlanSponsorshipType to static store
* Add sponsorship type to token and creates sponsorship
* PascalCase properties
* Require sponsorship for remove
* Create subscription sponsorship helper class
* Handle Sponsored subscription changes
* Add sponsorship id to subscription metadata
* Make sponsoring references nullable
This state indicates that a sponsorship has lapsed, but was not able to
be reverted for billing reasons
* WIP: Validate and remove subscriptions
* Update sponsorships on organization and org user delete
* Add friendly name to organization sponsorship
* Add sponsorship available boolean to orgDetails
* Add sponsorship service to DI
* Use userId to find org users
* Send f4e offer email
* Simplify names of f4e mail messages
* Fix Stripe org default tax rates
* Universal sponsorship redeem api
* Populate user in current context
* Add product type to organization details
* Use upgrade path to change sponsorship
Sponsorships need to be annual to match the GB add-on charge rate
* Use organization and auth to find organization sponsorship
* Add resend sponsorship offer api endpoint
* Fix double email send
* Fix sponsorship upgrade options
* Add is sponsored item to subscription response
* Add sponsorship validation to upcoming invoice webhook
* Add sponsorship validation to upcoming invoice webhook
* Fix organization delete sponsorship hooks
* Test org sponsorship service
* Fix sproc
* Create common test infrastructure project
* Add helpers to further type PlanTypes
* Enable testing of ASP.net MVC controllers
Controller properties have all kinds of validations in the background.
In general, we don't user properties on our Controllers, so the easiest
way to allow for Autofixture-based testing of our Controllers is to just
omit setting all properties on them.
* Workaround for broken MemberAutoDataAttribute
https://github.com/AutoFixture/AutoFixture/pull/1164 shows that only
the first test case is pulled for this attribute.
This is a workaround that populates the provided parameters, left to
right, using AutoFixture to populate any remaining.
* WIP: Organization sponsorship flow
* Add Attribute to use the Bit Autodata dependency chain
BitAutoDataAttribute is used to mark a Theory as autopopulating
parameters.
Extract common attribute methods to to a helper class. Cannot
inherit a common base, since both require inheriting from different
Xunit base classes to work.
* WIP: scaffolding for families for enterprise sponsorship flow
* Fix broken tests
* Create sponsorship offer (#1688)
* Initial db work (#1687)
* Add organization sponsorship databases to all providers
* Generalize create and update for database, specialize in code
* Add PlanSponsorshipType to db model
* Write valid json for test entries
* Initial scaffolding of emails (#1686)
* Initial scaffolding of emails
* Work on adding models for FamilyForEnterprise emails
* Switch verbage
* Put preliminary copy in emails
* Skip test
* Families for enterprise/stripe integrations (#1699)
* Add PlanSponsorshipType to static store
* Add sponsorship type to token and creates sponsorship
* PascalCase properties
* Require sponsorship for remove
* Create subscription sponsorship helper class
* Handle Sponsored subscription changes
* Add sponsorship id to subscription metadata
* Make sponsoring references nullable
This state indicates that a sponsorship has lapsed, but was not able to
be reverted for billing reasons
* WIP: Validate and remove subscriptions
* Update sponsorships on organization and org user delete
* Add friendly name to organization sponsorship
* Add sponsorship available boolean to orgDetails
* Add sponsorship service to DI
* Use userId to find org users
* Send f4e offer email
* Simplify names of f4e mail messages
* Fix Stripe org default tax rates
* Universal sponsorship redeem api
* Populate user in current context
* Add product type to organization details
* Use upgrade path to change sponsorship
Sponsorships need to be annual to match the GB add-on charge rate
* Use organization and auth to find organization sponsorship
* Add resend sponsorship offer api endpoint
* Fix double email send
* Fix sponsorship upgrade options
* Add is sponsored item to subscription response
* Add sponsorship validation to upcoming invoice webhook
* Add sponsorship validation to upcoming invoice webhook
* Fix organization delete sponsorship hooks
* Test org sponsorship service
* Fix sproc
* Fix build error
* Update emails
* Fix tests
* Skip local test
* Add newline
* Fix stripe subscription update
* Finish emails
* Skip test
* Fix unit tests
* Remove unused variable
* Fix unit tests
* Switch to handlebars ifs
* Remove ending email
* Remove reconfirmation template
* Switch naming convention
* Switch naming convention
* Fix migration
* Update copy and links
* Switch to using Guid in the method
* Remove unneeded css styles
* Add sql files to Sql.sqlproj
* Removed old comments
* Made name more verbose
* Fix SQL error
* Move unit tests to service
* Fix sp
* Revert "Move unit tests to service"
This reverts commit 1185bf3ec8ca36ccd75717ed2463adf8885159a6.
* Do repository validation in service layer
* Fix tests
* Fix merge conflicts and remove TODO
* Remove unneeded models
* Fix spacing and formatting
* Switch Org -> Organization
* Remove single use variables
* Switch method name
* Fix Controller
* Switch to obfuscating email
* Fix unit tests
Co-authored-by: Justin Baur <admin@justinbaur.com>
2021-11-19 16:25:06 -06:00
|
|
|
|
return eventCharge;
|
2022-08-29 14:53:16 -04:00
|
|
|
|
}
|
Families for Enterprise (#1714)
* Create common test infrastructure project
* Add helpers to further type PlanTypes
* Enable testing of ASP.net MVC controllers
Controller properties have all kinds of validations in the background.
In general, we don't user properties on our Controllers, so the easiest
way to allow for Autofixture-based testing of our Controllers is to just
omit setting all properties on them.
* Workaround for broken MemberAutoDataAttribute
https://github.com/AutoFixture/AutoFixture/pull/1164 shows that only
the first test case is pulled for this attribute.
This is a workaround that populates the provided parameters, left to
right, using AutoFixture to populate any remaining.
* WIP: Organization sponsorship flow
* Add Attribute to use the Bit Autodata dependency chain
BitAutoDataAttribute is used to mark a Theory as autopopulating
parameters.
Extract common attribute methods to to a helper class. Cannot
inherit a common base, since both require inheriting from different
Xunit base classes to work.
* WIP: scaffolding for families for enterprise sponsorship flow
* Fix broken tests
* Create sponsorship offer (#1688)
* Initial db work (#1687)
* Add organization sponsorship databases to all providers
* Generalize create and update for database, specialize in code
* Add PlanSponsorshipType to db model
* Write valid json for test entries
* Initial scaffolding of emails (#1686)
* Initial scaffolding of emails
* Work on adding models for FamilyForEnterprise emails
* Switch verbage
* Put preliminary copy in emails
* Skip test
* Families for enterprise/stripe integrations (#1699)
* Add PlanSponsorshipType to static store
* Add sponsorship type to token and creates sponsorship
* PascalCase properties
* Require sponsorship for remove
* Create subscription sponsorship helper class
* Handle Sponsored subscription changes
* Add sponsorship id to subscription metadata
* Make sponsoring references nullable
This state indicates that a sponsorship has lapsed, but was not able to
be reverted for billing reasons
* WIP: Validate and remove subscriptions
* Update sponsorships on organization and org user delete
* Add friendly name to organization sponsorship
* Add sponsorship available boolean to orgDetails
* Add sponsorship service to DI
* Use userId to find org users
* Send f4e offer email
* Simplify names of f4e mail messages
* Fix Stripe org default tax rates
* Universal sponsorship redeem api
* Populate user in current context
* Add product type to organization details
* Use upgrade path to change sponsorship
Sponsorships need to be annual to match the GB add-on charge rate
* Use organization and auth to find organization sponsorship
* Add resend sponsorship offer api endpoint
* Fix double email send
* Fix sponsorship upgrade options
* Add is sponsored item to subscription response
* Add sponsorship validation to upcoming invoice webhook
* Add sponsorship validation to upcoming invoice webhook
* Fix organization delete sponsorship hooks
* Test org sponsorship service
* Fix sproc
* Create common test infrastructure project
* Add helpers to further type PlanTypes
* Enable testing of ASP.net MVC controllers
Controller properties have all kinds of validations in the background.
In general, we don't user properties on our Controllers, so the easiest
way to allow for Autofixture-based testing of our Controllers is to just
omit setting all properties on them.
* Workaround for broken MemberAutoDataAttribute
https://github.com/AutoFixture/AutoFixture/pull/1164 shows that only
the first test case is pulled for this attribute.
This is a workaround that populates the provided parameters, left to
right, using AutoFixture to populate any remaining.
* WIP: Organization sponsorship flow
* Add Attribute to use the Bit Autodata dependency chain
BitAutoDataAttribute is used to mark a Theory as autopopulating
parameters.
Extract common attribute methods to to a helper class. Cannot
inherit a common base, since both require inheriting from different
Xunit base classes to work.
* WIP: scaffolding for families for enterprise sponsorship flow
* Fix broken tests
* Create sponsorship offer (#1688)
* Initial db work (#1687)
* Add organization sponsorship databases to all providers
* Generalize create and update for database, specialize in code
* Add PlanSponsorshipType to db model
* Write valid json for test entries
* Initial scaffolding of emails (#1686)
* Initial scaffolding of emails
* Work on adding models for FamilyForEnterprise emails
* Switch verbage
* Put preliminary copy in emails
* Skip test
* Families for enterprise/stripe integrations (#1699)
* Add PlanSponsorshipType to static store
* Add sponsorship type to token and creates sponsorship
* PascalCase properties
* Require sponsorship for remove
* Create subscription sponsorship helper class
* Handle Sponsored subscription changes
* Add sponsorship id to subscription metadata
* Make sponsoring references nullable
This state indicates that a sponsorship has lapsed, but was not able to
be reverted for billing reasons
* WIP: Validate and remove subscriptions
* Update sponsorships on organization and org user delete
* Add friendly name to organization sponsorship
* Add sponsorship available boolean to orgDetails
* Add sponsorship service to DI
* Use userId to find org users
* Send f4e offer email
* Simplify names of f4e mail messages
* Fix Stripe org default tax rates
* Universal sponsorship redeem api
* Populate user in current context
* Add product type to organization details
* Use upgrade path to change sponsorship
Sponsorships need to be annual to match the GB add-on charge rate
* Use organization and auth to find organization sponsorship
* Add resend sponsorship offer api endpoint
* Fix double email send
* Fix sponsorship upgrade options
* Add is sponsored item to subscription response
* Add sponsorship validation to upcoming invoice webhook
* Add sponsorship validation to upcoming invoice webhook
* Fix organization delete sponsorship hooks
* Test org sponsorship service
* Fix sproc
* Fix build error
* Update emails
* Fix tests
* Skip local test
* Add newline
* Fix stripe subscription update
* Finish emails
* Skip test
* Fix unit tests
* Remove unused variable
* Fix unit tests
* Switch to handlebars ifs
* Remove ending email
* Remove reconfirmation template
* Switch naming convention
* Switch naming convention
* Fix migration
* Update copy and links
* Switch to using Guid in the method
* Remove unneeded css styles
* Add sql files to Sql.sqlproj
* Removed old comments
* Made name more verbose
* Fix SQL error
* Move unit tests to service
* Fix sp
* Revert "Move unit tests to service"
This reverts commit 1185bf3ec8ca36ccd75717ed2463adf8885159a6.
* Do repository validation in service layer
* Fix tests
* Fix merge conflicts and remove TODO
* Remove unneeded models
* Fix spacing and formatting
* Switch Org -> Organization
* Remove single use variables
* Switch method name
* Fix Controller
* Switch to obfuscating email
* Fix unit tests
Co-authored-by: Justin Baur <admin@justinbaur.com>
2021-11-19 16:25:06 -06:00
|
|
|
|
var chargeService = new ChargeService();
|
|
|
|
|
|
var charge = await chargeService.GetAsync(eventCharge.Id);
|
|
|
|
|
|
if (charge == null)
|
2022-08-29 14:53:16 -04:00
|
|
|
|
{
|
Families for Enterprise (#1714)
* Create common test infrastructure project
* Add helpers to further type PlanTypes
* Enable testing of ASP.net MVC controllers
Controller properties have all kinds of validations in the background.
In general, we don't user properties on our Controllers, so the easiest
way to allow for Autofixture-based testing of our Controllers is to just
omit setting all properties on them.
* Workaround for broken MemberAutoDataAttribute
https://github.com/AutoFixture/AutoFixture/pull/1164 shows that only
the first test case is pulled for this attribute.
This is a workaround that populates the provided parameters, left to
right, using AutoFixture to populate any remaining.
* WIP: Organization sponsorship flow
* Add Attribute to use the Bit Autodata dependency chain
BitAutoDataAttribute is used to mark a Theory as autopopulating
parameters.
Extract common attribute methods to to a helper class. Cannot
inherit a common base, since both require inheriting from different
Xunit base classes to work.
* WIP: scaffolding for families for enterprise sponsorship flow
* Fix broken tests
* Create sponsorship offer (#1688)
* Initial db work (#1687)
* Add organization sponsorship databases to all providers
* Generalize create and update for database, specialize in code
* Add PlanSponsorshipType to db model
* Write valid json for test entries
* Initial scaffolding of emails (#1686)
* Initial scaffolding of emails
* Work on adding models for FamilyForEnterprise emails
* Switch verbage
* Put preliminary copy in emails
* Skip test
* Families for enterprise/stripe integrations (#1699)
* Add PlanSponsorshipType to static store
* Add sponsorship type to token and creates sponsorship
* PascalCase properties
* Require sponsorship for remove
* Create subscription sponsorship helper class
* Handle Sponsored subscription changes
* Add sponsorship id to subscription metadata
* Make sponsoring references nullable
This state indicates that a sponsorship has lapsed, but was not able to
be reverted for billing reasons
* WIP: Validate and remove subscriptions
* Update sponsorships on organization and org user delete
* Add friendly name to organization sponsorship
* Add sponsorship available boolean to orgDetails
* Add sponsorship service to DI
* Use userId to find org users
* Send f4e offer email
* Simplify names of f4e mail messages
* Fix Stripe org default tax rates
* Universal sponsorship redeem api
* Populate user in current context
* Add product type to organization details
* Use upgrade path to change sponsorship
Sponsorships need to be annual to match the GB add-on charge rate
* Use organization and auth to find organization sponsorship
* Add resend sponsorship offer api endpoint
* Fix double email send
* Fix sponsorship upgrade options
* Add is sponsored item to subscription response
* Add sponsorship validation to upcoming invoice webhook
* Add sponsorship validation to upcoming invoice webhook
* Fix organization delete sponsorship hooks
* Test org sponsorship service
* Fix sproc
* Create common test infrastructure project
* Add helpers to further type PlanTypes
* Enable testing of ASP.net MVC controllers
Controller properties have all kinds of validations in the background.
In general, we don't user properties on our Controllers, so the easiest
way to allow for Autofixture-based testing of our Controllers is to just
omit setting all properties on them.
* Workaround for broken MemberAutoDataAttribute
https://github.com/AutoFixture/AutoFixture/pull/1164 shows that only
the first test case is pulled for this attribute.
This is a workaround that populates the provided parameters, left to
right, using AutoFixture to populate any remaining.
* WIP: Organization sponsorship flow
* Add Attribute to use the Bit Autodata dependency chain
BitAutoDataAttribute is used to mark a Theory as autopopulating
parameters.
Extract common attribute methods to to a helper class. Cannot
inherit a common base, since both require inheriting from different
Xunit base classes to work.
* WIP: scaffolding for families for enterprise sponsorship flow
* Fix broken tests
* Create sponsorship offer (#1688)
* Initial db work (#1687)
* Add organization sponsorship databases to all providers
* Generalize create and update for database, specialize in code
* Add PlanSponsorshipType to db model
* Write valid json for test entries
* Initial scaffolding of emails (#1686)
* Initial scaffolding of emails
* Work on adding models for FamilyForEnterprise emails
* Switch verbage
* Put preliminary copy in emails
* Skip test
* Families for enterprise/stripe integrations (#1699)
* Add PlanSponsorshipType to static store
* Add sponsorship type to token and creates sponsorship
* PascalCase properties
* Require sponsorship for remove
* Create subscription sponsorship helper class
* Handle Sponsored subscription changes
* Add sponsorship id to subscription metadata
* Make sponsoring references nullable
This state indicates that a sponsorship has lapsed, but was not able to
be reverted for billing reasons
* WIP: Validate and remove subscriptions
* Update sponsorships on organization and org user delete
* Add friendly name to organization sponsorship
* Add sponsorship available boolean to orgDetails
* Add sponsorship service to DI
* Use userId to find org users
* Send f4e offer email
* Simplify names of f4e mail messages
* Fix Stripe org default tax rates
* Universal sponsorship redeem api
* Populate user in current context
* Add product type to organization details
* Use upgrade path to change sponsorship
Sponsorships need to be annual to match the GB add-on charge rate
* Use organization and auth to find organization sponsorship
* Add resend sponsorship offer api endpoint
* Fix double email send
* Fix sponsorship upgrade options
* Add is sponsored item to subscription response
* Add sponsorship validation to upcoming invoice webhook
* Add sponsorship validation to upcoming invoice webhook
* Fix organization delete sponsorship hooks
* Test org sponsorship service
* Fix sproc
* Fix build error
* Update emails
* Fix tests
* Skip local test
* Add newline
* Fix stripe subscription update
* Finish emails
* Skip test
* Fix unit tests
* Remove unused variable
* Fix unit tests
* Switch to handlebars ifs
* Remove ending email
* Remove reconfirmation template
* Switch naming convention
* Switch naming convention
* Fix migration
* Update copy and links
* Switch to using Guid in the method
* Remove unneeded css styles
* Add sql files to Sql.sqlproj
* Removed old comments
* Made name more verbose
* Fix SQL error
* Move unit tests to service
* Fix sp
* Revert "Move unit tests to service"
This reverts commit 1185bf3ec8ca36ccd75717ed2463adf8885159a6.
* Do repository validation in service layer
* Fix tests
* Fix merge conflicts and remove TODO
* Remove unneeded models
* Fix spacing and formatting
* Switch Org -> Organization
* Remove single use variables
* Switch method name
* Fix Controller
* Switch to obfuscating email
* Fix unit tests
Co-authored-by: Justin Baur <admin@justinbaur.com>
2021-11-19 16:25:06 -06:00
|
|
|
|
throw new Exception("Charge is null. " + eventCharge.Id);
|
2022-08-29 14:53:16 -04:00
|
|
|
|
}
|
2019-08-20 11:09:02 -04:00
|
|
|
|
return charge;
|
2022-08-29 16:06:55 -04:00
|
|
|
|
}
|
2022-08-29 15:53:48 -04:00
|
|
|
|
|
Families for Enterprise (#1714)
* Create common test infrastructure project
* Add helpers to further type PlanTypes
* Enable testing of ASP.net MVC controllers
Controller properties have all kinds of validations in the background.
In general, we don't user properties on our Controllers, so the easiest
way to allow for Autofixture-based testing of our Controllers is to just
omit setting all properties on them.
* Workaround for broken MemberAutoDataAttribute
https://github.com/AutoFixture/AutoFixture/pull/1164 shows that only
the first test case is pulled for this attribute.
This is a workaround that populates the provided parameters, left to
right, using AutoFixture to populate any remaining.
* WIP: Organization sponsorship flow
* Add Attribute to use the Bit Autodata dependency chain
BitAutoDataAttribute is used to mark a Theory as autopopulating
parameters.
Extract common attribute methods to to a helper class. Cannot
inherit a common base, since both require inheriting from different
Xunit base classes to work.
* WIP: scaffolding for families for enterprise sponsorship flow
* Fix broken tests
* Create sponsorship offer (#1688)
* Initial db work (#1687)
* Add organization sponsorship databases to all providers
* Generalize create and update for database, specialize in code
* Add PlanSponsorshipType to db model
* Write valid json for test entries
* Initial scaffolding of emails (#1686)
* Initial scaffolding of emails
* Work on adding models for FamilyForEnterprise emails
* Switch verbage
* Put preliminary copy in emails
* Skip test
* Families for enterprise/stripe integrations (#1699)
* Add PlanSponsorshipType to static store
* Add sponsorship type to token and creates sponsorship
* PascalCase properties
* Require sponsorship for remove
* Create subscription sponsorship helper class
* Handle Sponsored subscription changes
* Add sponsorship id to subscription metadata
* Make sponsoring references nullable
This state indicates that a sponsorship has lapsed, but was not able to
be reverted for billing reasons
* WIP: Validate and remove subscriptions
* Update sponsorships on organization and org user delete
* Add friendly name to organization sponsorship
* Add sponsorship available boolean to orgDetails
* Add sponsorship service to DI
* Use userId to find org users
* Send f4e offer email
* Simplify names of f4e mail messages
* Fix Stripe org default tax rates
* Universal sponsorship redeem api
* Populate user in current context
* Add product type to organization details
* Use upgrade path to change sponsorship
Sponsorships need to be annual to match the GB add-on charge rate
* Use organization and auth to find organization sponsorship
* Add resend sponsorship offer api endpoint
* Fix double email send
* Fix sponsorship upgrade options
* Add is sponsored item to subscription response
* Add sponsorship validation to upcoming invoice webhook
* Add sponsorship validation to upcoming invoice webhook
* Fix organization delete sponsorship hooks
* Test org sponsorship service
* Fix sproc
* Create common test infrastructure project
* Add helpers to further type PlanTypes
* Enable testing of ASP.net MVC controllers
Controller properties have all kinds of validations in the background.
In general, we don't user properties on our Controllers, so the easiest
way to allow for Autofixture-based testing of our Controllers is to just
omit setting all properties on them.
* Workaround for broken MemberAutoDataAttribute
https://github.com/AutoFixture/AutoFixture/pull/1164 shows that only
the first test case is pulled for this attribute.
This is a workaround that populates the provided parameters, left to
right, using AutoFixture to populate any remaining.
* WIP: Organization sponsorship flow
* Add Attribute to use the Bit Autodata dependency chain
BitAutoDataAttribute is used to mark a Theory as autopopulating
parameters.
Extract common attribute methods to to a helper class. Cannot
inherit a common base, since both require inheriting from different
Xunit base classes to work.
* WIP: scaffolding for families for enterprise sponsorship flow
* Fix broken tests
* Create sponsorship offer (#1688)
* Initial db work (#1687)
* Add organization sponsorship databases to all providers
* Generalize create and update for database, specialize in code
* Add PlanSponsorshipType to db model
* Write valid json for test entries
* Initial scaffolding of emails (#1686)
* Initial scaffolding of emails
* Work on adding models for FamilyForEnterprise emails
* Switch verbage
* Put preliminary copy in emails
* Skip test
* Families for enterprise/stripe integrations (#1699)
* Add PlanSponsorshipType to static store
* Add sponsorship type to token and creates sponsorship
* PascalCase properties
* Require sponsorship for remove
* Create subscription sponsorship helper class
* Handle Sponsored subscription changes
* Add sponsorship id to subscription metadata
* Make sponsoring references nullable
This state indicates that a sponsorship has lapsed, but was not able to
be reverted for billing reasons
* WIP: Validate and remove subscriptions
* Update sponsorships on organization and org user delete
* Add friendly name to organization sponsorship
* Add sponsorship available boolean to orgDetails
* Add sponsorship service to DI
* Use userId to find org users
* Send f4e offer email
* Simplify names of f4e mail messages
* Fix Stripe org default tax rates
* Universal sponsorship redeem api
* Populate user in current context
* Add product type to organization details
* Use upgrade path to change sponsorship
Sponsorships need to be annual to match the GB add-on charge rate
* Use organization and auth to find organization sponsorship
* Add resend sponsorship offer api endpoint
* Fix double email send
* Fix sponsorship upgrade options
* Add is sponsored item to subscription response
* Add sponsorship validation to upcoming invoice webhook
* Add sponsorship validation to upcoming invoice webhook
* Fix organization delete sponsorship hooks
* Test org sponsorship service
* Fix sproc
* Fix build error
* Update emails
* Fix tests
* Skip local test
* Add newline
* Fix stripe subscription update
* Finish emails
* Skip test
* Fix unit tests
* Remove unused variable
* Fix unit tests
* Switch to handlebars ifs
* Remove ending email
* Remove reconfirmation template
* Switch naming convention
* Switch naming convention
* Fix migration
* Update copy and links
* Switch to using Guid in the method
* Remove unneeded css styles
* Add sql files to Sql.sqlproj
* Removed old comments
* Made name more verbose
* Fix SQL error
* Move unit tests to service
* Fix sp
* Revert "Move unit tests to service"
This reverts commit 1185bf3ec8ca36ccd75717ed2463adf8885159a6.
* Do repository validation in service layer
* Fix tests
* Fix merge conflicts and remove TODO
* Remove unneeded models
* Fix spacing and formatting
* Switch Org -> Organization
* Remove single use variables
* Switch method name
* Fix Controller
* Switch to obfuscating email
* Fix unit tests
Co-authored-by: Justin Baur <admin@justinbaur.com>
2021-11-19 16:25:06 -06:00
|
|
|
|
private async Task<Invoice> GetInvoiceAsync(Stripe.Event parsedEvent, bool fresh = false)
|
2022-08-29 16:06:55 -04:00
|
|
|
|
{
|
Families for Enterprise (#1714)
* Create common test infrastructure project
* Add helpers to further type PlanTypes
* Enable testing of ASP.net MVC controllers
Controller properties have all kinds of validations in the background.
In general, we don't user properties on our Controllers, so the easiest
way to allow for Autofixture-based testing of our Controllers is to just
omit setting all properties on them.
* Workaround for broken MemberAutoDataAttribute
https://github.com/AutoFixture/AutoFixture/pull/1164 shows that only
the first test case is pulled for this attribute.
This is a workaround that populates the provided parameters, left to
right, using AutoFixture to populate any remaining.
* WIP: Organization sponsorship flow
* Add Attribute to use the Bit Autodata dependency chain
BitAutoDataAttribute is used to mark a Theory as autopopulating
parameters.
Extract common attribute methods to to a helper class. Cannot
inherit a common base, since both require inheriting from different
Xunit base classes to work.
* WIP: scaffolding for families for enterprise sponsorship flow
* Fix broken tests
* Create sponsorship offer (#1688)
* Initial db work (#1687)
* Add organization sponsorship databases to all providers
* Generalize create and update for database, specialize in code
* Add PlanSponsorshipType to db model
* Write valid json for test entries
* Initial scaffolding of emails (#1686)
* Initial scaffolding of emails
* Work on adding models for FamilyForEnterprise emails
* Switch verbage
* Put preliminary copy in emails
* Skip test
* Families for enterprise/stripe integrations (#1699)
* Add PlanSponsorshipType to static store
* Add sponsorship type to token and creates sponsorship
* PascalCase properties
* Require sponsorship for remove
* Create subscription sponsorship helper class
* Handle Sponsored subscription changes
* Add sponsorship id to subscription metadata
* Make sponsoring references nullable
This state indicates that a sponsorship has lapsed, but was not able to
be reverted for billing reasons
* WIP: Validate and remove subscriptions
* Update sponsorships on organization and org user delete
* Add friendly name to organization sponsorship
* Add sponsorship available boolean to orgDetails
* Add sponsorship service to DI
* Use userId to find org users
* Send f4e offer email
* Simplify names of f4e mail messages
* Fix Stripe org default tax rates
* Universal sponsorship redeem api
* Populate user in current context
* Add product type to organization details
* Use upgrade path to change sponsorship
Sponsorships need to be annual to match the GB add-on charge rate
* Use organization and auth to find organization sponsorship
* Add resend sponsorship offer api endpoint
* Fix double email send
* Fix sponsorship upgrade options
* Add is sponsored item to subscription response
* Add sponsorship validation to upcoming invoice webhook
* Add sponsorship validation to upcoming invoice webhook
* Fix organization delete sponsorship hooks
* Test org sponsorship service
* Fix sproc
* Create common test infrastructure project
* Add helpers to further type PlanTypes
* Enable testing of ASP.net MVC controllers
Controller properties have all kinds of validations in the background.
In general, we don't user properties on our Controllers, so the easiest
way to allow for Autofixture-based testing of our Controllers is to just
omit setting all properties on them.
* Workaround for broken MemberAutoDataAttribute
https://github.com/AutoFixture/AutoFixture/pull/1164 shows that only
the first test case is pulled for this attribute.
This is a workaround that populates the provided parameters, left to
right, using AutoFixture to populate any remaining.
* WIP: Organization sponsorship flow
* Add Attribute to use the Bit Autodata dependency chain
BitAutoDataAttribute is used to mark a Theory as autopopulating
parameters.
Extract common attribute methods to to a helper class. Cannot
inherit a common base, since both require inheriting from different
Xunit base classes to work.
* WIP: scaffolding for families for enterprise sponsorship flow
* Fix broken tests
* Create sponsorship offer (#1688)
* Initial db work (#1687)
* Add organization sponsorship databases to all providers
* Generalize create and update for database, specialize in code
* Add PlanSponsorshipType to db model
* Write valid json for test entries
* Initial scaffolding of emails (#1686)
* Initial scaffolding of emails
* Work on adding models for FamilyForEnterprise emails
* Switch verbage
* Put preliminary copy in emails
* Skip test
* Families for enterprise/stripe integrations (#1699)
* Add PlanSponsorshipType to static store
* Add sponsorship type to token and creates sponsorship
* PascalCase properties
* Require sponsorship for remove
* Create subscription sponsorship helper class
* Handle Sponsored subscription changes
* Add sponsorship id to subscription metadata
* Make sponsoring references nullable
This state indicates that a sponsorship has lapsed, but was not able to
be reverted for billing reasons
* WIP: Validate and remove subscriptions
* Update sponsorships on organization and org user delete
* Add friendly name to organization sponsorship
* Add sponsorship available boolean to orgDetails
* Add sponsorship service to DI
* Use userId to find org users
* Send f4e offer email
* Simplify names of f4e mail messages
* Fix Stripe org default tax rates
* Universal sponsorship redeem api
* Populate user in current context
* Add product type to organization details
* Use upgrade path to change sponsorship
Sponsorships need to be annual to match the GB add-on charge rate
* Use organization and auth to find organization sponsorship
* Add resend sponsorship offer api endpoint
* Fix double email send
* Fix sponsorship upgrade options
* Add is sponsored item to subscription response
* Add sponsorship validation to upcoming invoice webhook
* Add sponsorship validation to upcoming invoice webhook
* Fix organization delete sponsorship hooks
* Test org sponsorship service
* Fix sproc
* Fix build error
* Update emails
* Fix tests
* Skip local test
* Add newline
* Fix stripe subscription update
* Finish emails
* Skip test
* Fix unit tests
* Remove unused variable
* Fix unit tests
* Switch to handlebars ifs
* Remove ending email
* Remove reconfirmation template
* Switch naming convention
* Switch naming convention
* Fix migration
* Update copy and links
* Switch to using Guid in the method
* Remove unneeded css styles
* Add sql files to Sql.sqlproj
* Removed old comments
* Made name more verbose
* Fix SQL error
* Move unit tests to service
* Fix sp
* Revert "Move unit tests to service"
This reverts commit 1185bf3ec8ca36ccd75717ed2463adf8885159a6.
* Do repository validation in service layer
* Fix tests
* Fix merge conflicts and remove TODO
* Remove unneeded models
* Fix spacing and formatting
* Switch Org -> Organization
* Remove single use variables
* Switch method name
* Fix Controller
* Switch to obfuscating email
* Fix unit tests
Co-authored-by: Justin Baur <admin@justinbaur.com>
2021-11-19 16:25:06 -06:00
|
|
|
|
if (!(parsedEvent.Data.Object is Invoice eventInvoice))
|
2022-08-29 14:53:16 -04:00
|
|
|
|
{
|
2019-08-08 17:36:41 -04:00
|
|
|
|
throw new Exception("Invoice is null (from parsed event). " + parsedEvent.Id);
|
2022-08-29 14:53:16 -04:00
|
|
|
|
}
|
2022-06-24 14:20:32 -07:00
|
|
|
|
if (!fresh)
|
2022-05-31 10:55:56 -04:00
|
|
|
|
{
|
|
|
|
|
|
return eventInvoice;
|
2022-08-29 16:06:55 -04:00
|
|
|
|
}
|
2022-05-31 10:55:56 -04:00
|
|
|
|
var invoiceService = new InvoiceService();
|
2022-06-24 14:20:32 -07:00
|
|
|
|
var invoice = await invoiceService.GetAsync(eventInvoice.Id);
|
2020-12-09 14:04:46 -05:00
|
|
|
|
if (invoice == null)
|
2022-05-31 10:55:56 -04:00
|
|
|
|
{
|
|
|
|
|
|
throw new Exception("Invoice is null. " + eventInvoice.Id);
|
|
|
|
|
|
}
|
2019-08-20 11:09:02 -04:00
|
|
|
|
return invoice;
|
2022-08-29 16:06:55 -04:00
|
|
|
|
}
|
2022-05-31 10:55:56 -04:00
|
|
|
|
|
|
|
|
|
|
private async Task<Subscription> GetSubscriptionAsync(Stripe.Event parsedEvent, bool fresh = false)
|
2022-08-29 16:06:55 -04:00
|
|
|
|
{
|
2022-05-31 10:55:56 -04:00
|
|
|
|
if (!(parsedEvent.Data.Object is Subscription eventSubscription))
|
2022-08-29 16:06:55 -04:00
|
|
|
|
{
|
2022-05-31 10:55:56 -04:00
|
|
|
|
throw new Exception("Subscription is null (from parsed event). " + parsedEvent.Id);
|
2022-08-29 16:06:55 -04:00
|
|
|
|
}
|
2022-05-31 10:55:56 -04:00
|
|
|
|
if (!fresh)
|
2022-08-29 16:06:55 -04:00
|
|
|
|
{
|
2022-05-31 10:55:56 -04:00
|
|
|
|
return eventSubscription;
|
2022-08-29 16:06:55 -04:00
|
|
|
|
}
|
2022-05-31 10:55:56 -04:00
|
|
|
|
var subscriptionService = new SubscriptionService();
|
|
|
|
|
|
var subscription = await subscriptionService.GetAsync(eventSubscription.Id);
|
|
|
|
|
|
if (subscription == null)
|
2022-08-29 16:06:55 -04:00
|
|
|
|
{
|
2019-08-20 11:09:02 -04:00
|
|
|
|
throw new Exception("Subscription is null. " + eventSubscription.Id);
|
2022-08-29 16:06:55 -04:00
|
|
|
|
}
|
2019-08-20 11:09:02 -04:00
|
|
|
|
return subscription;
|
2022-08-29 16:06:55 -04:00
|
|
|
|
}
|
2022-05-31 10:55:56 -04:00
|
|
|
|
|
|
|
|
|
|
private async Task<Subscription> VerifyCorrectTaxRateForCharge(Invoice invoice, Subscription subscription)
|
2022-08-29 16:06:55 -04:00
|
|
|
|
{
|
2022-05-31 10:55:56 -04:00
|
|
|
|
if (!string.IsNullOrWhiteSpace(invoice?.CustomerAddress?.Country) && !string.IsNullOrWhiteSpace(invoice?.CustomerAddress?.PostalCode))
|
|
|
|
|
|
{
|
|
|
|
|
|
var localBitwardenTaxRates = await _taxRateRepository.GetByLocationAsync(
|
|
|
|
|
|
new TaxRate()
|
2022-08-29 15:53:48 -04:00
|
|
|
|
{
|
2022-05-31 10:55:56 -04:00
|
|
|
|
Country = invoice.CustomerAddress.Country,
|
|
|
|
|
|
PostalCode = invoice.CustomerAddress.PostalCode
|
2022-08-29 14:53:16 -04:00
|
|
|
|
}
|
2022-08-29 16:06:55 -04:00
|
|
|
|
);
|
|
|
|
|
|
|
2020-12-09 14:04:46 -05:00
|
|
|
|
if (localBitwardenTaxRates.Any())
|
2022-08-29 16:06:55 -04:00
|
|
|
|
{
|
2022-05-31 10:55:56 -04:00
|
|
|
|
var stripeTaxRate = await new TaxRateService().GetAsync(localBitwardenTaxRates.First().Id);
|
2020-12-09 14:04:46 -05:00
|
|
|
|
if (stripeTaxRate != null && !subscription.DefaultTaxRates.Any(x => x == stripeTaxRate))
|
2022-05-31 10:55:56 -04:00
|
|
|
|
{
|
|
|
|
|
|
subscription.DefaultTaxRates = new List<Stripe.TaxRate> { stripeTaxRate };
|
|
|
|
|
|
var subscriptionOptions = new SubscriptionUpdateOptions() { DefaultTaxRates = new List<string>() { stripeTaxRate.Id } };
|
|
|
|
|
|
subscription = await new SubscriptionService().UpdateAsync(subscription.Id, subscriptionOptions);
|
2022-08-29 15:53:48 -04:00
|
|
|
|
}
|
2022-05-31 10:55:56 -04:00
|
|
|
|
}
|
|
|
|
|
|
}
|
2020-12-09 14:04:46 -05:00
|
|
|
|
return subscription;
|
2022-08-29 16:06:55 -04:00
|
|
|
|
}
|
2022-08-29 14:53:16 -04:00
|
|
|
|
|
2019-09-23 09:03:18 -04:00
|
|
|
|
private static bool IsSponsoredSubscription(Subscription subscription) =>
|
|
|
|
|
|
StaticStore.SponsoredPlans.Any(p => p.StripePlanId == subscription.Id);
|
2022-08-29 15:53:48 -04:00
|
|
|
|
|
2019-02-03 00:05:35 -05:00
|
|
|
|
private async Task HandlePaymentFailed(Invoice invoice)
|
2022-08-29 16:06:55 -04:00
|
|
|
|
{
|
2019-02-03 00:05:35 -05:00
|
|
|
|
if (!invoice.Paid && invoice.AttemptCount > 1 && UnpaidAutoChargeInvoiceForSubscriptionCycle(invoice))
|
2022-08-29 14:53:16 -04:00
|
|
|
|
{
|
2019-08-20 11:09:02 -04:00
|
|
|
|
var subscriptionService = new SubscriptionService();
|
2019-02-15 16:18:53 -05:00
|
|
|
|
var subscription = await subscriptionService.GetAsync(invoice.SubscriptionId);
|
|
|
|
|
|
// attempt count 4 = 11 days after initial failure
|
|
|
|
|
|
if (invoice.AttemptCount > 3 && subscription.Items.Any(i => i.Price.Id == PremiumPlanId || i.Price.Id == PremiumPlanIdAppStore))
|
2022-08-29 15:53:48 -04:00
|
|
|
|
{
|
2022-05-31 10:55:56 -04:00
|
|
|
|
await CancelSubscription(invoice.SubscriptionId);
|
2020-12-09 14:04:46 -05:00
|
|
|
|
await VoidOpenInvoices(invoice.SubscriptionId);
|
2022-08-29 16:06:55 -04:00
|
|
|
|
}
|
2022-05-31 10:55:56 -04:00
|
|
|
|
else
|
2022-08-29 15:53:48 -04:00
|
|
|
|
{
|
2019-02-03 00:05:35 -05:00
|
|
|
|
await AttemptToPayInvoiceAsync(invoice);
|
2022-08-29 15:53:48 -04:00
|
|
|
|
}
|
2022-08-29 14:53:16 -04:00
|
|
|
|
}
|
|
|
|
|
|
}
|
2022-08-29 16:06:55 -04:00
|
|
|
|
|
2022-05-31 10:55:56 -04:00
|
|
|
|
private async Task CancelSubscription(string subscriptionId)
|
2022-08-29 16:06:55 -04:00
|
|
|
|
{
|
2022-05-31 10:55:56 -04:00
|
|
|
|
await new SubscriptionService().CancelAsync(subscriptionId, new SubscriptionCancelOptions());
|
2022-08-29 16:06:55 -04:00
|
|
|
|
}
|
|
|
|
|
|
|
2022-05-31 10:55:56 -04:00
|
|
|
|
private async Task VoidOpenInvoices(string subscriptionId)
|
2022-08-29 16:06:55 -04:00
|
|
|
|
{
|
2020-12-09 14:04:46 -05:00
|
|
|
|
var invoiceService = new InvoiceService();
|
2019-02-15 16:18:53 -05:00
|
|
|
|
var options = new InvoiceListOptions
|
2022-08-29 16:06:55 -04:00
|
|
|
|
{
|
2022-05-31 10:55:56 -04:00
|
|
|
|
Status = "open",
|
2019-09-23 09:03:18 -04:00
|
|
|
|
Subscription = subscriptionId
|
2022-08-29 16:06:55 -04:00
|
|
|
|
};
|
2019-02-03 00:05:35 -05:00
|
|
|
|
var invoices = invoiceService.List(options);
|
2022-05-31 10:55:56 -04:00
|
|
|
|
foreach (var invoice in invoices)
|
2022-08-29 16:06:55 -04:00
|
|
|
|
{
|
2019-02-03 00:05:35 -05:00
|
|
|
|
await invoiceService.VoidInvoiceAsync(invoice.Id);
|
2022-08-29 16:06:55 -04:00
|
|
|
|
}
|
|
|
|
|
|
}
|
2017-03-18 18:52:44 -04:00
|
|
|
|
}
|