diff --git a/src/Plugins/Payments.StripeCheckout/Areas/Admin/Views/StripeCheckout/Configure.cshtml b/src/Plugins/Payments.StripeCheckout/Areas/Admin/Views/StripeCheckout/Configure.cshtml index 9e975e36a..44cd6eea1 100644 --- a/src/Plugins/Payments.StripeCheckout/Areas/Admin/Views/StripeCheckout/Configure.cshtml +++ b/src/Plugins/Payments.StripeCheckout/Areas/Admin/Views/StripeCheckout/Configure.cshtml @@ -24,7 +24,8 @@ For plugin configuration please check:

1. Generate API keys from the Stripe Dashboard: Click here.
- 2. Register webhook endpoints with Stripe Click here.
+ 2. Register webhook endpoints with Stripe Click here. + Send it the event payment_intent.succeeded; to sell recurring products, also checkout.session.completed, invoice.paid, invoice.payment_failed and customer.subscription.deleted.
3. Your Webhook URL: @webhookUrl
4. Fill in your credentials below.
5. Save the configuration.
diff --git a/src/Plugins/Payments.StripeCheckout/Areas/Store/Views/StripeCheckout/Configure.cshtml b/src/Plugins/Payments.StripeCheckout/Areas/Store/Views/StripeCheckout/Configure.cshtml index 2055137b9..be4bc24b9 100644 --- a/src/Plugins/Payments.StripeCheckout/Areas/Store/Views/StripeCheckout/Configure.cshtml +++ b/src/Plugins/Payments.StripeCheckout/Areas/Store/Views/StripeCheckout/Configure.cshtml @@ -18,7 +18,8 @@ For plugin configuration please check:

