Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@
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.Utilities.Checkout;
using Grand.Domain.Orders;
using Grand.Mediator;
using Microsoft.Extensions.Logging;
Expand All @@ -25,7 +26,16 @@ public async Task<bool> 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)
{
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
Expand Down
Original file line number Diff line number Diff line change
@@ -1,16 +1,27 @@
using Grand.Business.Core.Commands.Checkout.Orders;
using Grand.Business.Core.Interfaces.Checkout.Orders;
using Grand.Business.Core.Utilities.Checkout;
using Grand.Mediator;
using Microsoft.Extensions.Logging;

namespace Grand.Business.Checkout.Commands.Handlers.Orders;

public class RecordRecurringPaymentEndedCommandHandler(IRecurringPaymentService recurringPaymentService)
public class RecordRecurringPaymentEndedCommandHandler(
IRecurringPaymentService recurringPaymentService,
ILogger<RecordRecurringPaymentEndedCommandHandler> logger)
: IRequestHandler<RecordRecurringPaymentEndedCommand, bool>
{
public async Task<bool> Handle(RecordRecurringPaymentEndedCommand request, CancellationToken cancellationToken)
{
ArgumentException.ThrowIfNullOrEmpty(request.RecurringPaymentId);

return await recurringPaymentService.RecordEnded(request.RecurringPaymentId);
var report = await recurringPaymentService.RecordEnded(request.RecurringPaymentId, 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 report.Outcome == RecurringReportOutcome.Recorded;
}
}
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
using Grand.Business.Core.Commands.Checkout.Orders;
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;

Expand All @@ -19,21 +19,25 @@ public async Task<bool> Handle(RecordRecurringPaymentFailureCommand request, Can
ArgumentException.ThrowIfNullOrEmpty(request.RecurringPaymentId);
ArgumentException.ThrowIfNullOrEmpty(request.CycleReference);

if (await recurringPaymentService.RecordFailure(request.RecurringPaymentId, 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?.Status is RecurringPaymentStatus.Cancelled or RecurringPaymentStatus.Completed &&
recurringPayment.Cycles.All(x => x.ProviderReference != request.CycleReference))
switch (report.Outcome)
{
if (string.IsNullOrEmpty(recurringPayment.ProviderReference))
recurringPayment.ProviderReference = request.ProviderReference;
await RecurringPaymentGateway.Stop(paymentService, orderService, logger, recurringPayment);
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;
}

return false;
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
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.Mediator;
using Microsoft.Extensions.Logging;

namespace Grand.Business.Checkout.Commands.Handlers.Orders;

public class RecordRecurringPaymentReferenceCommandHandler(
IRecurringPaymentService recurringPaymentService,
IPaymentService paymentService,
IOrderService orderService,
ILogger<RecordRecurringPaymentReferenceCommandHandler> logger)
: IRequestHandler<RecordRecurringPaymentReferenceCommand, bool>
{
public async Task<bool> Handle(RecordRecurringPaymentReferenceCommand request, CancellationToken cancellationToken)
{
ArgumentException.ThrowIfNullOrEmpty(request.RecurringPaymentId);
ArgumentException.ThrowIfNullOrEmpty(request.ProviderReference);

var report = await recurringPaymentService.RecordProviderReference(request.RecurringPaymentId,
request.ProviderReference);

switch (report.Outcome)
{
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;
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -6,38 +6,79 @@
namespace Grand.Business.Checkout.Commands.Handlers.Orders;

/// <summary>
/// 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
/// </summary>
internal static class RecurringPaymentGateway
{
public static async Task Stop(IPaymentService paymentService, IOrderService orderService, ILogger logger,
RecurringPayment recurringPayment)
{
IEnumerable<string> errors;
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())
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)}");
}

/// <summary>
/// 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
/// </summary>
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 {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<IList<string>> AskToStop(IPaymentService paymentService, ILogger logger,
RecurringPayment recurringPayment)
{
try
{
var result = await paymentService.CancelRecurringPayment(recurringPayment);
errors = result.Success ? [] : result.Errors;
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",
recurringPayment.Id);
errors = [e.Message];
logger.LogError(e, "Recurring payment {RecurringPaymentId}: the payment gateway could not be asked to stop charging {ProviderReference}",
recurringPayment.Id, recurringPayment.ProviderReference);
return [e.Message];
}

// the status stays as it is: every cycle is paid or the payment ended, only the gateway schedule may still run
if (errors.Any())
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 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
Expand Down
Loading
Loading