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
5 changes: 5 additions & 0 deletions .ai/skills/plugin-payment.md
Original file line number Diff line number Diff line change
Expand Up @@ -65,6 +65,11 @@ Do not use this skill for order processing business logic outside the payment fl
- The provider, not the shop, runs the schedule: the gateway charges every cycle, retries failures and reports each cycle to the shop, the first one (the initial order's payment) included: `CyclesPaid` stays 0 until it does. A cart with a recurring product is offered only methods whose `SupportRecurringPayment()` returns `true`, and the order is refused for any other method.
- Return `SupportRecurringPayment() => true` only when the payment flow starts the gateway's schedule for a recurring order and `CancelRecurringPayment` stops it. Both members have defaults (`false`, and an error result), so a provider without recurring support implements neither.
- Never report "cancelled" from `CancelRecurringPayment` unless the gateway confirmed it: on an error result the shop keeps the recurring payment running.
- A provider reports to the shop with three mediator commands (`Grand.Business.Core.Commands.Checkout.Orders`): `RecordRecurringPaymentCycleCommand` (a cycle was paid; the shop places the cycle order from the second cycle on and, whenever the recurring payment is completed or cancelled after the cycle is recorded, calls `CancelRecurringPayment` to stop the gateway), `RecordRecurringPaymentFailureCommand` and `RecordRecurringPaymentEndedCommand` (the gateway ended it).
- Pass `RecurringPayment.Id` to the gateway as metadata when the schedule starts, and send it back as `RecurringPaymentId` in every command. The webhook must verify the gateway signature before sending any of them.
- `CycleReference` is the gateway's invoice or charge id, so a resent webhook is recorded once and the command returns `false`. `ProviderReference` is the subscription id.
- `Amount` uses the units of `MarkAsPaidCommand.Amount`: the order total in the order's currency, as Stripe Checkout passes it (`paymentIntent.Amount / 100.0`).
- The first paid cycle is the initial order's own payment: the provider still marks that order paid on its existing path and also sends the cycle command, which records cycle 1 and places no order. If placing a later cycle's order throws, the command notes it on the initial order for staff (the order may exist but be unpaid), stops the gateway when the payment is completed, and rethrows so the provider can log or report it. `CycleReference` is required, and `Amount` must not be negative. The cycle is already recorded, so a resend of the same `CycleReference` returns `false` and does not retry the order. A cycle the gateway charged less for is recorded as a partial payment, so its order stays partially paid, and a cycle of 0 records no payment; an order note says so.

#### Project Structure
12. Use `Microsoft.NET.Sdk.Razor` as SDK.
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,136 @@
using System.Globalization;
using Grand.Business.Checkout.Extensions;
using Grand.Business.Core.Commands.Checkout.Orders;
using Grand.Business.Core.Commands.Messages.Common;
using Grand.Business.Core.Events.Checkout.Orders;
using Grand.Business.Core.Interfaces.Catalog.Products;
using Grand.Business.Core.Interfaces.Checkout.GiftVouchers;
using Grand.Business.Core.Interfaces.Checkout.Orders;
using Grand.Business.Core.Interfaces.Checkout.Payments;
using Grand.Business.Core.Interfaces.Customers;
using Grand.Domain.Orders;
using Grand.Domain.Payments;
using Grand.Mediator;
using Grand.SharedKernel;
using Microsoft.Extensions.Logging;

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

public class PlaceRecurringCycleOrderCommandHandler(
IOrderService orderService,
IPaymentTransactionService paymentTransactionService,
IProductService productService,
IInventoryManageService inventoryManageService,
ICustomerService customerService,
IGiftVoucherService giftVoucherService,
IMediator mediator,
ILogger<PlaceRecurringCycleOrderCommandHandler> logger)
: IRequestHandler<PlaceRecurringCycleOrderCommand, Order>
{
public async Task<Order> Handle(PlaceRecurringCycleOrderCommand request, CancellationToken cancellationToken)
{
var recurringPayment = request.RecurringPayment;
var cycle = request.Cycle;

var initialOrder = await orderService.GetOrderById(recurringPayment.InitialOrderId);
if (initialOrder == null || initialOrder.Deleted)
throw new GrandException(
$"The initial order {recurringPayment.InitialOrderId} of recurring payment {recurringPayment.Id} was not found");

// a gift voucher paid part of the first cycle only
var giftVouchersAmount = (await giftVoucherService.GetAllGiftVoucherUsageHistory(initialOrder.Id))
.Sum(x => x.UsedValue);

var code = await mediator.Send(new PrepareOrderCodeCommand(), cancellationToken);
var order = RecurringCycleOrder.Copy(initialOrder, cycle.OrderId, cycle.CycleNumber, code, DateTime.UtcNow,
giftVouchersAmount);

// the gateway already took the money, so the transaction is a real one from the start
var paymentTransaction = new PaymentTransaction {
TransactionStatus = TransactionStatus.Pending,
OrderGuid = order.OrderGuid,
OrderCode = order.Code,
StoreId = order.StoreId,
CustomerId = order.CustomerId,
CustomerEmail = order.CustomerEmail,
PaymentMethodSystemName = order.PaymentMethodSystemName,
CurrencyCode = order.CustomerCurrencyCode,
CurrencyRate = order.CurrencyRate,
TransactionAmount = order.OrderTotal,
Temp = false
};
await paymentTransactionService.InsertPaymentTransaction(paymentTransaction);

await orderService.InsertOrder(order);

// no stock check: the customer has paid, so low stock never blocks a cycle order
foreach (var item in order.OrderItems)
{
var product = await productService.GetProductById(item.ProductId);
if (product == null) continue;

await inventoryManageService.AdjustReserved(product, -item.Quantity, item.Attributes, item.WarehouseId);

// statistics only: the payment is already taken, so a failed write must not stop the order
try
{
await productService.IncrementProductField(product, x => x.Sold, item.Quantity);
}
catch (Exception exc)
{
logger.LogWarning(exc, "Could not update the sold count of product {ProductId}", product.Id);
}
Comment on lines +79 to +82
}

await InsertNote(order.Id,
$"Cycle {cycle.CycleNumber} of the recurring payment of order #{initialOrder.OrderNumber}");

// no request context here: the customer comes from the order, and no host falls back to the store's primary one
var customer = await customerService.GetCustomerById(order.CustomerId);
await mediator.Send(new OrderNotificationCommand { Order = order, Customer = customer, Host = null },
cancellationToken);

await mediator.Send(new CheckOrderStatusCommand { Order = order }, cancellationToken);

await mediator.Publish(new OrderPlacedEvent(order), cancellationToken);

// the order is paid with what the gateway charged: a smaller charge must not show as fully paid
var charged = Math.Round(cycle.Amount, 2);
var total = Math.Round(order.OrderTotal, 2);
if (charged >= total)
await mediator.Send(new MarkAsPaidCommand {
PaymentTransaction = paymentTransaction,
Amount = cycle.Amount,
Reference = cycle.ProviderReference,
CreatedBy = recurringPayment.PaymentMethodSystemName
}, cancellationToken);
else if (charged > 0)
await mediator.Send(new PartiallyPaidOfflineCommand {
PaymentTransaction = paymentTransaction,
AmountToPaid = cycle.Amount,
Reference = cycle.ProviderReference,
CreatedBy = recurringPayment.PaymentMethodSystemName
}, cancellationToken);

// a price change at the gateway shows here
if (charged != total)
await InsertNote(order.Id,
$"The payment gateway charged {Format(charged, order)} for this cycle; the order total is {Format(total, order)}");

return order;
}

private static string Format(double amount, Order order)
{
return $"{amount.ToString("0.00", CultureInfo.InvariantCulture)} {order.CustomerCurrencyCode}";
}

private Task InsertNote(string orderId, string note)
{
return orderService.InsertOrderNote(new OrderNote {
Note = note,
DisplayToCustomer = false,
OrderId = orderId
});
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,102 @@
using System.Runtime.ExceptionServices;
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.Mediator;
using Microsoft.Extensions.Logging;

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

public class RecordRecurringPaymentCycleCommandHandler(
IRecurringPaymentService recurringPaymentService,
IPaymentService paymentService,
IOrderService orderService,
IMediator mediator,
ILogger<RecordRecurringPaymentCycleCommandHandler> logger)
: IRequestHandler<RecordRecurringPaymentCycleCommand, bool>
{
public async Task<bool> Handle(RecordRecurringPaymentCycleCommand request, CancellationToken cancellationToken)
{
ArgumentException.ThrowIfNullOrEmpty(request.RecurringPaymentId);
ArgumentException.ThrowIfNullOrEmpty(request.CycleReference);
if (double.IsNaN(request.Amount) || request.Amount < 0)
throw new ArgumentOutOfRangeException(nameof(request), "The cycle amount must be zero or more");

var claim = await recurringPaymentService.ClaimCycle(request.RecurringPaymentId, request.ProviderReference,
request.CycleReference, request.Amount, request.PaidOnUtc, request.NextPaymentDateUtc);
if (claim == null)
return false;

// the cycle is recorded: an aborted webhook request must not leave it half done, so nothing below is cancellable
cancellationToken = CancellationToken.None;

// the first cycle is the initial order's own payment, which the provider marks paid on its existing path
ExceptionDispatchInfo placementFailure = null;
if (claim.Cycle.CycleNumber > 1)
try
{
await mediator.Send(new PlaceRecurringCycleOrderCommand {
RecurringPayment = claim.RecurringPayment, Cycle = claim.Cycle
}, cancellationToken);
}
catch (Exception e)
{
logger.LogError(e, "Recurring payment {RecurringPaymentId}: the order {OrderId} of cycle {CycleNumber} ({CycleReference}) could not be placed or marked paid",
claim.RecurringPayment.Id, claim.Cycle.OrderId, claim.Cycle.CycleNumber, request.CycleReference);
// the order may exist already (the failure can come after it was inserted), so the note names it
await AddNote(claim.RecurringPayment,
$"Cycle {claim.Cycle.CycleNumber} was paid at the payment gateway ({request.CycleReference}), but its order {claim.Cycle.OrderId} could not be placed or marked paid: {e.Message}");
// the failure must reach the provider so it can log or report it, but only after the gateway was
// asked to stop: the claim is recorded, so a resend is a no-op and would never stop it
placementFailure = ExceptionDispatchInfo.Capture(e);
}
Comment on lines +43 to +53

// a cycle claimed while the payment is already completed or cancelled means the gateway still charges
if (claim.RecurringPayment.Status is RecurringPaymentStatus.Completed or RecurringPaymentStatus.Cancelled)
await StopTheGateway(claim.RecurringPayment);

placementFailure?.Throw();

return true;
}

private async Task StopTheGateway(RecurringPayment recurringPayment)
{
IEnumerable<string> errors;
try
{
var result = await paymentService.CancelRecurringPayment(recurringPayment);
errors = result.Success ? [] : result.Errors;
}
catch (Exception e)
{
// a throw is treated as a refusal: the claim 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];
}
Comment on lines +72 to +78

// 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(recurringPayment,
$"The recurring payment is {recurringPayment.Status.ToString().ToLowerInvariant()}, but the payment gateway did not confirm it stopped charging: {string.Join(", ", errors)}");
}

private async Task AddNote(RecurringPayment recurringPayment, string note)
{
try
{
await orderService.InsertOrderNote(new OrderNote {
OrderId = recurringPayment.InitialOrderId, Note = note, DisplayToCustomer = false,
CreatedOnUtc = DateTime.UtcNow
});
}
catch (Exception e)
{
// the note is a courtesy to staff; losing it must not hide the original failure or fail a recorded cycle
logger.LogError(e, "Recurring payment {RecurringPaymentId}: the order note could not be written: {Note}",
recurringPayment.Id, note);
}
Comment on lines +95 to +100
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
using Grand.Business.Core.Commands.Checkout.Orders;
using Grand.Business.Core.Interfaces.Checkout.Orders;
using Grand.Mediator;

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

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

return await recurringPaymentService.RecordEnded(request.RecurringPaymentId);
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
using Grand.Business.Core.Commands.Checkout.Orders;
using Grand.Business.Core.Interfaces.Checkout.Orders;
using Grand.Mediator;

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

public class RecordRecurringPaymentFailureCommandHandler(IRecurringPaymentService recurringPaymentService)
: IRequestHandler<RecordRecurringPaymentFailureCommand, bool>
{
public async Task<bool> Handle(RecordRecurringPaymentFailureCommand request, CancellationToken cancellationToken)
{
ArgumentException.ThrowIfNullOrEmpty(request.RecurringPaymentId);
ArgumentException.ThrowIfNullOrEmpty(request.CycleReference);

return await recurringPaymentService.RecordFailure(request.RecurringPaymentId, request.CycleReference,
request.Reason);
}
}
Loading
Loading