From 354662a44a410fa5a77e480bf563cff6d4a701a2 Mon Sep 17 00:00:00 2001 From: support Date: Sun, 22 Nov 2026 07:32:26 +0100 Subject: [PATCH 1/3] Recurring payments: record the gateway reference at checkout and ignore reports on another one A provider can now record the gateway's reference of a recurring payment as soon as it learns it (RecordRecurringPaymentReferenceCommand), under the recurring payment's lock. A cancel made before the first paid cycle then stops the gateway at once; a payment cancelled before the reference was known is stopped when the reference arrives. The cycle, failure and ended reports are checked against the recorded reference: a report on another subscription (for example a second one started for the same order) records nothing and leaves a note on the initial order. RecordRecurringPaymentEndedCommand gains ProviderReference. --- ...cordRecurringPaymentCycleCommandHandler.cs | 8 + ...cordRecurringPaymentEndedCommandHandler.cs | 17 +- ...rdRecurringPaymentFailureCommandHandler.cs | 12 +- ...RecurringPaymentReferenceCommandHandler.cs | 40 +++++ .../Orders/RecurringPaymentGateway.cs | 9 + .../Orders/RecurringPaymentService.cs | 39 ++++- .../RecordRecurringPaymentEndedCommand.cs | 6 + .../RecordRecurringPaymentReferenceCommand.cs | 21 +++ .../Extensions/RecurringPaymentExtensions.cs | 10 ++ .../Orders/IRecurringPaymentService.cs | 22 ++- ...ordRecurringPaymentCommandHandlersTests.cs | 154 +++++++++++++++++- .../Orders/RecurringPaymentServiceTests.cs | 134 +++++++++++++-- 12 files changed, 433 insertions(+), 39 deletions(-) create mode 100644 src/Business/Grand.Business.Checkout/Commands/Handlers/Orders/RecordRecurringPaymentReferenceCommandHandler.cs create mode 100644 src/Business/Grand.Business.Core/Commands/Checkout/Orders/RecordRecurringPaymentReferenceCommand.cs diff --git a/src/Business/Grand.Business.Checkout/Commands/Handlers/Orders/RecordRecurringPaymentCycleCommandHandler.cs b/src/Business/Grand.Business.Checkout/Commands/Handlers/Orders/RecordRecurringPaymentCycleCommandHandler.cs index 052f75f5d..ba55bdf80 100644 --- a/src/Business/Grand.Business.Checkout/Commands/Handlers/Orders/RecordRecurringPaymentCycleCommandHandler.cs +++ b/src/Business/Grand.Business.Checkout/Commands/Handlers/Orders/RecordRecurringPaymentCycleCommandHandler.cs @@ -1,5 +1,6 @@ using System.Runtime.ExceptionServices; 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.Domain.Orders; @@ -26,7 +27,14 @@ public async Task Handle(RecordRecurringPaymentCycleCommand request, Cance var claim = await recurringPaymentService.ClaimCycle(request.RecurringPaymentId, request.ProviderReference, request.CycleReference, request.Amount, request.PaidOnUtc, request.NextPaymentDateUtc); if (claim == null) + { + // a resend is the usual reason; a report on another subscription is the one staff must hear about + var recurringPayment = await recurringPaymentService.GetRecurringPaymentById(request.RecurringPaymentId); + if (recurringPayment != null && recurringPayment.HasOtherProviderReference(request.ProviderReference)) + await RecurringPaymentGateway.NoteOtherReference(orderService, logger, recurringPayment, + request.ProviderReference); return false; + } // the cycle is recorded: an aborted webhook request must not leave it half done, so nothing below is cancellable cancellationToken = CancellationToken.None; diff --git a/src/Business/Grand.Business.Checkout/Commands/Handlers/Orders/RecordRecurringPaymentEndedCommandHandler.cs b/src/Business/Grand.Business.Checkout/Commands/Handlers/Orders/RecordRecurringPaymentEndedCommandHandler.cs index 14247abe5..8552aeab8 100644 --- a/src/Business/Grand.Business.Checkout/Commands/Handlers/Orders/RecordRecurringPaymentEndedCommandHandler.cs +++ b/src/Business/Grand.Business.Checkout/Commands/Handlers/Orders/RecordRecurringPaymentEndedCommandHandler.cs @@ -1,16 +1,29 @@ using Grand.Business.Core.Commands.Checkout.Orders; +using Grand.Business.Core.Extensions; using Grand.Business.Core.Interfaces.Checkout.Orders; using Grand.Mediator; +using Microsoft.Extensions.Logging; namespace Grand.Business.Checkout.Commands.Handlers.Orders; -public class RecordRecurringPaymentEndedCommandHandler(IRecurringPaymentService recurringPaymentService) +public class RecordRecurringPaymentEndedCommandHandler( + IRecurringPaymentService recurringPaymentService, + IOrderService orderService, + ILogger logger) : IRequestHandler { public async Task Handle(RecordRecurringPaymentEndedCommand request, CancellationToken cancellationToken) { ArgumentException.ThrowIfNullOrEmpty(request.RecurringPaymentId); - return await recurringPaymentService.RecordEnded(request.RecurringPaymentId); + if (await recurringPaymentService.RecordEnded(request.RecurringPaymentId, request.ProviderReference)) + return true; + + var recurringPayment = await recurringPaymentService.GetRecurringPaymentById(request.RecurringPaymentId); + if (recurringPayment != null && recurringPayment.HasOtherProviderReference(request.ProviderReference)) + await RecurringPaymentGateway.NoteOtherReference(orderService, logger, recurringPayment, + request.ProviderReference); + + return false; } } diff --git a/src/Business/Grand.Business.Checkout/Commands/Handlers/Orders/RecordRecurringPaymentFailureCommandHandler.cs b/src/Business/Grand.Business.Checkout/Commands/Handlers/Orders/RecordRecurringPaymentFailureCommandHandler.cs index 2eb78908d..1c440a76a 100644 --- a/src/Business/Grand.Business.Checkout/Commands/Handlers/Orders/RecordRecurringPaymentFailureCommandHandler.cs +++ b/src/Business/Grand.Business.Checkout/Commands/Handlers/Orders/RecordRecurringPaymentFailureCommandHandler.cs @@ -1,4 +1,5 @@ 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.Domain.Orders; @@ -19,13 +20,20 @@ public async Task Handle(RecordRecurringPaymentFailureCommand request, Can ArgumentException.ThrowIfNullOrEmpty(request.RecurringPaymentId); ArgumentException.ThrowIfNullOrEmpty(request.CycleReference); - if (await recurringPaymentService.RecordFailure(request.RecurringPaymentId, request.CycleReference, - request.Reason)) + if (await recurringPaymentService.RecordFailure(request.RecurringPaymentId, request.ProviderReference, + request.CycleReference, request.Reason)) return true; // a failed charge on a payment the shop ended means the gateway still tries to charge, typically a payment // cancelled while pending, before the gateway's reference was known var recurringPayment = await recurringPaymentService.GetRecurringPaymentById(request.RecurringPaymentId); + if (recurringPayment != null && recurringPayment.HasOtherProviderReference(request.ProviderReference)) + { + await RecurringPaymentGateway.NoteOtherReference(orderService, logger, recurringPayment, + request.ProviderReference); + return false; + } + if (recurringPayment?.Status is RecurringPaymentStatus.Cancelled or RecurringPaymentStatus.Completed && recurringPayment.Cycles.All(x => x.ProviderReference != request.CycleReference)) { diff --git a/src/Business/Grand.Business.Checkout/Commands/Handlers/Orders/RecordRecurringPaymentReferenceCommandHandler.cs b/src/Business/Grand.Business.Checkout/Commands/Handlers/Orders/RecordRecurringPaymentReferenceCommandHandler.cs new file mode 100644 index 000000000..5be63bb56 --- /dev/null +++ b/src/Business/Grand.Business.Checkout/Commands/Handlers/Orders/RecordRecurringPaymentReferenceCommandHandler.cs @@ -0,0 +1,40 @@ +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.Mediator; +using Microsoft.Extensions.Logging; + +namespace Grand.Business.Checkout.Commands.Handlers.Orders; + +public class RecordRecurringPaymentReferenceCommandHandler( + IRecurringPaymentService recurringPaymentService, + IPaymentService paymentService, + IOrderService orderService, + ILogger logger) + : IRequestHandler +{ + public async Task Handle(RecordRecurringPaymentReferenceCommand request, CancellationToken cancellationToken) + { + ArgumentException.ThrowIfNullOrEmpty(request.RecurringPaymentId); + ArgumentException.ThrowIfNullOrEmpty(request.ProviderReference); + + var recurringPayment = await recurringPaymentService.RecordProviderReference(request.RecurringPaymentId, + request.ProviderReference); + if (recurringPayment == null) + return false; + + if (recurringPayment.HasOtherProviderReference(request.ProviderReference)) + { + await RecurringPaymentGateway.NoteOtherReference(orderService, logger, recurringPayment, + request.ProviderReference); + return false; + } + + // cancelled before the reference was known, so the cancel could not stop the gateway: it is stopped now + if (recurringPayment.Status.HasEnded()) + await RecurringPaymentGateway.Stop(paymentService, orderService, logger, recurringPayment); + + return true; + } +} diff --git a/src/Business/Grand.Business.Checkout/Commands/Handlers/Orders/RecurringPaymentGateway.cs b/src/Business/Grand.Business.Checkout/Commands/Handlers/Orders/RecurringPaymentGateway.cs index 35e462790..f28215a63 100644 --- a/src/Business/Grand.Business.Checkout/Commands/Handlers/Orders/RecurringPaymentGateway.cs +++ b/src/Business/Grand.Business.Checkout/Commands/Handlers/Orders/RecurringPaymentGateway.cs @@ -33,6 +33,15 @@ await AddNote(orderService, logger, recurringPayment, $"The recurring payment is {recurringPayment.Status.ToString().ToLowerInvariant()}, but the payment gateway did not confirm it stopped charging: {string.Join(", ", errors)}"); } + public static Task NoteOtherReference(IOrderService orderService, ILogger logger, + RecurringPayment recurringPayment, string providerReference) + { + logger.LogWarning("Recurring payment {RecurringPaymentId} runs on {ProviderReference}, but the payment gateway reported on {ReportedReference}", + recurringPayment.Id, recurringPayment.ProviderReference, providerReference); + return AddNote(orderService, logger, recurringPayment, + $"The payment gateway reported on {providerReference}, but the recurring payment runs on {recurringPayment.ProviderReference}, so nothing was recorded: check the payment gateway for a second subscription charging the customer"); + } + public static async Task AddNote(IOrderService orderService, ILogger logger, RecurringPayment recurringPayment, string note) { diff --git a/src/Business/Grand.Business.Checkout/Services/Orders/RecurringPaymentService.cs b/src/Business/Grand.Business.Checkout/Services/Orders/RecurringPaymentService.cs index 0496ecdf0..29ec1ee16 100644 --- a/src/Business/Grand.Business.Checkout/Services/Orders/RecurringPaymentService.cs +++ b/src/Business/Grand.Business.Checkout/Services/Orders/RecurringPaymentService.cs @@ -1,4 +1,5 @@ using Grand.Business.Core.Events.Checkout.Orders; +using Grand.Business.Core.Extensions; using Grand.Business.Core.Interfaces.Catalog.Products; using Grand.Business.Core.Interfaces.Checkout.Orders; using Grand.Business.Core.Utilities.Checkout; @@ -40,7 +41,8 @@ public virtual async Task ClaimCycle(string recurringPaymen await using (await resourceLock.Acquire([LockKey(recurringPaymentId)])) { recurringPayment = await repository.GetByIdAsync(recurringPaymentId); - if (recurringPayment == null || recurringPayment.Cycles.Any(x => x.ProviderReference == cycleReference)) + if (recurringPayment == null || recurringPayment.Cycles.Any(x => x.ProviderReference == cycleReference) || + recurringPayment.HasOtherProviderReference(providerReference)) return null; recurringPayment.CyclesPaid++; @@ -80,7 +82,8 @@ recurringPayment.Status is not (RecurringPaymentStatus.Cancelled or RecurringPay return new RecurringCycleClaim { RecurringPayment = recurringPayment, Cycle = cycle, Completed = completed }; } - public virtual async Task RecordFailure(string recurringPaymentId, string cycleReference, string reason) + public virtual async Task RecordFailure(string recurringPaymentId, string providerReference, + string cycleReference, string reason) { ArgumentException.ThrowIfNullOrEmpty(cycleReference); @@ -93,7 +96,8 @@ public virtual async Task RecordFailure(string recurringPaymentId, string //a failure that arrives after the cycle was paid is a late, out of order event if (recurringPayment == null || recurringPayment.Status is RecurringPaymentStatus.Cancelled or RecurringPaymentStatus.Completed || - recurringPayment.Cycles.Any(x => x.ProviderReference == cycleReference)) + recurringPayment.Cycles.Any(x => x.ProviderReference == cycleReference) || + recurringPayment.HasOtherProviderReference(providerReference)) return false; recurringPayment.LastError = reason; @@ -113,15 +117,17 @@ recurringPayment.Status is RecurringPaymentStatus.Cancelled or RecurringPaymentS return enteredPastDue; } - public virtual async Task RecordEnded(string recurringPaymentId) + public virtual async Task RecordEnded(string recurringPaymentId, string providerReference) { RecurringPayment recurringPayment; await using (await resourceLock.Acquire([LockKey(recurringPaymentId)])) { recurringPayment = await repository.GetByIdAsync(recurringPaymentId); + //another subscription ending says nothing about the one this payment runs on if (recurringPayment == null || - recurringPayment.Status is RecurringPaymentStatus.Cancelled or RecurringPaymentStatus.Completed) + recurringPayment.Status is RecurringPaymentStatus.Cancelled or RecurringPaymentStatus.Completed || + recurringPayment.HasOtherProviderReference(providerReference)) return false; recurringPayment.Status = RecurringPaymentStatus.Cancelled; @@ -138,6 +144,29 @@ public virtual async Task RecordEnded(string recurringPaymentId) return true; } + public virtual async Task RecordProviderReference(string recurringPaymentId, + string providerReference) + { + ArgumentException.ThrowIfNullOrEmpty(providerReference); + + RecurringPayment recurringPayment; + + await using (await resourceLock.Acquire([LockKey(recurringPaymentId)])) + { + recurringPayment = await repository.GetByIdAsync(recurringPaymentId); + if (recurringPayment == null || !string.IsNullOrEmpty(recurringPayment.ProviderReference)) + return recurringPayment; + + recurringPayment.ProviderReference = providerReference; + await repository.UpdateAsync(recurringPayment); + } + + //event notification + await mediator.EntityUpdated(recurringPayment); + + return recurringPayment; + } + public virtual async Task Cancel(string recurringPaymentId, string cancelledBy, Func> stopAtGateway) { diff --git a/src/Business/Grand.Business.Core/Commands/Checkout/Orders/RecordRecurringPaymentEndedCommand.cs b/src/Business/Grand.Business.Core/Commands/Checkout/Orders/RecordRecurringPaymentEndedCommand.cs index 453261855..32c207c15 100644 --- a/src/Business/Grand.Business.Core/Commands/Checkout/Orders/RecordRecurringPaymentEndedCommand.cs +++ b/src/Business/Grand.Business.Core/Commands/Checkout/Orders/RecordRecurringPaymentEndedCommand.cs @@ -9,4 +9,10 @@ namespace Grand.Business.Core.Commands.Checkout.Orders; public class RecordRecurringPaymentEndedCommand : IRequest { public string RecurringPaymentId { get; set; } + + /// + /// The provider's reference of what ended (for example the subscription id), so the end of another + /// subscription started for the same order does not cancel the one the recurring payment runs on + /// + public string ProviderReference { get; set; } } diff --git a/src/Business/Grand.Business.Core/Commands/Checkout/Orders/RecordRecurringPaymentReferenceCommand.cs b/src/Business/Grand.Business.Core/Commands/Checkout/Orders/RecordRecurringPaymentReferenceCommand.cs new file mode 100644 index 000000000..dfcdfe083 --- /dev/null +++ b/src/Business/Grand.Business.Core/Commands/Checkout/Orders/RecordRecurringPaymentReferenceCommand.cs @@ -0,0 +1,21 @@ +using Grand.Mediator; + +namespace Grand.Business.Core.Commands.Checkout.Orders; + +/// +/// A payment provider reports the gateway's reference of a recurring payment as soon as it learns it, typically when +/// the customer completes the checkout and before the first cycle is reported, so a cancel stops the gateway at +/// once. The result is true when the recurring payment runs on this reference +/// +public class RecordRecurringPaymentReferenceCommand : IRequest +{ + /// + /// The recurring payment the provider was given as gateway metadata + /// + public string RecurringPaymentId { get; set; } + + /// + /// The provider's reference of the recurring payment (for example the subscription id) + /// + public string ProviderReference { get; set; } +} diff --git a/src/Business/Grand.Business.Core/Extensions/RecurringPaymentExtensions.cs b/src/Business/Grand.Business.Core/Extensions/RecurringPaymentExtensions.cs index a4bb5e2bd..526878712 100644 --- a/src/Business/Grand.Business.Core/Extensions/RecurringPaymentExtensions.cs +++ b/src/Business/Grand.Business.Core/Extensions/RecurringPaymentExtensions.cs @@ -12,4 +12,14 @@ public static bool HasEnded(this RecurringPaymentStatus status) { return status is RecurringPaymentStatus.Cancelled or RecurringPaymentStatus.Completed; } + + /// + /// Whether a gateway report names another reference than the one the recurring payment runs on, for example a + /// second subscription started for the same order. False while either reference is unknown + /// + public static bool HasOtherProviderReference(this RecurringPayment recurringPayment, string providerReference) + { + return !string.IsNullOrEmpty(recurringPayment.ProviderReference) && !string.IsNullOrEmpty(providerReference) && + recurringPayment.ProviderReference != providerReference; + } } diff --git a/src/Business/Grand.Business.Core/Interfaces/Checkout/Orders/IRecurringPaymentService.cs b/src/Business/Grand.Business.Core/Interfaces/Checkout/Orders/IRecurringPaymentService.cs index 495004fa6..42b85ab34 100644 --- a/src/Business/Grand.Business.Core/Interfaces/Checkout/Orders/IRecurringPaymentService.cs +++ b/src/Business/Grand.Business.Core/Interfaces/Checkout/Orders/IRecurringPaymentService.cs @@ -16,23 +16,33 @@ public interface IRecurringPaymentService /// /// Records a cycle the provider reports as paid, once: under a lock, so a gateway resending the event claims - /// nothing. Returns null when the recurring payment is unknown or the cycle reference was already recorded + /// nothing. Returns null when the recurring payment is unknown, the cycle reference was already recorded or + /// the provider reference is not the one the recurring payment runs on /// Task ClaimCycle(string recurringPaymentId, string providerReference, string cycleReference, double amount, DateTime paidOnUtc, DateTime? nextPaymentDateUtc); /// /// Records a cycle the provider reports as failed, under the same lock. Returns true only when the status moved - /// into PastDue. Nothing is recorded for an unknown recurring payment, one that is Cancelled or Completed, or a - /// cycle that was paid already + /// into PastDue. Nothing is recorded for an unknown recurring payment, one that is Cancelled or Completed, a + /// cycle that was paid already, or another provider reference than the one the recurring payment runs on /// - Task RecordFailure(string recurringPaymentId, string cycleReference, string reason); + Task RecordFailure(string recurringPaymentId, string providerReference, string cycleReference, + string reason); /// /// Cancels a recurring payment the provider reports as ended at the gateway, under the same lock. Returns false - /// for an unknown recurring payment or one that is Cancelled or Completed + /// for an unknown recurring payment, one that is Cancelled or Completed, or another provider reference than + /// the one the recurring payment runs on /// - Task RecordEnded(string recurringPaymentId); + Task RecordEnded(string recurringPaymentId, string providerReference); + + /// + /// Records the gateway's reference as soon as the provider learns it (at checkout), under the same lock, so a + /// cancel made before the first paid cycle stops the gateway. A reference recorded already is kept. Returns the + /// recurring payment as saved, or null when it is unknown + /// + Task RecordProviderReference(string recurringPaymentId, string providerReference); /// /// Cancels a recurring payment, writing it under the same lock on a fresh read. Unless it is Pending without a diff --git a/src/Tests/Grand.Business.Checkout.Tests/Commands/Handlers/Orders/RecordRecurringPaymentCommandHandlersTests.cs b/src/Tests/Grand.Business.Checkout.Tests/Commands/Handlers/Orders/RecordRecurringPaymentCommandHandlersTests.cs index 249285722..7719dfee1 100644 --- a/src/Tests/Grand.Business.Checkout.Tests/Commands/Handlers/Orders/RecordRecurringPaymentCommandHandlersTests.cs +++ b/src/Tests/Grand.Business.Checkout.Tests/Commands/Handlers/Orders/RecordRecurringPaymentCommandHandlersTests.cs @@ -44,12 +44,12 @@ private static RecordRecurringPaymentFailureCommand FailureCommand() [TestMethod] public async Task FailureCommand_PassesTheReportToTheService() { - _service.Setup(x => x.RecordFailure("rp1", "in_2", "declined")).ReturnsAsync(true); + _service.Setup(x => x.RecordFailure("rp1", "sub_1", "in_2", "declined")).ReturnsAsync(true); var result = await FailureHandler().Handle(FailureCommand(), CancellationToken.None); Assert.IsTrue(result); - _service.Verify(x => x.RecordFailure("rp1", "in_2", "declined"), Times.Once); + _service.Verify(x => x.RecordFailure("rp1", "sub_1", "in_2", "declined"), Times.Once); _paymentService.Verify(x => x.CancelRecurringPayment(It.IsAny()), Times.Never); } @@ -117,25 +117,163 @@ await Assert.ThrowsExactlyAsync(() => [TestMethod] public async Task EndedCommand_PassesTheReportToTheService() { - _service.Setup(x => x.RecordEnded("rp1")).ReturnsAsync(true); - var handler = new RecordRecurringPaymentEndedCommandHandler(_service.Object); + _service.Setup(x => x.RecordEnded("rp1", "sub_1")).ReturnsAsync(true); - var result = await handler.Handle(new RecordRecurringPaymentEndedCommand { RecurringPaymentId = "rp1" }, - CancellationToken.None); + var result = await EndedHandler().Handle(new RecordRecurringPaymentEndedCommand { + RecurringPaymentId = "rp1", ProviderReference = "sub_1" + }, CancellationToken.None); Assert.IsTrue(result); - _service.Verify(x => x.RecordEnded("rp1"), Times.Once); + _service.Verify(x => x.RecordEnded("rp1", "sub_1"), Times.Once); } [TestMethod] public async Task EndedCommand_WithoutRecurringPaymentId_Throws() { - var handler = new RecordRecurringPaymentEndedCommandHandler(_service.Object); + var handler = EndedHandler(); await Assert.ThrowsExactlyAsync(() => handler.Handle(new RecordRecurringPaymentEndedCommand { RecurringPaymentId = "" }, CancellationToken.None)); } + private RecordRecurringPaymentEndedCommandHandler EndedHandler() + { + return new RecordRecurringPaymentEndedCommandHandler(_service.Object, _orderService.Object, + new Mock>().Object); + } + + private void SetupOtherReference() + { + _service.Setup(x => x.GetRecurringPaymentById("rp1")).ReturnsAsync(new RecurringPayment { + Id = "rp1", InitialOrderId = "o1", Status = RecurringPaymentStatus.Cancelled, ProviderReference = "sub_9" + }); + } + + private void VerifyOtherReferenceNoted() + { + _orderService.Verify(x => x.InsertOrderNote(It.Is(n => n.OrderId == "o1" && + n.Note.StartsWith("The payment gateway reported on sub_1, but the recurring payment runs on sub_9"))), + Times.Once); + } + + [TestMethod] + public async Task EndedCommand_OtherProviderReference_NotesItOnTheInitialOrder() + { + SetupOtherReference(); + + var result = await EndedHandler().Handle(new RecordRecurringPaymentEndedCommand { + RecurringPaymentId = "rp1", ProviderReference = "sub_1" + }, CancellationToken.None); + + Assert.IsFalse(result); + VerifyOtherReferenceNoted(); + } + + [TestMethod] + public async Task EndedCommand_AlreadyEnded_WritesNoNote() + { + _service.Setup(x => x.GetRecurringPaymentById("rp1")).ReturnsAsync(new RecurringPayment { + Id = "rp1", InitialOrderId = "o1", Status = RecurringPaymentStatus.Cancelled, ProviderReference = "sub_1" + }); + + Assert.IsFalse(await EndedHandler().Handle(new RecordRecurringPaymentEndedCommand { + RecurringPaymentId = "rp1", ProviderReference = "sub_1" + }, CancellationToken.None)); + + _orderService.Verify(x => x.InsertOrderNote(It.IsAny()), Times.Never); + } + + [TestMethod] + public async Task FailureCommand_OtherProviderReference_NotesItAndDoesNotStopTheRecordedOne() + { + SetupOtherReference(); + + Assert.IsFalse(await FailureHandler().Handle(FailureCommand(), CancellationToken.None)); + + VerifyOtherReferenceNoted(); + _paymentService.Verify(x => x.CancelRecurringPayment(It.IsAny()), Times.Never); + } + + [TestMethod] + public async Task CycleCommand_OtherProviderReference_NotesItOnTheInitialOrder() + { + SetupOtherReference(); + + Assert.IsFalse(await CycleHandler().Handle(CycleCommand(), CancellationToken.None)); + + VerifyOtherReferenceNoted(); + _mediator.Verify(x => x.Send(It.IsAny(), It.IsAny()), + Times.Never); + } + + private RecordRecurringPaymentReferenceCommandHandler ReferenceHandler() + { + return new RecordRecurringPaymentReferenceCommandHandler(_service.Object, _paymentService.Object, + _orderService.Object, new Mock>().Object); + } + + private static RecordRecurringPaymentReferenceCommand ReferenceCommand() + { + return new RecordRecurringPaymentReferenceCommand { RecurringPaymentId = "rp1", ProviderReference = "sub_1" }; + } + + [TestMethod] + public async Task ReferenceCommand_Pending_RecordsItWithoutTheGateway() + { + _service.Setup(x => x.RecordProviderReference("rp1", "sub_1")).ReturnsAsync(new RecurringPayment { + Id = "rp1", Status = RecurringPaymentStatus.Pending, ProviderReference = "sub_1" + }); + + Assert.IsTrue(await ReferenceHandler().Handle(ReferenceCommand(), CancellationToken.None)); + + _paymentService.Verify(x => x.CancelRecurringPayment(It.IsAny()), Times.Never); + } + + [TestMethod] + [DataRow(RecurringPaymentStatus.Cancelled)] + [DataRow(RecurringPaymentStatus.Completed)] + public async Task ReferenceCommand_CancelledBeforeTheReferenceWasKnown_StopsTheGateway( + RecurringPaymentStatus status) + { + _service.Setup(x => x.RecordProviderReference("rp1", "sub_1")).ReturnsAsync(new RecurringPayment { + Id = "rp1", InitialOrderId = "o1", Status = status, ProviderReference = "sub_1" + }); + _paymentService.Setup(x => x.CancelRecurringPayment(It.IsAny())) + .ReturnsAsync(new CancelRecurringPaymentResult()); + + Assert.IsTrue(await ReferenceHandler().Handle(ReferenceCommand(), CancellationToken.None)); + + _paymentService.Verify(x => x.CancelRecurringPayment(It.Is(r => + r.ProviderReference == "sub_1")), Times.Once); + } + + [TestMethod] + public async Task ReferenceCommand_OtherReferenceRecorded_NotesItAndStopsNothing() + { + _service.Setup(x => x.RecordProviderReference("rp1", "sub_1")).ReturnsAsync(new RecurringPayment { + Id = "rp1", InitialOrderId = "o1", Status = RecurringPaymentStatus.Cancelled, ProviderReference = "sub_9" + }); + + Assert.IsFalse(await ReferenceHandler().Handle(ReferenceCommand(), CancellationToken.None)); + + VerifyOtherReferenceNoted(); + _paymentService.Verify(x => x.CancelRecurringPayment(It.IsAny()), Times.Never); + } + + [TestMethod] + public async Task ReferenceCommand_UnknownRecurringPayment_ReturnsFalse() + { + Assert.IsFalse(await ReferenceHandler().Handle(ReferenceCommand(), CancellationToken.None)); + } + + [TestMethod] + public async Task ReferenceCommand_WithoutReference_Throws() + { + await Assert.ThrowsExactlyAsync(() => ReferenceHandler().Handle( + new RecordRecurringPaymentReferenceCommand { RecurringPaymentId = "rp1", ProviderReference = "" }, + CancellationToken.None)); + } + private RecordRecurringPaymentCycleCommandHandler CycleHandler() { return new RecordRecurringPaymentCycleCommandHandler(_service.Object, _paymentService.Object, diff --git a/src/Tests/Grand.Business.Checkout.Tests/Services/Orders/RecurringPaymentServiceTests.cs b/src/Tests/Grand.Business.Checkout.Tests/Services/Orders/RecurringPaymentServiceTests.cs index 7993dcf0f..7aa9d3042 100644 --- a/src/Tests/Grand.Business.Checkout.Tests/Services/Orders/RecurringPaymentServiceTests.cs +++ b/src/Tests/Grand.Business.Checkout.Tests/Services/Orders/RecurringPaymentServiceTests.cs @@ -218,7 +218,8 @@ public async Task RecordFailure_WithoutCycleReference_Throws() { var rp = await Insert(RecurringPaymentStatus.Active, 1); - await Assert.ThrowsExactlyAsync(() => _service.RecordFailure(rp.Id, "", "declined")); + await Assert.ThrowsExactlyAsync(() => + _service.RecordFailure(rp.Id, "sub_1", "", "declined")); } [TestMethod] @@ -232,13 +233,13 @@ public async Task RecordFailure_Active_EntersPastDueOnlyOnce() { var rp = await Insert(RecurringPaymentStatus.Active, 1); - Assert.IsTrue(await _service.RecordFailure(rp.Id, "in_2", "declined")); + Assert.IsTrue(await _service.RecordFailure(rp.Id, "sub_1", "in_2", "declined")); var saved = await _service.GetRecurringPaymentById(rp.Id); Assert.AreEqual(RecurringPaymentStatus.PastDue, saved.Status); Assert.AreEqual("declined", saved.LastError); Assert.IsNotNull(saved.LastErrorDateUtc); - Assert.IsFalse(await _service.RecordFailure(rp.Id, "in_2", "expired")); + Assert.IsFalse(await _service.RecordFailure(rp.Id, "sub_1", "in_2", "expired")); saved = await _service.GetRecurringPaymentById(rp.Id); Assert.AreEqual(RecurringPaymentStatus.PastDue, saved.Status); Assert.AreEqual("expired", saved.LastError); @@ -249,7 +250,7 @@ public async Task RecordFailure_ForACyclePaidAlready_IsIgnored() { var rp = await Insert(RecurringPaymentStatus.Active, 2); - Assert.IsFalse(await _service.RecordFailure(rp.Id, "in_2", "late")); + Assert.IsFalse(await _service.RecordFailure(rp.Id, "sub_1", "in_2", "late")); var saved = await _service.GetRecurringPaymentById(rp.Id); Assert.AreEqual(RecurringPaymentStatus.Active, saved.Status); @@ -261,7 +262,7 @@ public async Task RecordFailure_Cancelled_ChangesNothing() { var rp = await Insert(RecurringPaymentStatus.Cancelled, 1); - Assert.IsFalse(await _service.RecordFailure(rp.Id, "in_2", "declined")); + Assert.IsFalse(await _service.RecordFailure(rp.Id, "sub_1", "in_2", "declined")); var saved = await _service.GetRecurringPaymentById(rp.Id); Assert.AreEqual(RecurringPaymentStatus.Cancelled, saved.Status); @@ -271,7 +272,7 @@ public async Task RecordFailure_Cancelled_ChangesNothing() [TestMethod] public async Task RecordFailure_UnknownRecurringPayment_ReturnsFalse() { - Assert.IsFalse(await _service.RecordFailure(UniqueIdentifier.New, "in_2", "declined")); + Assert.IsFalse(await _service.RecordFailure(UniqueIdentifier.New, "sub_1", "in_2", "declined")); } [TestMethod] @@ -281,7 +282,7 @@ public async Task RecordEnded_Active_CancelsByTheProvider() rp.PaymentMethodSystemName = "Payments.Test"; await _repository.UpdateAsync(rp); - Assert.IsTrue(await _service.RecordEnded(rp.Id)); + Assert.IsTrue(await _service.RecordEnded(rp.Id, "sub_1")); var saved = await _service.GetRecurringPaymentById(rp.Id); Assert.AreEqual(RecurringPaymentStatus.Cancelled, saved.Status); @@ -293,19 +294,120 @@ public async Task RecordEnded_Active_CancelsByTheProvider() public async Task RecordEnded_CompletedOrCancelled_ChangesNothing() { var completed = await Insert(RecurringPaymentStatus.Completed, 12); - Assert.IsFalse(await _service.RecordEnded(completed.Id)); + Assert.IsFalse(await _service.RecordEnded(completed.Id, "sub_1")); Assert.AreEqual(RecurringPaymentStatus.Completed, (await _service.GetRecurringPaymentById(completed.Id)).Status); var active = await Insert(RecurringPaymentStatus.Active, 1); - Assert.IsTrue(await _service.RecordEnded(active.Id)); - Assert.IsFalse(await _service.RecordEnded(active.Id)); + Assert.IsTrue(await _service.RecordEnded(active.Id, "sub_1")); + Assert.IsFalse(await _service.RecordEnded(active.Id, "sub_1")); } [TestMethod] public async Task RecordEnded_UnknownRecurringPayment_ReturnsFalse() { - Assert.IsFalse(await _service.RecordEnded(UniqueIdentifier.New)); + Assert.IsFalse(await _service.RecordEnded(UniqueIdentifier.New, "sub_1")); + } + + [TestMethod] + public async Task ClaimCycle_OtherProviderReference_RecordsNothing() + { + // a second subscription started for the same order reports with the same recurring payment id + var rp = await Insert(RecurringPaymentStatus.Active, 1, providerReference: "sub_1"); + + Assert.IsNull(await _service.ClaimCycle(rp.Id, "sub_2", "in_9", 10, DateTime.UtcNow, null)); + + var saved = await _service.GetRecurringPaymentById(rp.Id); + Assert.AreEqual(1, saved.CyclesPaid); + Assert.AreEqual("sub_1", saved.ProviderReference); + } + + [TestMethod] + public async Task ClaimCycle_ProviderReferenceNotGiven_IsNotChecked() + { + var rp = await Insert(RecurringPaymentStatus.Active, 1, providerReference: "sub_1"); + + Assert.IsNotNull(await _service.ClaimCycle(rp.Id, null, "in_2", 10, DateTime.UtcNow, null)); + } + + [TestMethod] + public async Task RecordFailure_OtherProviderReference_ChangesNothing() + { + var rp = await Insert(RecurringPaymentStatus.Active, 1, providerReference: "sub_1"); + + Assert.IsFalse(await _service.RecordFailure(rp.Id, "sub_2", "in_9", "declined")); + + var saved = await _service.GetRecurringPaymentById(rp.Id); + Assert.AreEqual(RecurringPaymentStatus.Active, saved.Status); + Assert.IsNull(saved.LastError); + } + + [TestMethod] + public async Task RecordEnded_OtherProviderReference_KeepsThePaymentRunning() + { + var rp = await Insert(RecurringPaymentStatus.Active, 1, providerReference: "sub_1"); + + Assert.IsFalse(await _service.RecordEnded(rp.Id, "sub_2")); + + Assert.AreEqual(RecurringPaymentStatus.Active, (await _service.GetRecurringPaymentById(rp.Id)).Status); + _mediatorMock.Verify(x => x.Publish(It.IsAny(), It.IsAny()), + Times.Never); + } + + [TestMethod] + public async Task RecordProviderReference_Pending_RecordsItSoACancelAsksTheGateway() + { + var rp = await Insert(RecurringPaymentStatus.Pending, 0); + + var saved = await _service.RecordProviderReference(rp.Id, "sub_1"); + + Assert.AreEqual("sub_1", saved.ProviderReference); + Assert.AreEqual(RecurringPaymentStatus.Pending, saved.Status); + Assert.AreEqual("sub_1", (await _service.GetRecurringPaymentById(rp.Id)).ProviderReference); + + var asked = false; + await _service.Cancel(rp.Id, "customer", _ => + { + asked = true; + return Task.FromResult(new CancelRecurringPaymentResult()); + }); + Assert.IsTrue(asked); + } + + [TestMethod] + public async Task RecordProviderReference_AlreadyRecorded_KeepsIt() + { + var rp = await Insert(RecurringPaymentStatus.Active, 1, providerReference: "sub_1"); + + var saved = await _service.RecordProviderReference(rp.Id, "sub_2"); + + Assert.AreEqual("sub_1", saved.ProviderReference); + Assert.AreEqual("sub_1", (await _service.GetRecurringPaymentById(rp.Id)).ProviderReference); + } + + [TestMethod] + public async Task RecordProviderReference_Cancelled_RecordsItAndKeepsTheStatus() + { + var rp = await Insert(RecurringPaymentStatus.Cancelled, 0); + + var saved = await _service.RecordProviderReference(rp.Id, "sub_1"); + + Assert.AreEqual("sub_1", saved.ProviderReference); + Assert.AreEqual(RecurringPaymentStatus.Cancelled, saved.Status); + } + + [TestMethod] + public async Task RecordProviderReference_UnknownRecurringPayment_ReturnsNull() + { + Assert.IsNull(await _service.RecordProviderReference(UniqueIdentifier.New, "sub_1")); + } + + [TestMethod] + public async Task RecordProviderReference_Empty_Throws() + { + var rp = await Insert(RecurringPaymentStatus.Pending, 0); + + await Assert.ThrowsExactlyAsync(() => _service.RecordProviderReference(rp.Id, "")); } private static CancelRecurringPaymentResult Refusal(string error) @@ -486,7 +588,7 @@ public async Task Cancel_EndedAtTheGatewayDuringTheCall_PublishesOnce() var result = await _service.Cancel(rp.Id, "jane@example.com", async _ => { - endedTask = other.RecordEnded(rp.Id); + endedTask = other.RecordEnded(rp.Id, "sub_1"); await endedTask.WaitAsync(ConcurrentTimeout); return new CancelRecurringPaymentResult(); }); @@ -557,8 +659,8 @@ public async Task RecordEnded_PublishesCancelledOnlyOnTheTransition() { var rp = await Insert(RecurringPaymentStatus.Active, 1); - Assert.IsTrue(await _service.RecordEnded(rp.Id)); - Assert.IsFalse(await _service.RecordEnded(rp.Id)); + Assert.IsTrue(await _service.RecordEnded(rp.Id, "sub_1")); + Assert.IsFalse(await _service.RecordEnded(rp.Id, "sub_1")); var published = Published(); Assert.AreEqual(1, published.Count); @@ -570,8 +672,8 @@ public async Task RecordFailure_PublishesPastDueOnlyWhenEnteringIt() { var rp = await Insert(RecurringPaymentStatus.Active, 1); - await _service.RecordFailure(rp.Id, "in_2", "a"); - await _service.RecordFailure(rp.Id, "in_2", "b"); + await _service.RecordFailure(rp.Id, "sub_1", "in_2", "a"); + await _service.RecordFailure(rp.Id, "sub_1", "in_2", "b"); var published = Published(); Assert.AreEqual(1, published.Count); From 0544a1fd6a72b339fd21a40cb8b85782670c56fe Mon Sep 17 00:00:00 2001 From: support Date: Sun, 22 Nov 2026 07:47:44 +0100 Subject: [PATCH 2/3] Stripe Checkout: pay recurring orders with a Stripe subscription A recurring order opens a Checkout session in subscription mode: one recurring price of the order total, every CycleLength days/weeks/months/years, with the recurring payment and the order named in the session and subscription metadata. The number of cycles stays with the shop, which cancels the subscription when the last one is paid. A recurring payment cancelled before the order was paid leaves a one-off payment. Webhooks: - checkout.session.completed records the subscription id at once (RecordRecurringPaymentReferenceCommand), so a cancel before the first invoice stops it; - invoice.paid records the cycle; the first invoice (subscription_create) also marks the initial order paid, with the invoice's payment intent kept for refunds; - invoice.payment_failed records the failure, customer.subscription.deleted the end; - other invoices of the subscription (updates, one-off dashboard invoices) are not cycles. A failing recurring event throws, so the webhook answers with an error and Stripe resends it. CancelRecurringPayment cancels the subscription with the recurring payment's store key; one Stripe ended already counts as cancelled. Paying again is refused once the subscription started. Every Stripe call shares one client with a 5 s timeout and no retry (Stripe.net waits 80 s). --- .../Views/StripeCheckout/Configure.cshtml | 3 +- .../Views/StripeCheckout/Configure.cshtml | 3 +- .../Services/IStripeCheckoutService.cs | 1 + .../Services/StripeCheckoutService.cs | 260 ++++++++++++- .../StripeCheckoutDefaults.cs | 6 + .../StripeCheckoutPaymentProvider.cs | 34 +- .../StripeCheckoutPaymentProviderTests.cs | 66 +++- .../Payments/StripeCheckoutServiceTests.cs | 358 +++++++++++++++++- 8 files changed, 707 insertions(+), 24 deletions(-) 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) { From c3777cb0e8d1e7a3b0ec4e06464c87165045d31f Mon Sep 17 00:00:00 2001 From: support Date: Sun, 22 Nov 2026 08:20:49 +0100 Subject: [PATCH 3/3] Recurring payments: say why a gateway report was refused, and stop another subscription The recurring payment service now returns the outcome of every gateway report (Recorded, NotFound, Duplicate, OtherReference, Ended) with the payment it read under the lock, so the provider commands no longer read it again to guess why nothing was recorded. - The first reported reference is recorded whichever report brings it: a failure or an end reported before the reference was known now records it, as a paid cycle already did. - The reference command stops the gateway of an ended payment only when it records the reference, so a resent checkout event no longer asks the gateway to cancel again. - A failure on an ended payment records the missing reference under the lock before the gateway is asked to stop, instead of patching it in memory. - A paid cycle, a failure or a reference reported on another subscription asks the provider to stop that subscription and leaves one note per report on the initial order; another subscription that ended is only logged. - RecordRecurringPaymentFailureCommand returns true when the failure was recorded, also while the payment is already past due. --- ...cordRecurringPaymentCycleCommandHandler.cs | 16 +- ...cordRecurringPaymentEndedCommandHandler.cs | 16 +- ...rdRecurringPaymentFailureCommandHandler.cs | 40 ++-- ...RecurringPaymentReferenceCommandHandler.cs | 30 +-- .../Orders/RecurringPaymentGateway.cs | 74 +++++-- .../Orders/RecurringPaymentService.cs | 99 +++++++--- .../RecordRecurringPaymentCycleCommand.cs | 3 +- .../RecordRecurringPaymentFailureCommand.cs | 4 +- .../Orders/IRecurringPaymentService.cs | 32 +-- .../Utilities/Checkout/RecurringCycleClaim.cs | 11 +- .../Checkout/RecurringReportOutcome.cs | 32 +++ .../Checkout/RecurringReportResult.cs | 16 ++ ...ordRecurringPaymentCommandHandlersTests.cs | 185 +++++++++++++----- .../Orders/RecurringPaymentServiceTests.cs | 126 ++++++++---- 14 files changed, 460 insertions(+), 224 deletions(-) create mode 100644 src/Business/Grand.Business.Core/Utilities/Checkout/RecurringReportOutcome.cs create mode 100644 src/Business/Grand.Business.Core/Utilities/Checkout/RecurringReportResult.cs diff --git a/src/Business/Grand.Business.Checkout/Commands/Handlers/Orders/RecordRecurringPaymentCycleCommandHandler.cs b/src/Business/Grand.Business.Checkout/Commands/Handlers/Orders/RecordRecurringPaymentCycleCommandHandler.cs index ba55bdf80..26939f488 100644 --- a/src/Business/Grand.Business.Checkout/Commands/Handlers/Orders/RecordRecurringPaymentCycleCommandHandler.cs +++ b/src/Business/Grand.Business.Checkout/Commands/Handlers/Orders/RecordRecurringPaymentCycleCommandHandler.cs @@ -1,8 +1,8 @@ using System.Runtime.ExceptionServices; 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.Utilities.Checkout; using Grand.Domain.Orders; using Grand.Mediator; using Microsoft.Extensions.Logging; @@ -26,16 +26,18 @@ public async Task Handle(RecordRecurringPaymentCycleCommand request, Cance var claim = await recurringPaymentService.ClaimCycle(request.RecurringPaymentId, request.ProviderReference, request.CycleReference, request.Amount, request.PaidOnUtc, request.NextPaymentDateUtc); - if (claim == null) + if (claim.Outcome == RecurringReportOutcome.OtherReference) { - // a resend is the usual reason; a report on another subscription is the one staff must hear about - var recurringPayment = await recurringPaymentService.GetRecurringPaymentById(request.RecurringPaymentId); - if (recurringPayment != null && recurringPayment.HasOtherProviderReference(request.ProviderReference)) - await RecurringPaymentGateway.NoteOtherReference(orderService, logger, recurringPayment, - request.ProviderReference); + await RecurringPaymentGateway.StopOtherReference(paymentService, orderService, logger, + claim.RecurringPayment, request.ProviderReference, + $"a paid cycle ({request.CycleReference})", "check whether the customer must be refunded"); return false; } + // a resend is the usual reason + if (claim.Outcome != RecurringReportOutcome.Recorded) + return false; + // the cycle is recorded: an aborted webhook request must not leave it half done, so nothing below is cancellable cancellationToken = CancellationToken.None; diff --git a/src/Business/Grand.Business.Checkout/Commands/Handlers/Orders/RecordRecurringPaymentEndedCommandHandler.cs b/src/Business/Grand.Business.Checkout/Commands/Handlers/Orders/RecordRecurringPaymentEndedCommandHandler.cs index 8552aeab8..a3ffb1ccb 100644 --- a/src/Business/Grand.Business.Checkout/Commands/Handlers/Orders/RecordRecurringPaymentEndedCommandHandler.cs +++ b/src/Business/Grand.Business.Checkout/Commands/Handlers/Orders/RecordRecurringPaymentEndedCommandHandler.cs @@ -1,6 +1,6 @@ using Grand.Business.Core.Commands.Checkout.Orders; -using Grand.Business.Core.Extensions; using Grand.Business.Core.Interfaces.Checkout.Orders; +using Grand.Business.Core.Utilities.Checkout; using Grand.Mediator; using Microsoft.Extensions.Logging; @@ -8,7 +8,6 @@ namespace Grand.Business.Checkout.Commands.Handlers.Orders; public class RecordRecurringPaymentEndedCommandHandler( IRecurringPaymentService recurringPaymentService, - IOrderService orderService, ILogger logger) : IRequestHandler { @@ -16,14 +15,13 @@ public async Task Handle(RecordRecurringPaymentEndedCommand request, Cance { ArgumentException.ThrowIfNullOrEmpty(request.RecurringPaymentId); - if (await recurringPaymentService.RecordEnded(request.RecurringPaymentId, request.ProviderReference)) - return true; + var report = await recurringPaymentService.RecordEnded(request.RecurringPaymentId, request.ProviderReference); - var recurringPayment = await recurringPaymentService.GetRecurringPaymentById(request.RecurringPaymentId); - if (recurringPayment != null && recurringPayment.HasOtherProviderReference(request.ProviderReference)) - await RecurringPaymentGateway.NoteOtherReference(orderService, logger, recurringPayment, - request.ProviderReference); + // another subscription that ended charges nothing more, typically one the shop stopped: nothing for staff to do + if (report.Outcome == RecurringReportOutcome.OtherReference) + logger.LogInformation("Recurring payment {RecurringPaymentId} runs on {ProviderReference}; {ReportedReference} ended at the payment gateway", + report.RecurringPayment.Id, report.RecurringPayment.ProviderReference, request.ProviderReference); - return false; + return report.Outcome == RecurringReportOutcome.Recorded; } } diff --git a/src/Business/Grand.Business.Checkout/Commands/Handlers/Orders/RecordRecurringPaymentFailureCommandHandler.cs b/src/Business/Grand.Business.Checkout/Commands/Handlers/Orders/RecordRecurringPaymentFailureCommandHandler.cs index 1c440a76a..a5d567eb2 100644 --- a/src/Business/Grand.Business.Checkout/Commands/Handlers/Orders/RecordRecurringPaymentFailureCommandHandler.cs +++ b/src/Business/Grand.Business.Checkout/Commands/Handlers/Orders/RecordRecurringPaymentFailureCommandHandler.cs @@ -1,8 +1,7 @@ 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.Domain.Orders; +using Grand.Business.Core.Utilities.Checkout; using Grand.Mediator; using Microsoft.Extensions.Logging; @@ -20,28 +19,25 @@ public async Task Handle(RecordRecurringPaymentFailureCommand request, Can ArgumentException.ThrowIfNullOrEmpty(request.RecurringPaymentId); ArgumentException.ThrowIfNullOrEmpty(request.CycleReference); - if (await recurringPaymentService.RecordFailure(request.RecurringPaymentId, request.ProviderReference, - request.CycleReference, request.Reason)) - return true; + var report = await recurringPaymentService.RecordFailure(request.RecurringPaymentId, + request.ProviderReference, request.CycleReference, request.Reason); - // a failed charge on a payment the shop ended means the gateway still tries to charge, typically a payment - // cancelled while pending, before the gateway's reference was known - var recurringPayment = await recurringPaymentService.GetRecurringPaymentById(request.RecurringPaymentId); - if (recurringPayment != null && recurringPayment.HasOtherProviderReference(request.ProviderReference)) + switch (report.Outcome) { - await RecurringPaymentGateway.NoteOtherReference(orderService, logger, recurringPayment, - request.ProviderReference); - return false; + case RecurringReportOutcome.Recorded: + return true; + case RecurringReportOutcome.OtherReference: + await RecurringPaymentGateway.StopOtherReference(paymentService, orderService, logger, + report.RecurringPayment, request.ProviderReference, + $"a failed cycle ({request.CycleReference})"); + return false; + case RecurringReportOutcome.Ended: + // a failed charge on a payment the shop ended means the gateway still tries to charge, typically a + // payment cancelled while pending; the service recorded the reported reference so it can be stopped + await RecurringPaymentGateway.Stop(paymentService, orderService, logger, report.RecurringPayment); + return false; + default: + return false; } - - if (recurringPayment?.Status is RecurringPaymentStatus.Cancelled or RecurringPaymentStatus.Completed && - recurringPayment.Cycles.All(x => x.ProviderReference != request.CycleReference)) - { - if (string.IsNullOrEmpty(recurringPayment.ProviderReference)) - recurringPayment.ProviderReference = request.ProviderReference; - await RecurringPaymentGateway.Stop(paymentService, orderService, logger, recurringPayment); - } - - return false; } } diff --git a/src/Business/Grand.Business.Checkout/Commands/Handlers/Orders/RecordRecurringPaymentReferenceCommandHandler.cs b/src/Business/Grand.Business.Checkout/Commands/Handlers/Orders/RecordRecurringPaymentReferenceCommandHandler.cs index 5be63bb56..d861d1d29 100644 --- a/src/Business/Grand.Business.Checkout/Commands/Handlers/Orders/RecordRecurringPaymentReferenceCommandHandler.cs +++ b/src/Business/Grand.Business.Checkout/Commands/Handlers/Orders/RecordRecurringPaymentReferenceCommandHandler.cs @@ -2,6 +2,7 @@ using Grand.Business.Core.Extensions; using Grand.Business.Core.Interfaces.Checkout.Orders; using Grand.Business.Core.Interfaces.Checkout.Payments; +using Grand.Business.Core.Utilities.Checkout; using Grand.Mediator; using Microsoft.Extensions.Logging; @@ -19,22 +20,25 @@ public async Task Handle(RecordRecurringPaymentReferenceCommand request, C ArgumentException.ThrowIfNullOrEmpty(request.RecurringPaymentId); ArgumentException.ThrowIfNullOrEmpty(request.ProviderReference); - var recurringPayment = await recurringPaymentService.RecordProviderReference(request.RecurringPaymentId, + var report = await recurringPaymentService.RecordProviderReference(request.RecurringPaymentId, request.ProviderReference); - if (recurringPayment == null) - return false; - if (recurringPayment.HasOtherProviderReference(request.ProviderReference)) + switch (report.Outcome) { - await RecurringPaymentGateway.NoteOtherReference(orderService, logger, recurringPayment, - request.ProviderReference); - return false; + case RecurringReportOutcome.Recorded: + // cancelled before the reference was known, so the cancel could not stop the gateway: it is stopped + // now, once, as a resend finds the reference recorded + if (report.RecurringPayment.Status.HasEnded()) + await RecurringPaymentGateway.Stop(paymentService, orderService, logger, report.RecurringPayment); + return true; + case RecurringReportOutcome.Duplicate: + return true; + case RecurringReportOutcome.OtherReference: + await RecurringPaymentGateway.StopOtherReference(paymentService, orderService, logger, + report.RecurringPayment, request.ProviderReference, "a second subscription"); + return false; + default: + return false; } - - // cancelled before the reference was known, so the cancel could not stop the gateway: it is stopped now - if (recurringPayment.Status.HasEnded()) - await RecurringPaymentGateway.Stop(paymentService, orderService, logger, recurringPayment); - - return true; } } diff --git a/src/Business/Grand.Business.Checkout/Commands/Handlers/Orders/RecurringPaymentGateway.cs b/src/Business/Grand.Business.Checkout/Commands/Handlers/Orders/RecurringPaymentGateway.cs index f28215a63..832edcd32 100644 --- a/src/Business/Grand.Business.Checkout/Commands/Handlers/Orders/RecurringPaymentGateway.cs +++ b/src/Business/Grand.Business.Checkout/Commands/Handlers/Orders/RecurringPaymentGateway.cs @@ -6,26 +6,15 @@ namespace Grand.Business.Checkout.Commands.Handlers.Orders; /// -/// What the provider commands do when the gateway reports on a recurring payment the shop already ended +/// What the provider commands do when the gateway reports on a recurring payment the shop already ended, or on +/// another reference than the one it runs on /// internal static class RecurringPaymentGateway { public static async Task Stop(IPaymentService paymentService, IOrderService orderService, ILogger logger, RecurringPayment recurringPayment) { - IEnumerable errors; - try - { - var result = await paymentService.CancelRecurringPayment(recurringPayment); - errors = result.Success ? [] : result.Errors; - } - catch (Exception e) - { - // a throw is treated as a refusal: the report is recorded and a resend is a no-op, so the note is the only trace - logger.LogError(e, "Recurring payment {RecurringPaymentId}: the payment gateway could not be asked to stop charging", - recurringPayment.Id); - errors = [e.Message]; - } + var errors = await AskToStop(paymentService, logger, recurringPayment); // the status stays as it is: every cycle is paid or the payment ended, only the gateway schedule may still run if (errors.Any()) @@ -33,20 +22,63 @@ await AddNote(orderService, logger, recurringPayment, $"The recurring payment is {recurringPayment.Status.ToString().ToLowerInvariant()}, but the payment gateway did not confirm it stopped charging: {string.Join(", ", errors)}"); } - public static Task NoteOtherReference(IOrderService orderService, ILogger logger, - RecurringPayment recurringPayment, string providerReference) + /// + /// Stops another subscription the gateway reported on for the same recurring payment (for example a second + /// checkout of the order): the recurring payment runs on the reference recorded first, so the other one must + /// not charge the customer + /// + public static async Task StopOtherReference(IPaymentService paymentService, IOrderService orderService, + ILogger logger, RecurringPayment recurringPayment, string providerReference, string reported, + string advice = null) { - logger.LogWarning("Recurring payment {RecurringPaymentId} runs on {ProviderReference}, but the payment gateway reported on {ReportedReference}", - recurringPayment.Id, recurringPayment.ProviderReference, providerReference); - return AddNote(orderService, logger, recurringPayment, - $"The payment gateway reported on {providerReference}, but the recurring payment runs on {recurringPayment.ProviderReference}, so nothing was recorded: check the payment gateway for a second subscription charging the customer"); + logger.LogWarning("Recurring payment {RecurringPaymentId} runs on {ProviderReference}, but the payment gateway reported {Reported} on {ReportedReference}", + recurringPayment.Id, recurringPayment.ProviderReference, reported, providerReference); + + // only the reference differs: the store and the payment method decide how the provider stops it + var errors = await AskToStop(paymentService, logger, new RecurringPayment { + Id = recurringPayment.Id, + StoreId = recurringPayment.StoreId, + CustomerId = recurringPayment.CustomerId, + InitialOrderId = recurringPayment.InitialOrderId, + PaymentMethodSystemName = recurringPayment.PaymentMethodSystemName, + Status = recurringPayment.Status, + ProviderReference = providerReference + }); + + var outcome = errors.Any() + ? $"could not be stopped ({string.Join(", ", errors)}): cancel it at the payment gateway" + : "was stopped"; + // a gateway resends its reports, so the same note is written once + await AddNote(orderService, logger, recurringPayment, + $"The payment gateway reported {reported} on {providerReference}, but the recurring payment runs on {recurringPayment.ProviderReference}, so nothing was recorded and {providerReference} {outcome}{(advice == null ? "" : $"; {advice}")}", + once: true); + } + + private static async Task> AskToStop(IPaymentService paymentService, ILogger logger, + RecurringPayment recurringPayment) + { + try + { + var result = await paymentService.CancelRecurringPayment(recurringPayment); + return result.Success ? [] : result.Errors; + } + catch (Exception e) + { + // a throw is treated as a refusal: the report is recorded and a resend is a no-op, so the note is the only trace + logger.LogError(e, "Recurring payment {RecurringPaymentId}: the payment gateway could not be asked to stop charging {ProviderReference}", + recurringPayment.Id, recurringPayment.ProviderReference); + return [e.Message]; + } } public static async Task AddNote(IOrderService orderService, ILogger logger, RecurringPayment recurringPayment, - string note) + string note, bool once = false) { try { + if (once && (await orderService.GetOrderNotes(recurringPayment.InitialOrderId)).Any(x => x.Note == note)) + return; + await orderService.InsertOrderNote(new OrderNote { OrderId = recurringPayment.InitialOrderId, Note = note, DisplayToCustomer = false, CreatedOnUtc = DateTime.UtcNow diff --git a/src/Business/Grand.Business.Checkout/Services/Orders/RecurringPaymentService.cs b/src/Business/Grand.Business.Checkout/Services/Orders/RecurringPaymentService.cs index 29ec1ee16..1b39dcce7 100644 --- a/src/Business/Grand.Business.Checkout/Services/Orders/RecurringPaymentService.cs +++ b/src/Business/Grand.Business.Checkout/Services/Orders/RecurringPaymentService.cs @@ -41,9 +41,11 @@ public virtual async Task ClaimCycle(string recurringPaymen await using (await resourceLock.Acquire([LockKey(recurringPaymentId)])) { recurringPayment = await repository.GetByIdAsync(recurringPaymentId); - if (recurringPayment == null || recurringPayment.Cycles.Any(x => x.ProviderReference == cycleReference) || - recurringPayment.HasOtherProviderReference(providerReference)) - return null; + var refused = Refusal(recurringPayment, providerReference); + if (refused == null && recurringPayment.Cycles.Any(x => x.ProviderReference == cycleReference)) + refused = RecurringReportOutcome.Duplicate; + if (refused.HasValue) + return new RecurringCycleClaim { Outcome = refused.Value, RecurringPayment = recurringPayment }; recurringPayment.CyclesPaid++; cycle = new RecurringPaymentCycle { @@ -56,8 +58,7 @@ public virtual async Task ClaimCycle(string recurringPaymen }; recurringPayment.Cycles.Add(cycle); - if (string.IsNullOrEmpty(recurringPayment.ProviderReference)) - recurringPayment.ProviderReference = providerReference; + KeepFirstReference(recurringPayment, providerReference); if (nextPaymentDateUtc.HasValue) recurringPayment.NextPaymentDateUtc = nextPaymentDateUtc; @@ -67,7 +68,7 @@ public virtual async Task ClaimCycle(string recurringPaymen //the gateway took the money after a cancel, so the cycle is recorded and the status is left alone if (recurringPayment.TotalCycles > 0 && recurringPayment.CyclesPaid == recurringPayment.TotalCycles && - recurringPayment.Status is not (RecurringPaymentStatus.Cancelled or RecurringPaymentStatus.Completed)) + !recurringPayment.Status.HasEnded()) { recurringPayment.Status = RecurringPaymentStatus.Completed; completed = true; @@ -79,11 +80,14 @@ recurringPayment.Status is not (RecurringPaymentStatus.Cancelled or RecurringPay //event notification await mediator.EntityUpdated(recurringPayment); - return new RecurringCycleClaim { RecurringPayment = recurringPayment, Cycle = cycle, Completed = completed }; + return new RecurringCycleClaim { + Outcome = RecurringReportOutcome.Recorded, RecurringPayment = recurringPayment, Cycle = cycle, + Completed = completed + }; } - public virtual async Task RecordFailure(string recurringPaymentId, string providerReference, - string cycleReference, string reason) + public virtual async Task RecordFailure(string recurringPaymentId, + string providerReference, string cycleReference, string reason) { ArgumentException.ThrowIfNullOrEmpty(cycleReference); @@ -93,13 +97,23 @@ public virtual async Task RecordFailure(string recurringPaymentId, string await using (await resourceLock.Acquire([LockKey(recurringPaymentId)])) { recurringPayment = await repository.GetByIdAsync(recurringPaymentId); + var refused = Refusal(recurringPayment, providerReference); //a failure that arrives after the cycle was paid is a late, out of order event - if (recurringPayment == null || - recurringPayment.Status is RecurringPaymentStatus.Cancelled or RecurringPaymentStatus.Completed || - recurringPayment.Cycles.Any(x => x.ProviderReference == cycleReference) || - recurringPayment.HasOtherProviderReference(providerReference)) - return false; + if (refused == null && recurringPayment.Cycles.Any(x => x.ProviderReference == cycleReference)) + refused = RecurringReportOutcome.Duplicate; + if (refused == null && recurringPayment.Status.HasEnded()) + { + //the gateway still tries to charge a payment the shop ended, typically one cancelled while pending: + //its reference is kept so the gateway can be stopped + if (KeepFirstReference(recurringPayment, providerReference)) + await repository.UpdateAsync(recurringPayment); + refused = RecurringReportOutcome.Ended; + } + if (refused.HasValue) + return new RecurringReportResult { Outcome = refused.Value, RecurringPayment = recurringPayment }; + + KeepFirstReference(recurringPayment, providerReference); recurringPayment.LastError = reason; recurringPayment.LastErrorDateUtc = DateTime.UtcNow; @@ -114,10 +128,10 @@ recurringPayment.Status is RecurringPaymentStatus.Cancelled or RecurringPaymentS if (enteredPastDue) await mediator.Publish(new RecurringPaymentPastDueEvent(recurringPayment)); - return enteredPastDue; + return new RecurringReportResult { Outcome = RecurringReportOutcome.Recorded, RecurringPayment = recurringPayment }; } - public virtual async Task RecordEnded(string recurringPaymentId, string providerReference) + public virtual async Task RecordEnded(string recurringPaymentId, string providerReference) { RecurringPayment recurringPayment; @@ -125,11 +139,13 @@ public virtual async Task RecordEnded(string recurringPaymentId, string pr { recurringPayment = await repository.GetByIdAsync(recurringPaymentId); //another subscription ending says nothing about the one this payment runs on - if (recurringPayment == null || - recurringPayment.Status is RecurringPaymentStatus.Cancelled or RecurringPaymentStatus.Completed || - recurringPayment.HasOtherProviderReference(providerReference)) - return false; + var refused = Refusal(recurringPayment, providerReference); + if (refused == null && recurringPayment.Status.HasEnded()) + refused = RecurringReportOutcome.Ended; + if (refused.HasValue) + return new RecurringReportResult { Outcome = refused.Value, RecurringPayment = recurringPayment }; + KeepFirstReference(recurringPayment, providerReference); recurringPayment.Status = RecurringPaymentStatus.Cancelled; recurringPayment.CancelledOnUtc = DateTime.UtcNow; recurringPayment.CancelledBy = recurringPayment.PaymentMethodSystemName; @@ -141,10 +157,10 @@ recurringPayment.Status is RecurringPaymentStatus.Cancelled or RecurringPaymentS await mediator.EntityUpdated(recurringPayment); await mediator.Publish(new RecurringPaymentCancelledEvent(recurringPayment)); - return true; + return new RecurringReportResult { Outcome = RecurringReportOutcome.Recorded, RecurringPayment = recurringPayment }; } - public virtual async Task RecordProviderReference(string recurringPaymentId, + public virtual async Task RecordProviderReference(string recurringPaymentId, string providerReference) { ArgumentException.ThrowIfNullOrEmpty(providerReference); @@ -154,8 +170,11 @@ public virtual async Task RecordProviderReference(string recur await using (await resourceLock.Acquire([LockKey(recurringPaymentId)])) { recurringPayment = await repository.GetByIdAsync(recurringPaymentId); - if (recurringPayment == null || !string.IsNullOrEmpty(recurringPayment.ProviderReference)) - return recurringPayment; + var refused = Refusal(recurringPayment, providerReference); + if (refused == null && recurringPayment.ProviderReference == providerReference) + refused = RecurringReportOutcome.Duplicate; + if (refused.HasValue) + return new RecurringReportResult { Outcome = refused.Value, RecurringPayment = recurringPayment }; recurringPayment.ProviderReference = providerReference; await repository.UpdateAsync(recurringPayment); @@ -164,7 +183,28 @@ public virtual async Task RecordProviderReference(string recur //event notification await mediator.EntityUpdated(recurringPayment); - return recurringPayment; + return new RecurringReportResult { Outcome = RecurringReportOutcome.Recorded, RecurringPayment = recurringPayment }; + } + + //why a report is refused whatever it reports, or null + private static RecurringReportOutcome? Refusal(RecurringPayment recurringPayment, string providerReference) + { + if (recurringPayment == null) + return RecurringReportOutcome.NotFound; + + return recurringPayment.HasOtherProviderReference(providerReference) + ? RecurringReportOutcome.OtherReference + : null; + } + + //the first reference reported is the one the payment runs on, whichever report brings it + private static bool KeepFirstReference(RecurringPayment recurringPayment, string providerReference) + { + if (!string.IsNullOrEmpty(recurringPayment.ProviderReference) || string.IsNullOrEmpty(providerReference)) + return false; + + recurringPayment.ProviderReference = providerReference; + return true; } public virtual async Task Cancel(string recurringPaymentId, string cancelledBy, @@ -186,11 +226,11 @@ public virtual async Task Cancel(string recurringP return notFound; } - if (recurringPayment.Status is RecurringPaymentStatus.Cancelled or RecurringPaymentStatus.Completed) + if (recurringPayment.Status.HasEnded()) return new CancelRecurringPaymentResult(); - //a pending payment has no reference to stop yet; the gateway may have started the subscription at checkout, - //and the first cycle it reports, recorded on the cancelled payment, stops it + //a pending payment whose reference is not known yet has nothing to stop: the gateway is stopped when the + //provider reports the reference (RecordRecurringPaymentReferenceCommand) or a first cycle on it if (recurringPayment.Status == RecurringPaymentStatus.Pending && string.IsNullOrEmpty(recurringPayment.ProviderReference)) { @@ -209,8 +249,7 @@ public virtual async Task Cancel(string recurringP { recurringPayment = await repository.GetByIdAsync(recurringPaymentId); //a webhook or another cancel ended it meanwhile, which also explains a refusal from the gateway - if (recurringPayment == null || - recurringPayment.Status is RecurringPaymentStatus.Cancelled or RecurringPaymentStatus.Completed) + if (recurringPayment == null || recurringPayment.Status.HasEnded()) return new CancelRecurringPaymentResult(); //never cancelled while the gateway may still charge diff --git a/src/Business/Grand.Business.Core/Commands/Checkout/Orders/RecordRecurringPaymentCycleCommand.cs b/src/Business/Grand.Business.Core/Commands/Checkout/Orders/RecordRecurringPaymentCycleCommand.cs index 39cce12c1..299d0f3bb 100644 --- a/src/Business/Grand.Business.Core/Commands/Checkout/Orders/RecordRecurringPaymentCycleCommand.cs +++ b/src/Business/Grand.Business.Core/Commands/Checkout/Orders/RecordRecurringPaymentCycleCommand.cs @@ -4,7 +4,8 @@ namespace Grand.Business.Core.Commands.Checkout.Orders; /// /// A payment provider reports that a cycle of a recurring payment was paid. The result is true when the cycle was -/// recorded now and false when there was nothing to do (an unknown recurring payment, or a cycle already recorded) +/// recorded now and false when there was nothing to do (an unknown recurring payment, a cycle already recorded, or +/// another subscription than the one the recurring payment runs on, which is asked to stop) /// public class RecordRecurringPaymentCycleCommand : IRequest { diff --git a/src/Business/Grand.Business.Core/Commands/Checkout/Orders/RecordRecurringPaymentFailureCommand.cs b/src/Business/Grand.Business.Core/Commands/Checkout/Orders/RecordRecurringPaymentFailureCommand.cs index 488ceb07b..891b22a72 100644 --- a/src/Business/Grand.Business.Core/Commands/Checkout/Orders/RecordRecurringPaymentFailureCommand.cs +++ b/src/Business/Grand.Business.Core/Commands/Checkout/Orders/RecordRecurringPaymentFailureCommand.cs @@ -3,8 +3,8 @@ namespace Grand.Business.Core.Commands.Checkout.Orders; /// -/// A payment provider reports that a cycle of a recurring payment failed. The result is true when the recurring -/// payment became past due +/// A payment provider reports that a cycle of a recurring payment failed. The result is true when the failure was +/// recorded and the recurring payment is past due /// public class RecordRecurringPaymentFailureCommand : IRequest { diff --git a/src/Business/Grand.Business.Core/Interfaces/Checkout/Orders/IRecurringPaymentService.cs b/src/Business/Grand.Business.Core/Interfaces/Checkout/Orders/IRecurringPaymentService.cs index 42b85ab34..616c8346e 100644 --- a/src/Business/Grand.Business.Core/Interfaces/Checkout/Orders/IRecurringPaymentService.cs +++ b/src/Business/Grand.Business.Core/Interfaces/Checkout/Orders/IRecurringPaymentService.cs @@ -16,33 +16,37 @@ public interface IRecurringPaymentService /// /// Records a cycle the provider reports as paid, once: under a lock, so a gateway resending the event claims - /// nothing. Returns null when the recurring payment is unknown, the cycle reference was already recorded or - /// the provider reference is not the one the recurring payment runs on + /// nothing. The cycle is recorded on a cancelled or completed recurring payment too, as the gateway took the + /// money; otherwise the outcome says why nothing was recorded (unknown, cycle reference recorded already, or + /// another provider reference than the one the recurring payment runs on). The first reported reference is + /// recorded /// Task ClaimCycle(string recurringPaymentId, string providerReference, string cycleReference, double amount, DateTime paidOnUtc, DateTime? nextPaymentDateUtc); /// - /// Records a cycle the provider reports as failed, under the same lock. Returns true only when the status moved - /// into PastDue. Nothing is recorded for an unknown recurring payment, one that is Cancelled or Completed, a - /// cycle that was paid already, or another provider reference than the one the recurring payment runs on + /// Records a cycle the provider reports as failed, under the same lock, moving the recurring payment into + /// PastDue. Nothing is recorded for an unknown recurring payment, a cycle that was paid already, another + /// provider reference than the one the recurring payment runs on, or a payment that is Cancelled or Completed, + /// whose missing reference is still recorded so the gateway can be stopped. The first reported reference is + /// recorded /// - Task RecordFailure(string recurringPaymentId, string providerReference, string cycleReference, - string reason); + Task RecordFailure(string recurringPaymentId, string providerReference, + string cycleReference, string reason); /// - /// Cancels a recurring payment the provider reports as ended at the gateway, under the same lock. Returns false - /// for an unknown recurring payment, one that is Cancelled or Completed, or another provider reference than - /// the one the recurring payment runs on + /// Cancels a recurring payment the provider reports as ended at the gateway, under the same lock. Nothing is + /// recorded for an unknown recurring payment, another provider reference than the one the recurring payment + /// runs on, or one that is Cancelled or Completed. The first reported reference is recorded /// - Task RecordEnded(string recurringPaymentId, string providerReference); + Task RecordEnded(string recurringPaymentId, string providerReference); /// /// Records the gateway's reference as soon as the provider learns it (at checkout), under the same lock, so a - /// cancel made before the first paid cycle stops the gateway. A reference recorded already is kept. Returns the - /// recurring payment as saved, or null when it is unknown + /// cancel made before the first paid cycle stops the gateway. A reference recorded already is kept: the + /// outcome is Duplicate for the same one and OtherReference for another /// - Task RecordProviderReference(string recurringPaymentId, string providerReference); + Task RecordProviderReference(string recurringPaymentId, string providerReference); /// /// Cancels a recurring payment, writing it under the same lock on a fresh read. Unless it is Pending without a diff --git a/src/Business/Grand.Business.Core/Utilities/Checkout/RecurringCycleClaim.cs b/src/Business/Grand.Business.Core/Utilities/Checkout/RecurringCycleClaim.cs index 92908ee58..2f18bda21 100644 --- a/src/Business/Grand.Business.Core/Utilities/Checkout/RecurringCycleClaim.cs +++ b/src/Business/Grand.Business.Core/Utilities/Checkout/RecurringCycleClaim.cs @@ -3,17 +3,12 @@ namespace Grand.Business.Core.Utilities.Checkout; /// -/// A paid cycle recorded on a recurring payment +/// A paid cycle reported on a recurring payment /// -public class RecurringCycleClaim +public class RecurringCycleClaim : RecurringReportResult { /// - /// The recurring payment as saved - /// - public RecurringPayment RecurringPayment { get; init; } - - /// - /// The cycle that was recorded + /// The cycle that was recorded; null unless the outcome is Recorded /// public RecurringPaymentCycle Cycle { get; init; } diff --git a/src/Business/Grand.Business.Core/Utilities/Checkout/RecurringReportOutcome.cs b/src/Business/Grand.Business.Core/Utilities/Checkout/RecurringReportOutcome.cs new file mode 100644 index 000000000..056135527 --- /dev/null +++ b/src/Business/Grand.Business.Core/Utilities/Checkout/RecurringReportOutcome.cs @@ -0,0 +1,32 @@ +namespace Grand.Business.Core.Utilities.Checkout; + +/// +/// What the recurring payment service did with a gateway report +/// +public enum RecurringReportOutcome +{ + /// + /// The report was recorded on the recurring payment + /// + Recorded = 0, + + /// + /// Nothing was recorded: the recurring payment is unknown + /// + NotFound = 10, + + /// + /// Nothing was recorded: the same report was recorded already, typically a resend + /// + Duplicate = 20, + + /// + /// Nothing was recorded: the report names another reference than the one the recurring payment runs on + /// + OtherReference = 30, + + /// + /// Nothing was recorded: the recurring payment is cancelled or completed + /// + Ended = 40 +} diff --git a/src/Business/Grand.Business.Core/Utilities/Checkout/RecurringReportResult.cs b/src/Business/Grand.Business.Core/Utilities/Checkout/RecurringReportResult.cs new file mode 100644 index 000000000..3866ce8a1 --- /dev/null +++ b/src/Business/Grand.Business.Core/Utilities/Checkout/RecurringReportResult.cs @@ -0,0 +1,16 @@ +using Grand.Domain.Orders; + +namespace Grand.Business.Core.Utilities.Checkout; + +/// +/// A gateway report on a recurring payment, as the recurring payment service handled it under the lock +/// +public class RecurringReportResult +{ + public RecurringReportOutcome Outcome { get; init; } + + /// + /// The recurring payment as read under the lock, or as saved; null when it is unknown + /// + public RecurringPayment RecurringPayment { get; init; } +} diff --git a/src/Tests/Grand.Business.Checkout.Tests/Commands/Handlers/Orders/RecordRecurringPaymentCommandHandlersTests.cs b/src/Tests/Grand.Business.Checkout.Tests/Commands/Handlers/Orders/RecordRecurringPaymentCommandHandlersTests.cs index 7719dfee1..b12493881 100644 --- a/src/Tests/Grand.Business.Checkout.Tests/Commands/Handlers/Orders/RecordRecurringPaymentCommandHandlersTests.cs +++ b/src/Tests/Grand.Business.Checkout.Tests/Commands/Handlers/Orders/RecordRecurringPaymentCommandHandlersTests.cs @@ -26,6 +26,12 @@ public void Init() _paymentService = new Mock(); _orderService = new Mock(); _mediator = new Mock(); + _orderService.Setup(x => x.GetOrderNotes(It.IsAny())).ReturnsAsync(new List()); + } + + private static RecurringReportResult Report(RecurringReportOutcome outcome, RecurringPayment recurringPayment = null) + { + return new RecurringReportResult { Outcome = outcome, RecurringPayment = recurringPayment }; } private RecordRecurringPaymentFailureCommandHandler FailureHandler() @@ -44,7 +50,8 @@ private static RecordRecurringPaymentFailureCommand FailureCommand() [TestMethod] public async Task FailureCommand_PassesTheReportToTheService() { - _service.Setup(x => x.RecordFailure("rp1", "sub_1", "in_2", "declined")).ReturnsAsync(true); + _service.Setup(x => x.RecordFailure("rp1", "sub_1", "in_2", "declined")) + .ReturnsAsync(Report(RecurringReportOutcome.Recorded, new RecurringPayment { Id = "rp1" })); var result = await FailureHandler().Handle(FailureCommand(), CancellationToken.None); @@ -56,13 +63,12 @@ public async Task FailureCommand_PassesTheReportToTheService() [TestMethod] [DataRow(RecurringPaymentStatus.Cancelled)] [DataRow(RecurringPaymentStatus.Completed)] - public async Task FailureCommand_OnAnEndedPayment_AsksTheProviderToStopWithTheReportedReference( - RecurringPaymentStatus status) + public async Task FailureCommand_OnAnEndedPayment_AsksTheProviderToStop(RecurringPaymentStatus status) { - // cancelled while pending, so the shop never learnt the gateway's reference - _service.Setup(x => x.GetRecurringPaymentById("rp1")).ReturnsAsync(new RecurringPayment { - Id = "rp1", InitialOrderId = "o1", Status = status - }); + // cancelled while pending: the service recorded the reported reference so the gateway can be stopped + _service.Setup(x => x.RecordFailure("rp1", "sub_1", "in_2", "declined")).ReturnsAsync(Report( + RecurringReportOutcome.Ended, + new RecurringPayment { Id = "rp1", InitialOrderId = "o1", Status = status, ProviderReference = "sub_1" })); _paymentService.Setup(x => x.CancelRecurringPayment(It.IsAny())) .ReturnsAsync(new CancelRecurringPaymentResult()); @@ -75,9 +81,11 @@ public async Task FailureCommand_OnAnEndedPayment_AsksTheProviderToStopWithTheRe [TestMethod] public async Task FailureCommand_OnAnEndedPaymentAndProviderRefuses_NotesItOnTheInitialOrder() { - _service.Setup(x => x.GetRecurringPaymentById("rp1")).ReturnsAsync(new RecurringPayment { - Id = "rp1", InitialOrderId = "o1", Status = RecurringPaymentStatus.Cancelled, ProviderReference = "sub_1" - }); + _service.Setup(x => x.RecordFailure("rp1", "sub_1", "in_2", "declined")).ReturnsAsync(Report( + RecurringReportOutcome.Ended, + new RecurringPayment { + Id = "rp1", InitialOrderId = "o1", Status = RecurringPaymentStatus.Cancelled, ProviderReference = "sub_1" + })); var refusal = new CancelRecurringPaymentResult(); refusal.AddError("no way"); _paymentService.Setup(x => x.CancelRecurringPayment(It.IsAny())).ReturnsAsync(refusal); @@ -90,19 +98,20 @@ public async Task FailureCommand_OnAnEndedPaymentAndProviderRefuses_NotesItOnThe } [TestMethod] - public async Task FailureCommand_ForACyclePaidAlreadyOrAnActivePayment_DoesNotAskTheProviderToStop() + [DataRow(RecurringReportOutcome.Duplicate)] + [DataRow(RecurringReportOutcome.NotFound)] + public async Task FailureCommand_ForACyclePaidAlreadyOrAnUnknownPayment_DoesNotAskTheProviderToStop( + RecurringReportOutcome outcome) { - var cancelled = new RecurringPayment { Id = "rp1", Status = RecurringPaymentStatus.Cancelled }; - cancelled.Cycles.Add(new RecurringPaymentCycle { CycleNumber = 2, ProviderReference = "in_2" }); - _service.Setup(x => x.GetRecurringPaymentById("rp1")).ReturnsAsync(cancelled); - await FailureHandler().Handle(FailureCommand(), CancellationToken.None); + _service.Setup(x => x.RecordFailure("rp1", "sub_1", "in_2", "declined")).ReturnsAsync(Report(outcome, + outcome == RecurringReportOutcome.NotFound + ? null + : new RecurringPayment { Id = "rp1", Status = RecurringPaymentStatus.Cancelled })); - _service.Setup(x => x.GetRecurringPaymentById("rp1")).ReturnsAsync(new RecurringPayment { - Id = "rp1", Status = RecurringPaymentStatus.PastDue - }); - await FailureHandler().Handle(FailureCommand(), CancellationToken.None); + Assert.IsFalse(await FailureHandler().Handle(FailureCommand(), CancellationToken.None)); _paymentService.Verify(x => x.CancelRecurringPayment(It.IsAny()), Times.Never); + _orderService.Verify(x => x.InsertOrderNote(It.IsAny()), Times.Never); } [TestMethod] @@ -117,7 +126,8 @@ await Assert.ThrowsExactlyAsync(() => [TestMethod] public async Task EndedCommand_PassesTheReportToTheService() { - _service.Setup(x => x.RecordEnded("rp1", "sub_1")).ReturnsAsync(true); + _service.Setup(x => x.RecordEnded("rp1", "sub_1")) + .ReturnsAsync(Report(RecurringReportOutcome.Recorded, new RecurringPayment { Id = "rp1" })); var result = await EndedHandler().Handle(new RecordRecurringPaymentEndedCommand { RecurringPaymentId = "rp1", ProviderReference = "sub_1" @@ -138,43 +148,58 @@ await Assert.ThrowsExactlyAsync(() => private RecordRecurringPaymentEndedCommandHandler EndedHandler() { - return new RecordRecurringPaymentEndedCommandHandler(_service.Object, _orderService.Object, + return new RecordRecurringPaymentEndedCommandHandler(_service.Object, new Mock>().Object); } - private void SetupOtherReference() + // the recurring payment runs on sub_9, and a second subscription sub_1 reports on it + private static RecurringPayment RunsOnAnotherReference() { - _service.Setup(x => x.GetRecurringPaymentById("rp1")).ReturnsAsync(new RecurringPayment { - Id = "rp1", InitialOrderId = "o1", Status = RecurringPaymentStatus.Cancelled, ProviderReference = "sub_9" - }); + return new RecurringPayment { + Id = "rp1", InitialOrderId = "o1", StoreId = "s1", PaymentMethodSystemName = "Payments.Test", + Status = RecurringPaymentStatus.Active, ProviderReference = "sub_9" + }; } - private void VerifyOtherReferenceNoted() + private void SetupStop() { - _orderService.Verify(x => x.InsertOrderNote(It.Is(n => n.OrderId == "o1" && - n.Note.StartsWith("The payment gateway reported on sub_1, but the recurring payment runs on sub_9"))), + _paymentService.Setup(x => x.CancelRecurringPayment(It.IsAny())) + .ReturnsAsync(new CancelRecurringPaymentResult()); + } + + private void VerifyOtherReferenceStopped(string note) + { + _paymentService.Verify(x => x.CancelRecurringPayment(It.Is(r => r.Id == "rp1" && + r.ProviderReference == "sub_1" && r.StoreId == "s1" && r.PaymentMethodSystemName == "Payments.Test")), Times.Once); + _paymentService.Verify(x => x.CancelRecurringPayment(It.Is(r => + r.ProviderReference == "sub_9")), Times.Never); + _orderService.Verify(x => x.InsertOrderNote(It.Is(n => n.OrderId == "o1" && + !n.DisplayToCustomer && n.Note == note)), Times.Once); } [TestMethod] - public async Task EndedCommand_OtherProviderReference_NotesItOnTheInitialOrder() + public async Task EndedCommand_OtherProviderReference_WritesNoNote() { - SetupOtherReference(); + // another subscription that ended charges nothing more + _service.Setup(x => x.RecordEnded("rp1", "sub_1")) + .ReturnsAsync(Report(RecurringReportOutcome.OtherReference, RunsOnAnotherReference())); var result = await EndedHandler().Handle(new RecordRecurringPaymentEndedCommand { RecurringPaymentId = "rp1", ProviderReference = "sub_1" }, CancellationToken.None); Assert.IsFalse(result); - VerifyOtherReferenceNoted(); + _orderService.Verify(x => x.InsertOrderNote(It.IsAny()), Times.Never); } [TestMethod] public async Task EndedCommand_AlreadyEnded_WritesNoNote() { - _service.Setup(x => x.GetRecurringPaymentById("rp1")).ReturnsAsync(new RecurringPayment { - Id = "rp1", InitialOrderId = "o1", Status = RecurringPaymentStatus.Cancelled, ProviderReference = "sub_1" - }); + _service.Setup(x => x.RecordEnded("rp1", "sub_1")).ReturnsAsync(Report(RecurringReportOutcome.Ended, + new RecurringPayment { + Id = "rp1", InitialOrderId = "o1", Status = RecurringPaymentStatus.Cancelled, ProviderReference = "sub_1" + })); Assert.IsFalse(await EndedHandler().Handle(new RecordRecurringPaymentEndedCommand { RecurringPaymentId = "rp1", ProviderReference = "sub_1" @@ -184,28 +209,57 @@ public async Task EndedCommand_AlreadyEnded_WritesNoNote() } [TestMethod] - public async Task FailureCommand_OtherProviderReference_NotesItAndDoesNotStopTheRecordedOne() + public async Task FailureCommand_OtherProviderReference_StopsTheOtherOneAndNotesIt() { - SetupOtherReference(); + _service.Setup(x => x.RecordFailure("rp1", "sub_1", "in_2", "declined")) + .ReturnsAsync(Report(RecurringReportOutcome.OtherReference, RunsOnAnotherReference())); + SetupStop(); Assert.IsFalse(await FailureHandler().Handle(FailureCommand(), CancellationToken.None)); - VerifyOtherReferenceNoted(); - _paymentService.Verify(x => x.CancelRecurringPayment(It.IsAny()), Times.Never); + VerifyOtherReferenceStopped( + "The payment gateway reported a failed cycle (in_2) on sub_1, but the recurring payment runs on sub_9, so nothing was recorded and sub_1 was stopped"); } [TestMethod] - public async Task CycleCommand_OtherProviderReference_NotesItOnTheInitialOrder() + public async Task CycleCommand_OtherProviderReference_StopsTheOtherOneAndNotesARefund() { - SetupOtherReference(); + _service.Setup(x => x.ClaimCycle("rp1", "sub_1", "in_2", 10, It.IsAny(), null)) + .ReturnsAsync(new RecurringCycleClaim { + Outcome = RecurringReportOutcome.OtherReference, RecurringPayment = RunsOnAnotherReference() + }); + SetupStop(); Assert.IsFalse(await CycleHandler().Handle(CycleCommand(), CancellationToken.None)); - VerifyOtherReferenceNoted(); + VerifyOtherReferenceStopped( + "The payment gateway reported a paid cycle (in_2) on sub_1, but the recurring payment runs on sub_9, so nothing was recorded and sub_1 was stopped; check whether the customer must be refunded"); _mediator.Verify(x => x.Send(It.IsAny(), It.IsAny()), Times.Never); } + [TestMethod] + public async Task CycleCommand_OtherProviderReferenceAndProviderRefuses_NotesItOnce() + { + _service.Setup(x => x.ClaimCycle("rp1", "sub_1", "in_2", 10, It.IsAny(), null)) + .ReturnsAsync(new RecurringCycleClaim { + Outcome = RecurringReportOutcome.OtherReference, RecurringPayment = RunsOnAnotherReference() + }); + var refusal = new CancelRecurringPaymentResult(); + refusal.AddError("no way"); + _paymentService.Setup(x => x.CancelRecurringPayment(It.IsAny())).ReturnsAsync(refusal); + const string note = + "The payment gateway reported a paid cycle (in_2) on sub_1, but the recurring payment runs on sub_9, so nothing was recorded and sub_1 could not be stopped (no way): cancel it at the payment gateway; check whether the customer must be refunded"; + + await CycleHandler().Handle(CycleCommand(), CancellationToken.None); + // the gateway resends the report, and the note is already there + _orderService.Setup(x => x.GetOrderNotes("o1")) + .ReturnsAsync(new List { new() { OrderId = "o1", Note = note } }); + await CycleHandler().Handle(CycleCommand(), CancellationToken.None); + + _orderService.Verify(x => x.InsertOrderNote(It.Is(n => n.Note == note)), Times.Once); + } + private RecordRecurringPaymentReferenceCommandHandler ReferenceHandler() { return new RecordRecurringPaymentReferenceCommandHandler(_service.Object, _paymentService.Object, @@ -220,9 +274,9 @@ private static RecordRecurringPaymentReferenceCommand ReferenceCommand() [TestMethod] public async Task ReferenceCommand_Pending_RecordsItWithoutTheGateway() { - _service.Setup(x => x.RecordProviderReference("rp1", "sub_1")).ReturnsAsync(new RecurringPayment { - Id = "rp1", Status = RecurringPaymentStatus.Pending, ProviderReference = "sub_1" - }); + _service.Setup(x => x.RecordProviderReference("rp1", "sub_1")).ReturnsAsync(Report( + RecurringReportOutcome.Recorded, + new RecurringPayment { Id = "rp1", Status = RecurringPaymentStatus.Pending, ProviderReference = "sub_1" })); Assert.IsTrue(await ReferenceHandler().Handle(ReferenceCommand(), CancellationToken.None)); @@ -235,9 +289,9 @@ public async Task ReferenceCommand_Pending_RecordsItWithoutTheGateway() public async Task ReferenceCommand_CancelledBeforeTheReferenceWasKnown_StopsTheGateway( RecurringPaymentStatus status) { - _service.Setup(x => x.RecordProviderReference("rp1", "sub_1")).ReturnsAsync(new RecurringPayment { - Id = "rp1", InitialOrderId = "o1", Status = status, ProviderReference = "sub_1" - }); + _service.Setup(x => x.RecordProviderReference("rp1", "sub_1")).ReturnsAsync(Report( + RecurringReportOutcome.Recorded, + new RecurringPayment { Id = "rp1", InitialOrderId = "o1", Status = status, ProviderReference = "sub_1" })); _paymentService.Setup(x => x.CancelRecurringPayment(It.IsAny())) .ReturnsAsync(new CancelRecurringPaymentResult()); @@ -248,21 +302,41 @@ public async Task ReferenceCommand_CancelledBeforeTheReferenceWasKnown_StopsTheG } [TestMethod] - public async Task ReferenceCommand_OtherReferenceRecorded_NotesItAndStopsNothing() + [DataRow(RecurringPaymentStatus.Cancelled)] + [DataRow(RecurringPaymentStatus.Completed)] + public async Task ReferenceCommand_ResentOnAnEndedPayment_DoesNotAskTheProviderToStopAgain( + RecurringPaymentStatus status) + { + // the gateway was stopped when the reference was recorded, or by the cancel that came after it + _service.Setup(x => x.RecordProviderReference("rp1", "sub_1")).ReturnsAsync(Report( + RecurringReportOutcome.Duplicate, + new RecurringPayment { Id = "rp1", InitialOrderId = "o1", Status = status, ProviderReference = "sub_1" })); + + Assert.IsTrue(await ReferenceHandler().Handle(ReferenceCommand(), CancellationToken.None)); + + _paymentService.Verify(x => x.CancelRecurringPayment(It.IsAny()), Times.Never); + _orderService.Verify(x => x.InsertOrderNote(It.IsAny()), Times.Never); + } + + [TestMethod] + public async Task ReferenceCommand_OtherReferenceRecorded_StopsTheOtherOneAndNotesIt() { - _service.Setup(x => x.RecordProviderReference("rp1", "sub_1")).ReturnsAsync(new RecurringPayment { - Id = "rp1", InitialOrderId = "o1", Status = RecurringPaymentStatus.Cancelled, ProviderReference = "sub_9" - }); + _service.Setup(x => x.RecordProviderReference("rp1", "sub_1")) + .ReturnsAsync(Report(RecurringReportOutcome.OtherReference, RunsOnAnotherReference())); + SetupStop(); Assert.IsFalse(await ReferenceHandler().Handle(ReferenceCommand(), CancellationToken.None)); - VerifyOtherReferenceNoted(); - _paymentService.Verify(x => x.CancelRecurringPayment(It.IsAny()), Times.Never); + VerifyOtherReferenceStopped( + "The payment gateway reported a second subscription on sub_1, but the recurring payment runs on sub_9, so nothing was recorded and sub_1 was stopped"); } [TestMethod] public async Task ReferenceCommand_UnknownRecurringPayment_ReturnsFalse() { + _service.Setup(x => x.RecordProviderReference("rp1", "sub_1")) + .ReturnsAsync(Report(RecurringReportOutcome.NotFound)); + Assert.IsFalse(await ReferenceHandler().Handle(ReferenceCommand(), CancellationToken.None)); } @@ -292,6 +366,7 @@ private void SetupClaim(int cycleNumber, RecurringPaymentStatus status = Recurri bool completed = false) { var claim = new RecurringCycleClaim { + Outcome = RecurringReportOutcome.Recorded, RecurringPayment = new RecurringPayment { Id = "rp1", InitialOrderId = "o1", PaymentMethodSystemName = "Payments.Test", Status = status }, @@ -305,7 +380,9 @@ private void SetupClaim(int cycleNumber, RecurringPaymentStatus status = Recurri public async Task CycleCommand_AlreadyRecorded_DoesNothing() { _service.Setup(x => x.ClaimCycle(It.IsAny(), It.IsAny(), It.IsAny(), - It.IsAny(), It.IsAny(), It.IsAny())).ReturnsAsync((RecurringCycleClaim)null); + It.IsAny(), It.IsAny(), It.IsAny())).ReturnsAsync(new RecurringCycleClaim { + Outcome = RecurringReportOutcome.Duplicate, RecurringPayment = new RecurringPayment { Id = "rp1" } + }); var result = await CycleHandler().Handle(CycleCommand(), CancellationToken.None); diff --git a/src/Tests/Grand.Business.Checkout.Tests/Services/Orders/RecurringPaymentServiceTests.cs b/src/Tests/Grand.Business.Checkout.Tests/Services/Orders/RecurringPaymentServiceTests.cs index 7aa9d3042..2cb8293fd 100644 --- a/src/Tests/Grand.Business.Checkout.Tests/Services/Orders/RecurringPaymentServiceTests.cs +++ b/src/Tests/Grand.Business.Checkout.Tests/Services/Orders/RecurringPaymentServiceTests.cs @@ -102,7 +102,7 @@ public async Task ClaimCycle_FirstCycle_IsTheInitialOrderAndActivates() var claim = await _service.ClaimCycle(rp.Id, "sub_1", "in_1", 10, paid, next); - Assert.IsNotNull(claim); + Assert.AreEqual(RecurringReportOutcome.Recorded, claim.Outcome); Assert.AreEqual(1, claim.Cycle.CycleNumber); Assert.AreEqual("o1", claim.Cycle.OrderId); Assert.AreEqual("in_1", claim.Cycle.ProviderReference); @@ -130,12 +130,12 @@ public async Task ClaimCycle_LaterCycle_GetsANewOrderIdAndLeavesPastDue() } [TestMethod] - public async Task ClaimCycle_SameCycleReferenceAgain_ReturnsNull() + public async Task ClaimCycle_SameCycleReferenceAgain_IsADuplicate() { var rp = await Insert(RecurringPaymentStatus.Pending, 0); - Assert.IsNotNull(await _service.ClaimCycle(rp.Id, "sub_1", "in_1", 10, DateTime.UtcNow, null)); - Assert.IsNull(await _service.ClaimCycle(rp.Id, "sub_1", "in_1", 10, DateTime.UtcNow, null)); + Assert.AreEqual(RecurringReportOutcome.Recorded, (await _service.ClaimCycle(rp.Id, "sub_1", "in_1", 10, DateTime.UtcNow, null)).Outcome); + Assert.AreEqual(RecurringReportOutcome.Duplicate, (await _service.ClaimCycle(rp.Id, "sub_1", "in_1", 10, DateTime.UtcNow, null)).Outcome); var saved = await _service.GetRecurringPaymentById(rp.Id); Assert.AreEqual(1, saved.Cycles.Count); @@ -152,7 +152,7 @@ public async Task ClaimCycle_ConcurrentDeliveries_ClaimOnce() _service.ClaimCycle(rp.Id, "sub_1", "in_2", 10, DateTime.UtcNow, null), other.ClaimCycle(rp.Id, "sub_1", "in_2", 10, DateTime.UtcNow, null)); - Assert.AreEqual(1, claims.Count(c => c != null)); + Assert.AreEqual(1, claims.Count(c => c.Outcome == RecurringReportOutcome.Recorded)); var saved = await _service.GetRecurringPaymentById(rp.Id); Assert.AreEqual(1, saved.Cycles.Count(c => c.ProviderReference == "in_2")); } @@ -186,7 +186,7 @@ public async Task ClaimCycle_AfterCancelled_RecordsTheCycleAndKeepsTheStatus() var claim = await _service.ClaimCycle(rp.Id, "sub_1", "in_2", 10, DateTime.UtcNow, null); - Assert.IsNotNull(claim); + Assert.AreEqual(RecurringReportOutcome.Recorded, claim.Outcome); Assert.AreEqual(2, claim.Cycle.CycleNumber); Assert.IsFalse(claim.Completed); Assert.AreEqual(RecurringPaymentStatus.Cancelled, (await _service.GetRecurringPaymentById(rp.Id)).Status); @@ -199,7 +199,7 @@ public async Task ClaimCycle_ReachingTotalCyclesAfterCancelled_KeepsTheStatusAnd var claim = await _service.ClaimCycle(rp.Id, "sub_1", "in_2", 10, DateTime.UtcNow, null); - Assert.IsNotNull(claim); + Assert.AreEqual(RecurringReportOutcome.Recorded, claim.Outcome); Assert.IsFalse(claim.Completed); Assert.AreEqual(RecurringPaymentStatus.Cancelled, (await _service.GetRecurringPaymentById(rp.Id)).Status); } @@ -223,23 +223,23 @@ await Assert.ThrowsExactlyAsync(() => } [TestMethod] - public async Task ClaimCycle_UnknownRecurringPayment_ReturnsNull() + public async Task ClaimCycle_UnknownRecurringPayment_IsNotFound() { - Assert.IsNull(await _service.ClaimCycle(UniqueIdentifier.New, "sub_1", "in_1", 10, DateTime.UtcNow, null)); + Assert.AreEqual(RecurringReportOutcome.NotFound, (await _service.ClaimCycle(UniqueIdentifier.New, "sub_1", "in_1", 10, DateTime.UtcNow, null)).Outcome); } [TestMethod] - public async Task RecordFailure_Active_EntersPastDueOnlyOnce() + public async Task RecordFailure_Active_EntersPastDueAndKeepsTheLastError() { var rp = await Insert(RecurringPaymentStatus.Active, 1); - Assert.IsTrue(await _service.RecordFailure(rp.Id, "sub_1", "in_2", "declined")); + Assert.AreEqual(RecurringReportOutcome.Recorded, (await _service.RecordFailure(rp.Id, "sub_1", "in_2", "declined")).Outcome); var saved = await _service.GetRecurringPaymentById(rp.Id); Assert.AreEqual(RecurringPaymentStatus.PastDue, saved.Status); Assert.AreEqual("declined", saved.LastError); Assert.IsNotNull(saved.LastErrorDateUtc); - Assert.IsFalse(await _service.RecordFailure(rp.Id, "sub_1", "in_2", "expired")); + Assert.AreEqual(RecurringReportOutcome.Recorded, (await _service.RecordFailure(rp.Id, "sub_1", "in_2", "expired")).Outcome); saved = await _service.GetRecurringPaymentById(rp.Id); Assert.AreEqual(RecurringPaymentStatus.PastDue, saved.Status); Assert.AreEqual("expired", saved.LastError); @@ -250,7 +250,7 @@ public async Task RecordFailure_ForACyclePaidAlready_IsIgnored() { var rp = await Insert(RecurringPaymentStatus.Active, 2); - Assert.IsFalse(await _service.RecordFailure(rp.Id, "sub_1", "in_2", "late")); + Assert.AreEqual(RecurringReportOutcome.Duplicate, (await _service.RecordFailure(rp.Id, "sub_1", "in_2", "late")).Outcome); var saved = await _service.GetRecurringPaymentById(rp.Id); Assert.AreEqual(RecurringPaymentStatus.Active, saved.Status); @@ -258,21 +258,25 @@ public async Task RecordFailure_ForACyclePaidAlready_IsIgnored() } [TestMethod] - public async Task RecordFailure_Cancelled_ChangesNothing() + public async Task RecordFailure_Cancelled_RecordsOnlyTheMissingReference() { + // cancelled while pending: the gateway still charges, and its reference is needed to stop it var rp = await Insert(RecurringPaymentStatus.Cancelled, 1); - Assert.IsFalse(await _service.RecordFailure(rp.Id, "sub_1", "in_2", "declined")); + var report = await _service.RecordFailure(rp.Id, "sub_1", "in_2", "declined"); + Assert.AreEqual(RecurringReportOutcome.Ended, report.Outcome); + Assert.AreEqual("sub_1", report.RecurringPayment.ProviderReference); var saved = await _service.GetRecurringPaymentById(rp.Id); Assert.AreEqual(RecurringPaymentStatus.Cancelled, saved.Status); + Assert.AreEqual("sub_1", saved.ProviderReference); Assert.IsNull(saved.LastError); } [TestMethod] - public async Task RecordFailure_UnknownRecurringPayment_ReturnsFalse() + public async Task RecordFailure_UnknownRecurringPayment_IsNotFound() { - Assert.IsFalse(await _service.RecordFailure(UniqueIdentifier.New, "sub_1", "in_2", "declined")); + Assert.AreEqual(RecurringReportOutcome.NotFound, (await _service.RecordFailure(UniqueIdentifier.New, "sub_1", "in_2", "declined")).Outcome); } [TestMethod] @@ -282,10 +286,11 @@ public async Task RecordEnded_Active_CancelsByTheProvider() rp.PaymentMethodSystemName = "Payments.Test"; await _repository.UpdateAsync(rp); - Assert.IsTrue(await _service.RecordEnded(rp.Id, "sub_1")); + Assert.AreEqual(RecurringReportOutcome.Recorded, (await _service.RecordEnded(rp.Id, "sub_1")).Outcome); var saved = await _service.GetRecurringPaymentById(rp.Id); Assert.AreEqual(RecurringPaymentStatus.Cancelled, saved.Status); + Assert.AreEqual("sub_1", saved.ProviderReference); Assert.AreEqual("Payments.Test", saved.CancelledBy); Assert.IsNotNull(saved.CancelledOnUtc); } @@ -294,19 +299,19 @@ public async Task RecordEnded_Active_CancelsByTheProvider() public async Task RecordEnded_CompletedOrCancelled_ChangesNothing() { var completed = await Insert(RecurringPaymentStatus.Completed, 12); - Assert.IsFalse(await _service.RecordEnded(completed.Id, "sub_1")); + Assert.AreEqual(RecurringReportOutcome.Ended, (await _service.RecordEnded(completed.Id, "sub_1")).Outcome); Assert.AreEqual(RecurringPaymentStatus.Completed, (await _service.GetRecurringPaymentById(completed.Id)).Status); var active = await Insert(RecurringPaymentStatus.Active, 1); - Assert.IsTrue(await _service.RecordEnded(active.Id, "sub_1")); - Assert.IsFalse(await _service.RecordEnded(active.Id, "sub_1")); + Assert.AreEqual(RecurringReportOutcome.Recorded, (await _service.RecordEnded(active.Id, "sub_1")).Outcome); + Assert.AreEqual(RecurringReportOutcome.Ended, (await _service.RecordEnded(active.Id, "sub_1")).Outcome); } [TestMethod] - public async Task RecordEnded_UnknownRecurringPayment_ReturnsFalse() + public async Task RecordEnded_UnknownRecurringPayment_IsNotFound() { - Assert.IsFalse(await _service.RecordEnded(UniqueIdentifier.New, "sub_1")); + Assert.AreEqual(RecurringReportOutcome.NotFound, (await _service.RecordEnded(UniqueIdentifier.New, "sub_1")).Outcome); } [TestMethod] @@ -315,7 +320,7 @@ public async Task ClaimCycle_OtherProviderReference_RecordsNothing() // a second subscription started for the same order reports with the same recurring payment id var rp = await Insert(RecurringPaymentStatus.Active, 1, providerReference: "sub_1"); - Assert.IsNull(await _service.ClaimCycle(rp.Id, "sub_2", "in_9", 10, DateTime.UtcNow, null)); + Assert.AreEqual(RecurringReportOutcome.OtherReference, (await _service.ClaimCycle(rp.Id, "sub_2", "in_9", 10, DateTime.UtcNow, null)).Outcome); var saved = await _service.GetRecurringPaymentById(rp.Id); Assert.AreEqual(1, saved.CyclesPaid); @@ -327,7 +332,7 @@ public async Task ClaimCycle_ProviderReferenceNotGiven_IsNotChecked() { var rp = await Insert(RecurringPaymentStatus.Active, 1, providerReference: "sub_1"); - Assert.IsNotNull(await _service.ClaimCycle(rp.Id, null, "in_2", 10, DateTime.UtcNow, null)); + Assert.AreEqual(RecurringReportOutcome.Recorded, (await _service.ClaimCycle(rp.Id, null, "in_2", 10, DateTime.UtcNow, null)).Outcome); } [TestMethod] @@ -335,7 +340,7 @@ public async Task RecordFailure_OtherProviderReference_ChangesNothing() { var rp = await Insert(RecurringPaymentStatus.Active, 1, providerReference: "sub_1"); - Assert.IsFalse(await _service.RecordFailure(rp.Id, "sub_2", "in_9", "declined")); + Assert.AreEqual(RecurringReportOutcome.OtherReference, (await _service.RecordFailure(rp.Id, "sub_2", "in_9", "declined")).Outcome); var saved = await _service.GetRecurringPaymentById(rp.Id); Assert.AreEqual(RecurringPaymentStatus.Active, saved.Status); @@ -347,7 +352,7 @@ public async Task RecordEnded_OtherProviderReference_KeepsThePaymentRunning() { var rp = await Insert(RecurringPaymentStatus.Active, 1, providerReference: "sub_1"); - Assert.IsFalse(await _service.RecordEnded(rp.Id, "sub_2")); + Assert.AreEqual(RecurringReportOutcome.OtherReference, (await _service.RecordEnded(rp.Id, "sub_2")).Outcome); Assert.AreEqual(RecurringPaymentStatus.Active, (await _service.GetRecurringPaymentById(rp.Id)).Status); _mediatorMock.Verify(x => x.Publish(It.IsAny(), It.IsAny()), @@ -359,10 +364,11 @@ public async Task RecordProviderReference_Pending_RecordsItSoACancelAsksTheGatew { var rp = await Insert(RecurringPaymentStatus.Pending, 0); - var saved = await _service.RecordProviderReference(rp.Id, "sub_1"); + var report = await _service.RecordProviderReference(rp.Id, "sub_1"); - Assert.AreEqual("sub_1", saved.ProviderReference); - Assert.AreEqual(RecurringPaymentStatus.Pending, saved.Status); + Assert.AreEqual(RecurringReportOutcome.Recorded, report.Outcome); + Assert.AreEqual("sub_1", report.RecurringPayment.ProviderReference); + Assert.AreEqual(RecurringPaymentStatus.Pending, report.RecurringPayment.Status); Assert.AreEqual("sub_1", (await _service.GetRecurringPaymentById(rp.Id)).ProviderReference); var asked = false; @@ -375,31 +381,65 @@ await _service.Cancel(rp.Id, "customer", _ => } [TestMethod] - public async Task RecordProviderReference_AlreadyRecorded_KeepsIt() + public async Task RecordProviderReference_AnotherOneRecorded_KeepsIt() { var rp = await Insert(RecurringPaymentStatus.Active, 1, providerReference: "sub_1"); - var saved = await _service.RecordProviderReference(rp.Id, "sub_2"); + var report = await _service.RecordProviderReference(rp.Id, "sub_2"); - Assert.AreEqual("sub_1", saved.ProviderReference); + Assert.AreEqual(RecurringReportOutcome.OtherReference, report.Outcome); + Assert.AreEqual("sub_1", report.RecurringPayment.ProviderReference); Assert.AreEqual("sub_1", (await _service.GetRecurringPaymentById(rp.Id)).ProviderReference); } + [TestMethod] + public async Task RecordProviderReference_SameOneAgain_IsADuplicate() + { + var rp = await Insert(RecurringPaymentStatus.Cancelled, 0); + + Assert.AreEqual(RecurringReportOutcome.Recorded, (await _service.RecordProviderReference(rp.Id, "sub_1")).Outcome); + Assert.AreEqual(RecurringReportOutcome.Duplicate, (await _service.RecordProviderReference(rp.Id, "sub_1")).Outcome); + } + + [TestMethod] + public async Task RecordEnded_BeforeTheReferenceIsKnown_RunsOnTheReportedOne() + { + // the first reference reported is the one the payment runs on, whichever report brings it + var rp = await Insert(RecurringPaymentStatus.Pending, 0); + + Assert.AreEqual(RecurringReportOutcome.Recorded, (await _service.RecordEnded(rp.Id, "sub_2")).Outcome); + + Assert.AreEqual("sub_2", (await _service.GetRecurringPaymentById(rp.Id)).ProviderReference); + Assert.AreEqual(RecurringReportOutcome.OtherReference, (await _service.RecordProviderReference(rp.Id, "sub_1")).Outcome); + } + + [TestMethod] + public async Task RecordFailure_BeforeTheReferenceIsKnown_RunsOnTheReportedOne() + { + var rp = await Insert(RecurringPaymentStatus.Pending, 0); + + Assert.AreEqual(RecurringReportOutcome.Recorded, (await _service.RecordFailure(rp.Id, "sub_2", "in_1", "declined")).Outcome); + + Assert.AreEqual("sub_2", (await _service.GetRecurringPaymentById(rp.Id)).ProviderReference); + Assert.AreEqual(RecurringReportOutcome.OtherReference, (await _service.ClaimCycle(rp.Id, "sub_1", "in_1", 10, DateTime.UtcNow, null)).Outcome); + } + [TestMethod] public async Task RecordProviderReference_Cancelled_RecordsItAndKeepsTheStatus() { var rp = await Insert(RecurringPaymentStatus.Cancelled, 0); - var saved = await _service.RecordProviderReference(rp.Id, "sub_1"); + var report = await _service.RecordProviderReference(rp.Id, "sub_1"); - Assert.AreEqual("sub_1", saved.ProviderReference); - Assert.AreEqual(RecurringPaymentStatus.Cancelled, saved.Status); + Assert.AreEqual(RecurringReportOutcome.Recorded, report.Outcome); + Assert.AreEqual("sub_1", report.RecurringPayment.ProviderReference); + Assert.AreEqual(RecurringPaymentStatus.Cancelled, report.RecurringPayment.Status); } [TestMethod] - public async Task RecordProviderReference_UnknownRecurringPayment_ReturnsNull() + public async Task RecordProviderReference_UnknownRecurringPayment_IsNotFound() { - Assert.IsNull(await _service.RecordProviderReference(UniqueIdentifier.New, "sub_1")); + Assert.AreEqual(RecurringReportOutcome.NotFound, (await _service.RecordProviderReference(UniqueIdentifier.New, "sub_1")).Outcome); } [TestMethod] @@ -569,7 +609,7 @@ public async Task Cancel_CycleWebhookDuringTheGatewayCall_IsNotHeldUpAndIsKept() }); Assert.IsTrue(result.Success); - Assert.IsNotNull(await claimTask); + Assert.AreEqual(RecurringReportOutcome.Recorded, (await claimTask).Outcome); var saved = await _service.GetRecurringPaymentById(rp.Id); Assert.AreEqual(RecurringPaymentStatus.Cancelled, saved.Status); Assert.AreEqual(2, saved.Cycles.Count); @@ -584,7 +624,7 @@ public async Task Cancel_EndedAtTheGatewayDuringTheCall_PublishesOnce() rp.PaymentMethodSystemName = "Payments.Test"; await _repository.UpdateAsync(rp); var other = new RecurringPaymentService(_repository, _productService.Object, _mediator, _resourceLock); - Task endedTask = null; + Task endedTask = null; var result = await _service.Cancel(rp.Id, "jane@example.com", async _ => { @@ -594,7 +634,7 @@ public async Task Cancel_EndedAtTheGatewayDuringTheCall_PublishesOnce() }); Assert.IsTrue(result.Success); - Assert.IsTrue(await endedTask); + Assert.AreEqual(RecurringReportOutcome.Recorded, (await endedTask).Outcome); var saved = await _service.GetRecurringPaymentById(rp.Id); Assert.AreEqual(RecurringPaymentStatus.Cancelled, saved.Status); Assert.AreEqual("Payments.Test", saved.CancelledBy); @@ -659,8 +699,8 @@ public async Task RecordEnded_PublishesCancelledOnlyOnTheTransition() { var rp = await Insert(RecurringPaymentStatus.Active, 1); - Assert.IsTrue(await _service.RecordEnded(rp.Id, "sub_1")); - Assert.IsFalse(await _service.RecordEnded(rp.Id, "sub_1")); + Assert.AreEqual(RecurringReportOutcome.Recorded, (await _service.RecordEnded(rp.Id, "sub_1")).Outcome); + Assert.AreEqual(RecurringReportOutcome.Ended, (await _service.RecordEnded(rp.Id, "sub_1")).Outcome); var published = Published(); Assert.AreEqual(1, published.Count);