1. Generate API keys from the Stripe Dashboard: Click here.
- 2. Register webhook endpoints with Stripe Click here.
+ 2. Register webhook endpoints with Stripe Click here. + Send it the event payment_intent.succeeded; to sell recurring products, also checkout.session.completed, invoice.paid, invoice.payment_failed and customer.subscription.deleted.
3. Your Webhook URL: @ViewBag.WebhookUrl
4. Fill in your credentials below.
5. Save the configuration.
diff --git a/src/Plugins/Payments.StripeCheckout/Services/IStripeCheckoutService.cs b/src/Plugins/Payments.StripeCheckout/Services/IStripeCheckoutService.cs index 21aabdc11..62784a9e6 100644 --- a/src/Plugins/Payments.StripeCheckout/Services/IStripeCheckoutService.cs +++ b/src/Plugins/Payments.StripeCheckout/Services/IStripeCheckoutService.cs @@ -7,5 +7,6 @@ public interface IStripeCheckoutService { Task CreateRedirectUrl(Order order); Task> Refund(PaymentTransaction paymentTransaction, double? amount); + Task> CancelSubscription(RecurringPayment recurringPayment); Task WebHookProcessPayment(string stripeSignature, string json); } \ No newline at end of file diff --git a/src/Plugins/Payments.StripeCheckout/Services/StripeCheckoutService.cs b/src/Plugins/Payments.StripeCheckout/Services/StripeCheckoutService.cs index 661757945..fc15393a5 100644 --- a/src/Plugins/Payments.StripeCheckout/Services/StripeCheckoutService.cs +++ b/src/Plugins/Payments.StripeCheckout/Services/StripeCheckoutService.cs @@ -1,6 +1,10 @@ using Grand.Business.Core.Commands.Checkout.Orders; +using Grand.Business.Core.Extensions; +using Grand.Business.Core.Interfaces.Checkout.Orders; using Grand.Business.Core.Interfaces.Checkout.Payments; using Grand.Business.Core.Interfaces.Common.Configuration; +using Grand.Business.Core.Queries.Checkout.Orders; +using Grand.Domain.Catalog; using Grand.Domain.Orders; using Grand.Domain.Payments; using Grand.Infrastructure; @@ -14,9 +18,23 @@ namespace Payments.StripeCheckout.Services; public class StripeCheckoutService : IStripeCheckoutService { + private const string OrderGuidKey = "order_guid"; + private const string RecurringPaymentIdKey = "recurring_payment_id"; + + //the first invoice of a subscription pays the order the customer placed, each renewal one cycle; any other + //(an update or a one-off invoice made in the Stripe dashboard) is not a cycle of the recurring payment + private const string SubscriptionCreate = "subscription_create"; + private const string SubscriptionCycle = "subscription_cycle"; + + //one client for every store: it keeps the connections, and a call to Stripe never holds a webhook, a checkout or + //a cancel for long; no retry, so a slow Stripe costs one timeout and the webhook is resent or the action repeated + private static readonly IHttpClient SharedHttpClient = new SystemNetHttpClient( + new HttpClient { Timeout = StripeCheckoutDefaults.RequestTimeout }, 0); + private readonly ILogger _logger; private readonly IMediator _mediator; private readonly IPaymentTransactionService _paymentTransactionService; + private readonly IRecurringPaymentService _recurringPaymentService; private readonly ISettingService _settingService; private readonly StripeCheckoutPaymentSettings _stripeCheckoutPaymentSettings; private readonly IContextAccessor _contextAccessor; @@ -27,6 +45,7 @@ public StripeCheckoutService( ILogger logger, IMediator mediator, IPaymentTransactionService paymentTransactionService, + IRecurringPaymentService recurringPaymentService, ISettingService settingService) { _contextAccessor = contextAccessor; @@ -34,6 +53,7 @@ public StripeCheckoutService( _logger = logger; _mediator = mediator; _paymentTransactionService = paymentTransactionService; + _recurringPaymentService = recurringPaymentService; _settingService = settingService; } @@ -112,19 +132,64 @@ private static string FormatCents(long cents) return (cents / 100.0).ToString("0.00", CultureInfo.InvariantCulture); } + public async Task> CancelSubscription(RecurringPayment recurringPayment) + { + if (string.IsNullOrEmpty(recurringPayment.ProviderReference)) + return ["The recurring payment has no Stripe subscription id. Check the Stripe dashboard and cancel the subscription there."]; + + //cancelled from the panel or My account, or by the shop when the cycles are paid: the key comes from the + //recurring payment's store, as two stores may use two Stripe accounts + var settings = await _settingService.LoadSetting(recurringPayment.StoreId); + if (string.IsNullOrEmpty(settings.ApiKey)) + return ["The Stripe API key is not set for the store of this recurring payment."]; + + var subscriptionService = new SubscriptionService(CreateStripeClient(settings.ApiKey)); + try + { + //at once and without a refund: the cycle paid last stays paid, nothing more is charged + var subscription = await subscriptionService.CancelAsync(recurringPayment.ProviderReference); + return subscription.Status == "canceled" + ? [] + : [$"Stripe left subscription {subscription.Id} {subscription.Status}."]; + } + catch (StripeException e) + { + //Stripe refuses to cancel a subscription twice: one it ended already is what was asked for + if (await IsSubscriptionCanceled(subscriptionService, recurringPayment.ProviderReference)) + return []; + + _logger.LogError(e, "Stripe subscription {SubscriptionId} could not be cancelled", + recurringPayment.ProviderReference); + return [e.StripeError?.Message ?? e.Message]; + } + catch (Exception e) + { + _logger.LogError(e, "Stripe subscription {SubscriptionId} could not be cancelled", + recurringPayment.ProviderReference); + return [$"Stripe could not be reached ({e.Message}). Try again, or cancel the subscription in the Stripe dashboard."]; + } + } + + private async Task IsSubscriptionCanceled(SubscriptionService subscriptionService, string subscriptionId) + { + try + { + return (await subscriptionService.GetAsync(subscriptionId)).Status == "canceled"; + } + catch (Exception e) + { + _logger.LogError(e, "Stripe subscription {SubscriptionId} could not be read", subscriptionId); + return false; + } + } + public async Task WebHookProcessPayment(string stripeSignature, string json) { + Event stripeEvent; try { - var stripeEvent = EventUtility.ConstructEvent(json, stripeSignature, + stripeEvent = EventUtility.ConstructEvent(json, stripeSignature, _stripeCheckoutPaymentSettings.WebhookEndpointSecret); - // Handle the event - if (stripeEvent.Type == EventTypes.PaymentIntentSucceeded) - { - var paymentIntent = stripeEvent.Data.Object as PaymentIntent; - await CreatePaymentTransaction(paymentIntent); - return true; - } } catch (StripeException e) { @@ -132,12 +197,143 @@ public async Task WebHookProcessPayment(string stripeSignature, string jso return false; } + //a recurring payment event that fails throws, so the webhook answers with an error and Stripe sends it + //again; the recurring payment commands record each report once + switch (stripeEvent.Type) + { + case EventTypes.PaymentIntentSucceeded: + await CreatePaymentTransaction(stripeEvent.Data.Object as PaymentIntent); + return true; + case EventTypes.CheckoutSessionCompleted: + await RecordSubscriptionStarted(stripeEvent.Data.Object as Session); + return true; + case EventTypes.InvoicePaid: + await RecordInvoicePaid(stripeEvent.Data.Object as Invoice); + return true; + case EventTypes.InvoicePaymentFailed: + await RecordInvoiceFailed(stripeEvent.Data.Object as Invoice); + return true; + case EventTypes.CustomerSubscriptionDeleted: + await RecordSubscriptionEnded(stripeEvent.Data.Object as Subscription); + return true; + } + return false; } + private async Task RecordSubscriptionStarted(Session session) + { + //a one-off payment has no subscription; its payment intent marks the order paid + if (session is not { Mode: "subscription" } || string.IsNullOrEmpty(session.SubscriptionId) || + session.Metadata?.TryGetValue(RecurringPaymentIdKey, out var recurringPaymentId) != true) + return; + + await _mediator.Send(new RecordRecurringPaymentReferenceCommand { + RecurringPaymentId = recurringPaymentId, ProviderReference = session.SubscriptionId + }); + } + + private async Task RecordInvoicePaid(Invoice invoice) + { + if (!IsRecurringCycle(invoice, out var subscription, out var recurringPaymentId)) + return; + + //in the smallest unit, as the price was created with the order total * 100 + var amount = invoice.AmountPaid / 100.0; + if (invoice.BillingReason == SubscriptionCreate) + await MarkInitialOrderPaid(invoice, subscription.Metadata, amount); + + await _mediator.Send(new RecordRecurringPaymentCycleCommand { + RecurringPaymentId = recurringPaymentId, + ProviderReference = subscription.SubscriptionId, + CycleReference = invoice.Id, + Amount = amount, + PaidOnUtc = invoice.StatusTransitions?.PaidAt ?? DateTime.UtcNow, + //the end of the period the invoice paid for is when Stripe charges the next one + NextPaymentDateUtc = invoice.Lines?.Data?.FirstOrDefault()?.Period?.End + }); + } + + private async Task MarkInitialOrderPaid(Invoice invoice, Dictionary metadata, double amount) + { + if (metadata?.TryGetValue(OrderGuidKey, out var value) != true || !Guid.TryParse(value, out var orderGuid)) + { + _logger.LogError("Stripe invoice {InvoiceId}: the subscription names no order", invoice.Id); + return; + } + + var paymentTransaction = await _paymentTransactionService.GetOrderByGuid(orderGuid); + if (paymentTransaction == null || + !invoice.Currency.Equals(paymentTransaction.CurrencyCode, StringComparison.InvariantCultureIgnoreCase)) + { + _logger.LogError("Stripe invoice {InvoiceId}: paymentTransaction is null or currency is not equal", + invoice.Id); + return; + } + + //paid by an earlier delivery of this event, or by staff + if (!await _mediator.Send(new CanMarkPaymentTransactionAsPaidQuery { PaymentTransaction = paymentTransaction })) + return; + + //a refund of the order goes to the payment intent, which a subscription's invoice does not carry + var paymentIntentId = await GetInvoicePaymentIntentId(invoice.Id, paymentTransaction.StoreId); + paymentTransaction.AuthorizationTransactionId = paymentIntentId; + await _mediator.Send(new MarkAsPaidCommand { + PaymentTransaction = paymentTransaction, + CreatedBy = StripeCheckoutDefaults.ProviderSystemName, + Amount = amount, + Reference = paymentIntentId ?? invoice.Id + }); + } + + private async Task GetInvoicePaymentIntentId(string invoiceId, string storeId) + { + var settings = await _settingService.LoadSetting(storeId); + var payments = await new InvoicePaymentService(CreateStripeClient(settings.ApiKey)) + .ListAsync(new InvoicePaymentListOptions { Invoice = invoiceId, Status = "paid" }); + return payments.Data.FirstOrDefault()?.Payment?.PaymentIntentId; + } + + private async Task RecordInvoiceFailed(Invoice invoice) + { + if (!IsRecurringCycle(invoice, out var subscription, out var recurringPaymentId)) + return; + + await _mediator.Send(new RecordRecurringPaymentFailureCommand { + RecurringPaymentId = recurringPaymentId, + ProviderReference = subscription.SubscriptionId, + CycleReference = invoice.Id, + Reason = $"Stripe could not charge invoice {invoice.Number ?? invoice.Id} (attempt {invoice.AttemptCount})" + }); + } + + private async Task RecordSubscriptionEnded(Subscription subscription) + { + if (subscription?.Metadata?.TryGetValue(RecurringPaymentIdKey, out var recurringPaymentId) != true) + return; + + await _mediator.Send(new RecordRecurringPaymentEndedCommand { + RecurringPaymentId = recurringPaymentId, ProviderReference = subscription.Id + }); + } + + private static bool IsRecurringCycle(Invoice invoice, out InvoiceParentSubscriptionDetails subscription, + out string recurringPaymentId) + { + subscription = invoice?.Parent?.SubscriptionDetails; + recurringPaymentId = null; + return invoice?.BillingReason is SubscriptionCreate or SubscriptionCycle && + !string.IsNullOrEmpty(subscription?.SubscriptionId) && + subscription.Metadata?.TryGetValue(RecurringPaymentIdKey, out recurringPaymentId) == true; + } + private async Task CreatePaymentTransaction(PaymentIntent paymentIntent) { - if (paymentIntent.Metadata.TryGetValue("order_guid", out var order_guid) + //a subscription's payments carry no order: its invoices record them + if (paymentIntent.Metadata?.ContainsKey(OrderGuidKey) != true) + return; + + if (paymentIntent.Metadata.TryGetValue(OrderGuidKey, out var order_guid) && Guid.TryParse(order_guid, out var orderGuid)) { var paymentTransaction = await _paymentTransactionService.GetOrderByGuid(orderGuid); @@ -175,6 +371,12 @@ private async Task CreateUrlSession(Order order) { var storeLocation = _contextAccessor.StoreContext.CurrentHost.Url.TrimEnd('/'); + //a recurring payment cancelled before the order was paid leaves an order to pay once + var recurringPayment = await _recurringPaymentService.GetRecurringPaymentByInitialOrderId(order.Id); + if (recurringPayment != null && recurringPayment.Status.HasEnded()) + recurringPayment = null; + + var metadata = new Dictionary { { OrderGuidKey, order.OrderGuid.ToString() } }; var options = new SessionCreateOptions { LineItems = [ new SessionLineItemOptions { @@ -183,20 +385,37 @@ private async Task CreateUrlSession(Order order) ProductData = new SessionLineItemPriceDataProductDataOptions { Name = string.Format(_stripeCheckoutPaymentSettings.Line, order.OrderNumber) }, - Currency = order.CustomerCurrencyCode + Currency = order.CustomerCurrencyCode, + //every cycle charges the order total again, as each cycle order is a copy of this one + Recurring = recurringPayment == null + ? null + : new SessionLineItemPriceDataRecurringOptions { + Interval = Interval(recurringPayment.CyclePeriodId), + IntervalCount = recurringPayment.CycleLength + } }, Quantity = 1 } ], ClientReferenceId = order.Id, CustomerEmail = order.CustomerEmail, - PaymentIntentData = new SessionPaymentIntentDataOptions { - Metadata = new Dictionary { { "order_guid", order.OrderGuid.ToString() } } - }, - Mode = "payment", + Mode = recurringPayment == null ? "payment" : "subscription", SuccessUrl = $"{storeLocation}/orderdetails/{order.Id}", CancelUrl = $"{storeLocation}/Plugins/PaymentStripeCheckout/CancelOrder/{order.Id}" }; + if (recurringPayment == null) + { + options.PaymentIntentData = new SessionPaymentIntentDataOptions { Metadata = metadata }; + } + else + { + //the session names the recurring payment for the subscription's reference, the subscription for its + //invoices; the total number of cycles stays with the shop, which cancels the subscription when the + //last one is paid + metadata[RecurringPaymentIdKey] = recurringPayment.Id; + options.Metadata = metadata; + options.SubscriptionData = new SessionSubscriptionDataOptions { Metadata = metadata }; + } //the api key is store-specific, so it travels with the client - the static //StripeConfiguration.ApiKey is process-wide and two stores checking out at the same time //would overwrite each other's credentials @@ -206,8 +425,19 @@ private async Task CreateUrlSession(Order order) return session; } + private static string Interval(RecurringCyclePeriod period) + { + return period switch { + RecurringCyclePeriod.Days => "day", + RecurringCyclePeriod.Weeks => "week", + RecurringCyclePeriod.Months => "month", + RecurringCyclePeriod.Years => "year", + _ => throw new ArgumentOutOfRangeException(nameof(period), period, "Unknown recurring cycle period") + }; + } + protected virtual IStripeClient CreateStripeClient(string apiKey) { - return new StripeClient(apiKey); + return new StripeClient(apiKey, httpClient: SharedHttpClient); } } \ No newline at end of file diff --git a/src/Plugins/Payments.StripeCheckout/StripeCheckoutDefaults.cs b/src/Plugins/Payments.StripeCheckout/StripeCheckoutDefaults.cs index 37f571711..19c4974e0 100644 --- a/src/Plugins/Payments.StripeCheckout/StripeCheckoutDefaults.cs +++ b/src/Plugins/Payments.StripeCheckout/StripeCheckoutDefaults.cs @@ -7,4 +7,10 @@ public static class StripeCheckoutDefaults public const string ConfigurationUrl = "/Admin/StripeCheckout/Configure"; public static string WebHook => "Plugin.Payments.StripeCheckout.WebHook"; public static string PaymentInfo => "Plugin.Payments.StripeCheckout.PaymentInfo"; + + /// + /// How long one call to Stripe may take: well below 10 s, as Stripe.net's own 80 s is too long for a webhook, + /// a checkout or a cancel to wait + /// + public static TimeSpan RequestTimeout => TimeSpan.FromSeconds(5); } \ No newline at end of file diff --git a/src/Plugins/Payments.StripeCheckout/StripeCheckoutPaymentProvider.cs b/src/Plugins/Payments.StripeCheckout/StripeCheckoutPaymentProvider.cs index 8ac555ed0..58b53b590 100644 --- a/src/Plugins/Payments.StripeCheckout/StripeCheckoutPaymentProvider.cs +++ b/src/Plugins/Payments.StripeCheckout/StripeCheckoutPaymentProvider.cs @@ -12,6 +12,7 @@ namespace Payments.StripeCheckout; public class StripeCheckoutPaymentProvider : IPaymentProvider { private readonly IOrderService _orderService; + private readonly IRecurringPaymentService _recurringPaymentService; private readonly StripeCheckoutPaymentSettings _stripeCheckoutPaymentSettings; private readonly IStripeCheckoutService _stripeCheckoutService; private readonly IRequestTranslationService _translationService; @@ -21,10 +22,12 @@ public class StripeCheckoutPaymentProvider : IPaymentProvider public StripeCheckoutPaymentProvider( IRequestTranslationService translationService, IOrderService orderService, + IRecurringPaymentService recurringPaymentService, StripeCheckoutPaymentSettings stripeCheckoutPaymentSettings, IStripeCheckoutService stripeCheckoutService) { _translationService = translationService; _orderService = orderService; + _recurringPaymentService = recurringPaymentService; _stripeCheckoutPaymentSettings = stripeCheckoutPaymentSettings; _stripeCheckoutService = stripeCheckoutService; } @@ -173,7 +176,15 @@ public async Task CanRePostRedirectPayment(PaymentTransaction paymentTrans if ((DateTime.UtcNow - paymentTransaction.CreatedOnUtc).TotalMinutes < 1) return false; - return await Task.FromResult(true); + //the customer completed the checkout and Stripe runs the subscription, whose first invoice is still to be + //reported: paying again would start a second subscription charging every cycle twice + var order = await _orderService.GetOrderByGuid(paymentTransaction.OrderGuid); + if (order != null && + await _recurringPaymentService.GetRecurringPaymentByInitialOrderId(order.Id) is { } recurringPayment && + !string.IsNullOrEmpty(recurringPayment.ProviderReference)) + return false; + + return true; } /// @@ -229,6 +240,27 @@ public async Task SupportVoid() return await Task.FromResult(false); } + /// + /// Gets a value indicating whether recurring payments are supported: a recurring order is paid with a Stripe + /// subscription, whose invoices report every cycle + /// + public Task SupportRecurringPayment() + { + return Task.FromResult(true); + } + + /// + /// Cancels the Stripe subscription of a recurring payment + /// + public async Task CancelRecurringPayment(RecurringPayment recurringPayment) + { + var result = new CancelRecurringPaymentResult(); + foreach (var error in await _stripeCheckoutService.CancelSubscription(recurringPayment)) + result.AddError(error); + + return result; + } + /// /// Gets a payment method type /// diff --git a/src/Tests/Grand.Modules.Tests/Plugins/Payments/StripeCheckoutPaymentProviderTests.cs b/src/Tests/Grand.Modules.Tests/Plugins/Payments/StripeCheckoutPaymentProviderTests.cs index 4fd23537e..91e58c222 100644 --- a/src/Tests/Grand.Modules.Tests/Plugins/Payments/StripeCheckoutPaymentProviderTests.cs +++ b/src/Tests/Grand.Modules.Tests/Plugins/Payments/StripeCheckoutPaymentProviderTests.cs @@ -1,5 +1,6 @@ using Grand.Business.Core.Interfaces.Checkout.Orders; using Grand.Business.Core.Utilities.Checkout; +using Grand.Domain.Orders; using Grand.Domain.Payments; using Grand.Web.Common.Localization; using Microsoft.VisualStudio.TestTools.UnitTesting; @@ -23,8 +24,71 @@ public void Init() _stripeCheckoutService = new Mock(); _stripeCheckoutService.Setup(s => s.Refund(It.IsAny(), It.IsAny())) .ReturnsAsync(new List()); + _orderService = new Mock(); + _recurringPaymentService = new Mock(); _provider = new StripeCheckoutPaymentProvider(Mock.Of(), - Mock.Of(), new StripeCheckoutPaymentSettings(), _stripeCheckoutService.Object); + _orderService.Object, _recurringPaymentService.Object, new StripeCheckoutPaymentSettings(), + _stripeCheckoutService.Object); + } + + private Mock _orderService; + private Mock _recurringPaymentService; + + [TestMethod] + public async Task SupportRecurringPayment_IsTrue() + { + Assert.IsTrue(await _provider.SupportRecurringPayment()); + } + + [TestMethod] + public async Task CancelRecurringPayment_CancelsTheSubscription() + { + var recurringPayment = new RecurringPayment { ProviderReference = "sub_1" }; + _stripeCheckoutService.Setup(s => s.CancelSubscription(recurringPayment)).ReturnsAsync(new List()); + + Assert.IsTrue((await _provider.CancelRecurringPayment(recurringPayment)).Success); + _stripeCheckoutService.Verify(s => s.CancelSubscription(recurringPayment), Times.Once); + } + + [TestMethod] + public async Task CancelRecurringPayment_ServiceErrors_AreReturned() + { + _stripeCheckoutService.Setup(s => s.CancelSubscription(It.IsAny())) + .ReturnsAsync(new List { "No such subscription" }); + + var result = await _provider.CancelRecurringPayment(new RecurringPayment()); + + Assert.IsFalse(result.Success); + CollectionAssert.Contains(result.Errors.ToList(), "No such subscription"); + } + + private PaymentTransaction OldTransaction() + { + var orderGuid = Guid.NewGuid(); + _orderService.Setup(x => x.GetOrderByGuid(orderGuid)).ReturnsAsync(new Order { Id = "o1" }); + return new PaymentTransaction { OrderGuid = orderGuid, CreatedOnUtc = DateTime.UtcNow.AddMinutes(-5) }; + } + + [TestMethod] + public async Task CanRePostRedirectPayment_StandardOrPendingRecurringOrder_IsTrue() + { + var transaction = OldTransaction(); + Assert.IsTrue(await _provider.CanRePostRedirectPayment(transaction)); + + _recurringPaymentService.Setup(x => x.GetRecurringPaymentByInitialOrderId("o1")) + .ReturnsAsync(new RecurringPayment()); + Assert.IsTrue(await _provider.CanRePostRedirectPayment(transaction)); + } + + [TestMethod] + public async Task CanRePostRedirectPayment_SubscriptionStarted_IsFalse() + { + //paying again would start a second subscription + var transaction = OldTransaction(); + _recurringPaymentService.Setup(x => x.GetRecurringPaymentByInitialOrderId("o1")) + .ReturnsAsync(new RecurringPayment { ProviderReference = "sub_1" }); + + Assert.IsFalse(await _provider.CanRePostRedirectPayment(transaction)); } [TestMethod] diff --git a/src/Tests/Grand.Modules.Tests/Plugins/Payments/StripeCheckoutServiceTests.cs b/src/Tests/Grand.Modules.Tests/Plugins/Payments/StripeCheckoutServiceTests.cs index 64206aaee..4d74a116a 100644 --- a/src/Tests/Grand.Modules.Tests/Plugins/Payments/StripeCheckoutServiceTests.cs +++ b/src/Tests/Grand.Modules.Tests/Plugins/Payments/StripeCheckoutServiceTests.cs @@ -1,8 +1,15 @@ using System.Net; +using System.Security.Cryptography; using System.Text; +using Grand.Business.Core.Commands.Checkout.Orders; +using Grand.Business.Core.Interfaces.Checkout.Orders; using Grand.Business.Core.Interfaces.Checkout.Payments; using Grand.Business.Core.Interfaces.Common.Configuration; +using Grand.Business.Core.Queries.Checkout.Orders; +using Grand.Domain.Catalog; +using Grand.Domain.Orders; using Grand.Domain.Payments; +using Grand.Domain.Stores; using Grand.Infrastructure; using Grand.Mediator; using Microsoft.Extensions.Logging.Abstractions; @@ -17,7 +24,12 @@ namespace Grand.Modules.Tests.Plugins.Payments; [TestClass] public class StripeCheckoutServiceTests { + private const string WebhookSecret = "whsec_test"; + private FakeStripeHandler _handler; + private Mock _mediator; + private Mock _paymentTransactionService; + private Mock _recurringPaymentService; private TestStripeCheckoutService _service; private Mock _settingService; @@ -28,11 +40,20 @@ public void Init() _settingService = new Mock(); _settingService.Setup(s => s.LoadSetting("s2")) .ReturnsAsync(new StripeCheckoutPaymentSettings { ApiKey = "sk_s2" }); - _service = new TestStripeCheckoutService(_handler, Mock.Of(), + _mediator = new Mock(); + _paymentTransactionService = new Mock(); + _recurringPaymentService = new Mock(); + var storeContext = new Mock(); + storeContext.Setup(x => x.CurrentHost).Returns(new DomainHost { Url = "https://shop.test/" }); + var contextAccessor = new Mock(); + contextAccessor.Setup(x => x.StoreContext).Returns(storeContext.Object); + _service = new TestStripeCheckoutService(_handler, contextAccessor.Object, //the injected settings are the current store's, never the transaction's - new StripeCheckoutPaymentSettings { ApiKey = "sk_current" }, - NullLogger.Instance, Mock.Of(), - Mock.Of(), _settingService.Object); + new StripeCheckoutPaymentSettings { + ApiKey = "sk_current", WebhookEndpointSecret = WebhookSecret, Line = "Order {0}" + }, + NullLogger.Instance, _mediator.Object, + _paymentTransactionService.Object, _recurringPaymentService.Object, _settingService.Object); } private static PaymentTransaction Transaction(string paymentIntentId = "pi_1") @@ -228,6 +249,332 @@ public async Task Refund_PendingStatus_Succeeds() Assert.AreEqual(0, errors.Count); } + private static Order Order() + { + return new Order { + Id = "o1", OrderGuid = Guid.Parse("11111111-1111-1111-1111-111111111111"), OrderNumber = 7, + OrderTotal = 19.99, CustomerCurrencyCode = "USD", CustomerEmail = "c@shop.test" + }; + } + + private const string Session = """{"id":"cs_1","object":"checkout.session","url":"https://checkout.stripe.test/cs_1"}"""; + + [TestMethod] + public async Task CreateRedirectUrl_StandardOrder_IsAOneOffPaymentNamingTheOrder() + { + _handler.Respond(HttpMethod.Post, HttpStatusCode.OK, Session); + + Assert.AreEqual("https://checkout.stripe.test/cs_1", await _service.CreateRedirectUrl(Order())); + + var body = Uri.UnescapeDataString(_handler.Requests[0].Body); + StringAssert.Contains(body, "mode=payment"); + StringAssert.Contains(body, "payment_intent_data[metadata][order_guid]=11111111-1111-1111-1111-111111111111"); + Assert.IsFalse(body.Contains("recurring")); + Assert.IsFalse(body.Contains("subscription_data")); + } + + [TestMethod] + public async Task CreateRedirectUrl_RecurringOrder_StartsASubscriptionOfTheOrderTotalEveryCycle() + { + _recurringPaymentService.Setup(x => x.GetRecurringPaymentByInitialOrderId("o1")).ReturnsAsync( + new RecurringPayment { + Id = "rp1", CycleLength = 3, CyclePeriodId = RecurringCyclePeriod.Months, TotalCycles = 4 + }); + _handler.Respond(HttpMethod.Post, HttpStatusCode.OK, Session); + + await _service.CreateRedirectUrl(Order()); + + var body = Uri.UnescapeDataString(_handler.Requests[0].Body); + StringAssert.Contains(body, "mode=subscription"); + StringAssert.Contains(body, "line_items[0][price_data][recurring][interval]=month"); + StringAssert.Contains(body, "line_items[0][price_data][recurring][interval_count]=3"); + StringAssert.Contains(body, "line_items[0][price_data][unit_amount_decimal]=1999"); + StringAssert.Contains(body, "subscription_data[metadata][recurring_payment_id]=rp1"); + StringAssert.Contains(body, "subscription_data[metadata][order_guid]=11111111-1111-1111-1111-111111111111"); + StringAssert.Contains(body, "metadata[recurring_payment_id]=rp1"); + //Stripe refuses payment intent data on a subscription session + Assert.IsFalse(body.Contains("payment_intent_data")); + } + + [TestMethod] + [DataRow(RecurringCyclePeriod.Days, "day")] + [DataRow(RecurringCyclePeriod.Weeks, "week")] + [DataRow(RecurringCyclePeriod.Years, "year")] + public async Task CreateRedirectUrl_RecurringOrder_MapsTheCyclePeriod(RecurringCyclePeriod period, string interval) + { + _recurringPaymentService.Setup(x => x.GetRecurringPaymentByInitialOrderId("o1")).ReturnsAsync( + new RecurringPayment { Id = "rp1", CycleLength = 1, CyclePeriodId = period }); + _handler.Respond(HttpMethod.Post, HttpStatusCode.OK, Session); + + await _service.CreateRedirectUrl(Order()); + + StringAssert.Contains(Uri.UnescapeDataString(_handler.Requests[0].Body), + $"line_items[0][price_data][recurring][interval]={interval}"); + } + + [TestMethod] + [DataRow(RecurringPaymentStatus.Cancelled)] + [DataRow(RecurringPaymentStatus.Completed)] + public async Task CreateRedirectUrl_RecurringPaymentEnded_PaysTheOrderOnce(RecurringPaymentStatus status) + { + _recurringPaymentService.Setup(x => x.GetRecurringPaymentByInitialOrderId("o1")).ReturnsAsync( + new RecurringPayment { Id = "rp1", CycleLength = 1, Status = status }); + _handler.Respond(HttpMethod.Post, HttpStatusCode.OK, Session); + + await _service.CreateRedirectUrl(Order()); + + var body = Uri.UnescapeDataString(_handler.Requests[0].Body); + StringAssert.Contains(body, "mode=payment"); + Assert.IsFalse(body.Contains("recurring")); + } + + private static RecurringPayment Subscribed(string subscriptionId = "sub_1") + { + return new RecurringPayment { Id = "rp1", StoreId = "s2", ProviderReference = subscriptionId }; + } + + private static string SubscriptionJson(string status) + { + return $$"""{"id":"sub_1","object":"subscription","status":"{{status}}"}"""; + } + + [TestMethod] + public async Task CancelSubscription_CancelsItWithTheRecurringPaymentStoreKey() + { + _handler.Respond(HttpMethod.Delete, HttpStatusCode.OK, SubscriptionJson("canceled")); + + var errors = await _service.CancelSubscription(Subscribed()); + + Assert.AreEqual(0, errors.Count); + var request = _handler.Requests.Single().Request; + Assert.AreEqual(HttpMethod.Delete, request.Method); + Assert.AreEqual("/v1/subscriptions/sub_1", request.RequestUri!.AbsolutePath); + Assert.AreEqual("Bearer sk_s2", request.Headers.Authorization!.ToString()); + } + + [TestMethod] + public async Task CancelSubscription_StripeRefusesOneCancelledAlready_Succeeds() + { + _handler.Respond(HttpMethod.Delete, HttpStatusCode.BadRequest, + """{"error":{"type":"invalid_request_error","message":"No such subscription: 'sub_1'"}}"""); + _handler.Respond(HttpMethod.Get, HttpStatusCode.OK, SubscriptionJson("canceled")); + + Assert.AreEqual(0, (await _service.CancelSubscription(Subscribed())).Count); + } + + [TestMethod] + public async Task CancelSubscription_StripeRefusesOneStillRunning_ReturnsStripeMessage() + { + _handler.Respond(HttpMethod.Delete, HttpStatusCode.BadRequest, + """{"error":{"type":"invalid_request_error","message":"Something is wrong."}}"""); + _handler.Respond(HttpMethod.Get, HttpStatusCode.OK, SubscriptionJson("active")); + + var errors = await _service.CancelSubscription(Subscribed()); + + Assert.AreEqual(1, errors.Count); + StringAssert.Contains(errors[0], "Something is wrong."); + } + + [TestMethod] + public async Task CancelSubscription_StripeUnreachable_ReturnsErrorInsteadOfThrowing() + { + _handler.Fail(new TaskCanceledException("timeout")); + + var errors = await _service.CancelSubscription(Subscribed()); + + Assert.AreEqual(1, errors.Count); + StringAssert.Contains(errors[0], "Stripe dashboard"); + } + + [TestMethod] + public async Task CancelSubscription_NoSubscriptionOrNoApiKey_ReturnsErrorWithoutCallingStripe() + { + Assert.AreEqual(1, (await _service.CancelSubscription(Subscribed(null))).Count); + + _settingService.Setup(s => s.LoadSetting("s2")) + .ReturnsAsync(new StripeCheckoutPaymentSettings()); + Assert.AreEqual(1, (await _service.CancelSubscription(Subscribed())).Count); + + Assert.AreEqual(0, _handler.Requests.Count); + } + + private static string SignatureFor(string json) + { + var timestamp = DateTimeOffset.UtcNow.ToUnixTimeSeconds(); + using var hmac = new HMACSHA256(Encoding.UTF8.GetBytes(WebhookSecret)); + var signature = Convert.ToHexStringLower(hmac.ComputeHash(Encoding.UTF8.GetBytes($"{timestamp}.{json}"))); + return $"t={timestamp},v1={signature}"; + } + + private Task Deliver(string type, string dataObject) + { + var json = $$$"""{"id":"evt_1","object":"event","api_version":"{{{StripeConfiguration.ApiVersion}}}","type":"{{{type}}}","data":{"object":{{{dataObject}}}}}"""; + return _service.WebHookProcessPayment(SignatureFor(json), json); + } + + private const string SubscriptionMetadata = + """{"recurring_payment_id":"rp1","order_guid":"11111111-1111-1111-1111-111111111111"}"""; + + private static string InvoiceJson(string billingReason, string subscriptionMetadata = SubscriptionMetadata) + { + //paid on 2026-01-01, the period it paid for ends on 2026-02-01 + return $$$""" + {"id":"in_2","object":"invoice","billing_reason":"{{{billingReason}}}","amount_paid":1999, + "currency":"usd","number":"INV-2","attempt_count":2,"status_transitions":{"paid_at":1767225600}, + "lines":{"object":"list","data":[{"id":"il_1","object":"line_item","period":{"start":1767225600,"end":1769904000}}]}, + "parent":{"type":"subscription_details","subscription_details":{"subscription":"sub_1", + "metadata":{{{subscriptionMetadata}}} } } } + """; + } + + [TestMethod] + public async Task WebHook_InvoicePaidForARenewal_RecordsTheCycle() + { + Assert.IsTrue(await Deliver("invoice.paid", InvoiceJson("subscription_cycle"))); + + _mediator.Verify(x => x.Send(It.Is(c => + c.RecurringPaymentId == "rp1" && c.ProviderReference == "sub_1" && c.CycleReference == "in_2" && + c.Amount == 19.99 && c.PaidOnUtc == new DateTime(2026, 1, 1, 0, 0, 0, DateTimeKind.Utc) && + c.NextPaymentDateUtc == new DateTime(2026, 2, 1, 0, 0, 0, DateTimeKind.Utc)), + It.IsAny()), Times.Once); + //only the first invoice pays the order the customer placed + _mediator.Verify(x => x.Send(It.IsAny(), It.IsAny()), Times.Never); + } + + private PaymentTransaction SetupInitialPayment(bool canMarkPaid = true) + { + var transaction = new PaymentTransaction { Id = "t1", StoreId = "s2", CurrencyCode = "USD" }; + _paymentTransactionService.Setup(x => x.GetOrderByGuid(Order().OrderGuid)).ReturnsAsync(transaction); + _mediator.Setup(x => x.Send(It.IsAny(), It.IsAny())) + .ReturnsAsync(canMarkPaid); + return transaction; + } + + [TestMethod] + public async Task WebHook_InvoicePaidForTheSubscriptionStart_MarksTheOrderPaidAndRecordsCycleOne() + { + var transaction = SetupInitialPayment(); + _handler.Respond(HttpMethod.Get, HttpStatusCode.OK, """ + {"object":"list","data":[{"id":"inpay_1","object":"invoice_payment","status":"paid", + "payment":{"type":"payment_intent","payment_intent":"pi_9"}}],"has_more":false,"url":"/v1/invoice_payments"} + """); + + Assert.IsTrue(await Deliver("invoice.paid", InvoiceJson("subscription_create"))); + + //a refund goes to the payment intent; the subscription's invoice is read with the order store's key + Assert.AreEqual("pi_9", transaction.AuthorizationTransactionId); + var list = _handler.Requests.Single().Request; + StringAssert.Contains(list.RequestUri!.Query, "invoice=in_2"); + Assert.AreEqual("Bearer sk_s2", list.Headers.Authorization!.ToString()); + _mediator.Verify(x => x.Send(It.Is(c => + c.PaymentTransaction == transaction && c.Amount == 19.99 && c.Reference == "pi_9" && + c.CreatedBy == StripeCheckoutDefaults.ProviderSystemName), It.IsAny()), Times.Once); + _mediator.Verify(x => x.Send(It.Is(c => c.CycleReference == "in_2"), + It.IsAny()), Times.Once); + } + + [TestMethod] + public async Task WebHook_InvoicePaidForTheSubscriptionStartAgain_RecordsTheCycleWithoutPayingTwice() + { + SetupInitialPayment(canMarkPaid: false); + + Assert.IsTrue(await Deliver("invoice.paid", InvoiceJson("subscription_create"))); + + _mediator.Verify(x => x.Send(It.IsAny(), It.IsAny()), Times.Never); + Assert.AreEqual(0, _handler.Requests.Count); + _mediator.Verify(x => x.Send(It.IsAny(), It.IsAny()), + Times.Once); + } + + [TestMethod] + public async Task WebHook_InvoicePaidCommandFails_Throws_SoStripeSendsItAgain() + { + _mediator.Setup(x => x.Send(It.IsAny(), It.IsAny())) + .ThrowsAsync(new InvalidOperationException("database down")); + + await Assert.ThrowsExactlyAsync(() => + Deliver("invoice.paid", InvoiceJson("subscription_cycle"))); + } + + [TestMethod] + [DataRow("subscription_update")] + [DataRow("manual")] + public async Task WebHook_InvoiceNotACycle_RecordsNothing(string billingReason) + { + await Deliver("invoice.paid", InvoiceJson(billingReason)); + await Deliver("invoice.payment_failed", InvoiceJson(billingReason)); + + _mediator.VerifyNoOtherCalls(); + } + + [TestMethod] + public async Task WebHook_InvoiceOfASubscriptionTheShopDidNotStart_RecordsNothing() + { + await Deliver("invoice.paid", InvoiceJson("subscription_cycle", "{}")); + + _mediator.VerifyNoOtherCalls(); + } + + [TestMethod] + public async Task WebHook_InvoicePaymentFailed_RecordsTheFailure() + { + Assert.IsTrue(await Deliver("invoice.payment_failed", InvoiceJson("subscription_cycle"))); + + _mediator.Verify(x => x.Send(It.Is(c => + c.RecurringPaymentId == "rp1" && c.ProviderReference == "sub_1" && c.CycleReference == "in_2" && + c.Reason == "Stripe could not charge invoice INV-2 (attempt 2)"), It.IsAny()), + Times.Once); + } + + [TestMethod] + public async Task WebHook_SubscriptionDeleted_RecordsTheEndWithTheSubscription() + { + Assert.IsTrue(await Deliver("customer.subscription.deleted", + $$$"""{"id":"sub_1","object":"subscription","status":"canceled","metadata":{{{SubscriptionMetadata}}}}""")); + + _mediator.Verify(x => x.Send(It.Is(c => + c.RecurringPaymentId == "rp1" && c.ProviderReference == "sub_1"), It.IsAny()), + Times.Once); + } + + [TestMethod] + public async Task WebHook_SubscriptionCheckoutCompleted_RecordsTheSubscriptionAtOnce() + { + Assert.IsTrue(await Deliver("checkout.session.completed", + $$$"""{"id":"cs_1","object":"checkout.session","mode":"subscription","subscription":"sub_1","metadata":{{{SubscriptionMetadata}}}}""")); + + _mediator.Verify(x => x.Send(It.Is(c => + c.RecurringPaymentId == "rp1" && c.ProviderReference == "sub_1"), It.IsAny()), + Times.Once); + } + + [TestMethod] + public async Task WebHook_OneOffCheckoutCompleted_RecordsNothing() + { + await Deliver("checkout.session.completed", + """{"id":"cs_1","object":"checkout.session","mode":"payment","metadata":{}}"""); + + _mediator.VerifyNoOtherCalls(); + } + + [TestMethod] + public async Task WebHook_PaymentIntentOfASubscription_IsLeftToTheInvoice() + { + await Deliver("payment_intent.succeeded", + """{"id":"pi_9","object":"payment_intent","amount":1999,"currency":"usd","metadata":{}}"""); + + _paymentTransactionService.VerifyNoOtherCalls(); + _mediator.VerifyNoOtherCalls(); + } + + [TestMethod] + public async Task WebHook_BadSignature_IsRefused() + { + Assert.IsFalse(await _service.WebHookProcessPayment("t=1,v1=00", """{"id":"evt_1","object":"event"}""")); + + _mediator.VerifyNoOtherCalls(); + } + private class TestStripeCheckoutService( FakeStripeHandler handler, IContextAccessor contextAccessor, @@ -235,9 +582,10 @@ private class TestStripeCheckoutService( Microsoft.Extensions.Logging.ILogger logger, IMediator mediator, IPaymentTransactionService paymentTransactionService, + IRecurringPaymentService recurringPaymentService, ISettingService settingService) : StripeCheckoutService(contextAccessor, settings, logger, mediator, paymentTransactionService, - settingService) + recurringPaymentService, settingService) { protected override IStripeClient CreateStripeClient(string apiKey) {