Skip to content

Commit a1dc85a

Browse files
Recurring payments: cancelling and messages (slice 3 of 5) (#1077)
1 parent 1179b40 commit a1dc85a

38 files changed

Lines changed: 2075 additions & 91 deletions

File tree

‎.ai/skills/message-notification.md‎

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -32,7 +32,7 @@ Do not use this skill as the primary review for MongoDB queries or security; com
3232
6. Use DotLiquid syntax: `{{Drop.Property}}` for values, `{% if condition %}...{% endif %}` for conditions, `{% for item in Collection %}...{% endfor %}` for loops.
3333

3434
#### Sending Messages
35-
7. Add a typed send method to the area interface that owns the recipient's flow, `I<Area>MessageProviderService` in `src/Business/Grand.Business.Core/Interfaces/Messages/` (Customer, Order, Newsletter, Catalog, MerchandiseReturn, Vendor, Cms), when the trigger is a recurring, well-defined business event. Follow the signature pattern:
35+
7. Add a typed send method to the area interface that owns the recipient's flow, `I<Area>MessageProviderService` in `src/Business/Grand.Business.Core/Interfaces/Messages/` (Customer, Order, Newsletter, Catalog, MerchandiseReturn, RecurringPayment, Vendor, Cms), when the trigger is a recurring, well-defined business event. Follow the signature pattern:
3636
```csharp
3737
Task<int> SendXxxMessage(TEntity entity, Store store, string languageId);
3838
```
@@ -94,6 +94,7 @@ Task<int> SendOrderPlacedCustomerMessage(Order order, Customer customer, string
9494
| `INewsletterMessageProviderService` | newsletter subscription activation and deactivation |
9595
| `ICatalogMessageProviderService` | email a friend, wishlist, product questions and reviews, low stock, back in stock, auctions and bids |
9696
| `IMerchandiseReturnMessageProviderService` | merchandise return created, status changed, notes |
97+
| `IRecurringPaymentMessageProviderService` | recurring payment cancelled and cycle failed, for customer and store owner |
9798
| `IVendorMessageProviderService` | vendor application, information change, vendor reviews, contact vendor |
9899
| `ICmsMessageProviderService` | blog, knowledgebase article and news comments |
99100

@@ -167,6 +168,7 @@ public class MessageTokensAddedEvent : INotification {
167168
| `LiquidShipment` | `{{Shipment.*}}` | Shipment |
168169
| `LiquidProduct` | `{{Product.*}}` | Product |
169170
| `LiquidMerchandiseReturn` | `{{MerchandiseReturn.*}}` | MerchandiseReturn |
171+
| `LiquidRecurringPayment` | `{{RecurringPayment.*}}` | RecurringPayment (the initial order comes from `LiquidOrder`) |
170172
| `LiquidGiftVoucher` | `{{GiftVoucher.*}}` | GiftVoucher |
171173
| `LiquidNewsLetterSubscription` | `{{NewsLetterSubscription.*}}` | NewsLetterSubscription |
172174
| `LiquidVendor` | `{{Vendor.*}}` | Vendor |

‎.ai/skills/plugin-payment.md‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -65,6 +65,7 @@ Do not use this skill for order processing business logic outside the payment fl
6565
- 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.
6666
- 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.
6767
- Never report "cancelled" from `CancelRecurringPayment` unless the gateway confirmed it: on an error result the shop keeps the recurring payment running.
68+
- `CancelRecurringPayment` stops the gateway's schedule for `RecurringPayment.ProviderReference` and returns. The shop cancels through `CancelRecurringPaymentCommand`, which calls it outside the recurring payment's lock and then, under the lock on a fresh read, marks it `Cancelled` only on success; a throw counts as a refusal. Webhooks for the payment are not held up by the call, and a cycle recorded meanwhile is kept. A `Pending` payment with no `ProviderReference` is cancelled without the call: it has no reference to stop yet, the gateway may have started the subscription at checkout already, and the first cycle or failure it reports on the cancelled payment makes the shop stop the gateway, so send `ProviderReference` with the failure command as well. A cycle charged after the payment was cancelled or completed is noted on the initial order for staff to refund.
6869
- 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).
6970
- 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.
7071
- `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.
Lines changed: 42 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,42 @@
1+
using Grand.Business.Core.Commands.Checkout.Orders;
2+
using Grand.Business.Core.Interfaces.Checkout.Orders;
3+
using Grand.Business.Core.Interfaces.Checkout.Payments;
4+
using Grand.Business.Core.Utilities.Checkout;
5+
using Grand.Domain.Orders;
6+
using Grand.Mediator;
7+
using Microsoft.Extensions.Logging;
8+
9+
namespace Grand.Business.Checkout.Commands.Handlers.Orders;
10+
11+
public class CancelRecurringPaymentCommandHandler(
12+
IRecurringPaymentService recurringPaymentService,
13+
IPaymentService paymentService,
14+
ILogger<CancelRecurringPaymentCommandHandler> logger)
15+
: IRequestHandler<CancelRecurringPaymentCommand, CancelRecurringPaymentResult>
16+
{
17+
public async Task<CancelRecurringPaymentResult> Handle(CancelRecurringPaymentCommand request,
18+
CancellationToken cancellationToken)
19+
{
20+
ArgumentNullException.ThrowIfNull(request.RecurringPayment);
21+
ArgumentException.ThrowIfNullOrEmpty(request.CancelledBy);
22+
23+
return await recurringPaymentService.Cancel(request.RecurringPayment.Id, request.CancelledBy, StopAtGateway);
24+
}
25+
26+
private async Task<CancelRecurringPaymentResult> StopAtGateway(RecurringPayment recurringPayment)
27+
{
28+
try
29+
{
30+
return await paymentService.CancelRecurringPayment(recurringPayment);
31+
}
32+
catch (Exception e)
33+
{
34+
//a throw is treated as a refusal: the gateway may still be charging, so the status must stay as it is
35+
logger.LogError(e, "Recurring payment {RecurringPaymentId}: the payment gateway could not be asked to stop charging",
36+
recurringPayment.Id);
37+
var result = new CancelRecurringPaymentResult();
38+
result.AddError(e.Message);
39+
return result;
40+
}
41+
}
42+
}

‎src/Business/Grand.Business.Checkout/Commands/Handlers/Orders/RecordRecurringPaymentCycleCommandHandler.cs‎

Lines changed: 8 additions & 41 deletions
Original file line numberDiff line numberDiff line change
@@ -45,7 +45,7 @@ await mediator.Send(new PlaceRecurringCycleOrderCommand {
4545
logger.LogError(e, "Recurring payment {RecurringPaymentId}: the order {OrderId} of cycle {CycleNumber} ({CycleReference}) could not be placed or marked paid",
4646
claim.RecurringPayment.Id, claim.Cycle.OrderId, claim.Cycle.CycleNumber, request.CycleReference);
4747
// the order may exist already (the failure can come after it was inserted), so the note names it
48-
await AddNote(claim.RecurringPayment,
48+
await RecurringPaymentGateway.AddNote(orderService, logger, claim.RecurringPayment,
4949
$"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}");
5050
// the failure must reach the provider so it can log or report it, but only after the gateway was
5151
// asked to stop: the claim is recorded, so a resend is a no-op and would never stop it
@@ -54,49 +54,16 @@ await AddNote(claim.RecurringPayment,
5454

5555
// a cycle claimed while the payment is already completed or cancelled means the gateway still charges
5656
if (claim.RecurringPayment.Status is RecurringPaymentStatus.Completed or RecurringPaymentStatus.Cancelled)
57-
await StopTheGateway(claim.RecurringPayment);
58-
59-
placementFailure?.Throw();
60-
61-
return true;
62-
}
63-
64-
private async Task StopTheGateway(RecurringPayment recurringPayment)
65-
{
66-
IEnumerable<string> errors;
67-
try
68-
{
69-
var result = await paymentService.CancelRecurringPayment(recurringPayment);
70-
errors = result.Success ? [] : result.Errors;
71-
}
72-
catch (Exception e)
7357
{
74-
// 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
75-
logger.LogError(e, "Recurring payment {RecurringPaymentId}: the payment gateway could not be asked to stop charging",
76-
recurringPayment.Id);
77-
errors = [e.Message];
58+
// the last cycle completing the payment is expected; any other was taken after the shop ended it
59+
if (!claim.Completed)
60+
await RecurringPaymentGateway.AddNote(orderService, logger, claim.RecurringPayment,
61+
$"Cycle {claim.Cycle.CycleNumber} was charged at the payment gateway ({request.CycleReference}) after the recurring payment was {claim.RecurringPayment.Status.ToString().ToLowerInvariant()}: check whether the customer must be refunded");
62+
await RecurringPaymentGateway.Stop(paymentService, orderService, logger, claim.RecurringPayment);
7863
}
7964

80-
// the status stays as it is: every cycle is paid or the payment ended, only the gateway schedule may still run
81-
if (errors.Any())
82-
await AddNote(recurringPayment,
83-
$"The recurring payment is {recurringPayment.Status.ToString().ToLowerInvariant()}, but the payment gateway did not confirm it stopped charging: {string.Join(", ", errors)}");
84-
}
65+
placementFailure?.Throw();
8566

86-
private async Task AddNote(RecurringPayment recurringPayment, string note)
87-
{
88-
try
89-
{
90-
await orderService.InsertOrderNote(new OrderNote {
91-
OrderId = recurringPayment.InitialOrderId, Note = note, DisplayToCustomer = false,
92-
CreatedOnUtc = DateTime.UtcNow
93-
});
94-
}
95-
catch (Exception e)
96-
{
97-
// the note is a courtesy to staff; losing it must not hide the original failure or fail a recorded cycle
98-
logger.LogError(e, "Recurring payment {RecurringPaymentId}: the order note could not be written: {Note}",
99-
recurringPayment.Id, note);
100-
}
67+
return true;
10168
}
10269
}
Lines changed: 24 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,18 +1,39 @@
11
using Grand.Business.Core.Commands.Checkout.Orders;
22
using Grand.Business.Core.Interfaces.Checkout.Orders;
3+
using Grand.Business.Core.Interfaces.Checkout.Payments;
4+
using Grand.Domain.Orders;
35
using Grand.Mediator;
6+
using Microsoft.Extensions.Logging;
47

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

7-
public class RecordRecurringPaymentFailureCommandHandler(IRecurringPaymentService recurringPaymentService)
10+
public class RecordRecurringPaymentFailureCommandHandler(
11+
IRecurringPaymentService recurringPaymentService,
12+
IPaymentService paymentService,
13+
IOrderService orderService,
14+
ILogger<RecordRecurringPaymentFailureCommandHandler> logger)
815
: IRequestHandler<RecordRecurringPaymentFailureCommand, bool>
916
{
1017
public async Task<bool> Handle(RecordRecurringPaymentFailureCommand request, CancellationToken cancellationToken)
1118
{
1219
ArgumentException.ThrowIfNullOrEmpty(request.RecurringPaymentId);
1320
ArgumentException.ThrowIfNullOrEmpty(request.CycleReference);
1421

15-
return await recurringPaymentService.RecordFailure(request.RecurringPaymentId, request.CycleReference,
16-
request.Reason);
22+
if (await recurringPaymentService.RecordFailure(request.RecurringPaymentId, request.CycleReference,
23+
request.Reason))
24+
return true;
25+
26+
// a failed charge on a payment the shop ended means the gateway still tries to charge, typically a payment
27+
// cancelled while pending, before the gateway's reference was known
28+
var recurringPayment = await recurringPaymentService.GetRecurringPaymentById(request.RecurringPaymentId);
29+
if (recurringPayment?.Status is RecurringPaymentStatus.Cancelled or RecurringPaymentStatus.Completed &&
30+
recurringPayment.Cycles.All(x => x.ProviderReference != request.CycleReference))
31+
{
32+
if (string.IsNullOrEmpty(recurringPayment.ProviderReference))
33+
recurringPayment.ProviderReference = request.ProviderReference;
34+
await RecurringPaymentGateway.Stop(paymentService, orderService, logger, recurringPayment);
35+
}
36+
37+
return false;
1738
}
1839
}
Lines changed: 53 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,53 @@
1+
using Grand.Business.Core.Interfaces.Checkout.Orders;
2+
using Grand.Business.Core.Interfaces.Checkout.Payments;
3+
using Grand.Domain.Orders;
4+
using Microsoft.Extensions.Logging;
5+
6+
namespace Grand.Business.Checkout.Commands.Handlers.Orders;
7+
8+
/// <summary>
9+
/// What the provider commands do when the gateway reports on a recurring payment the shop already ended
10+
/// </summary>
11+
internal static class RecurringPaymentGateway
12+
{
13+
public static async Task Stop(IPaymentService paymentService, IOrderService orderService, ILogger logger,
14+
RecurringPayment recurringPayment)
15+
{
16+
IEnumerable<string> errors;
17+
try
18+
{
19+
var result = await paymentService.CancelRecurringPayment(recurringPayment);
20+
errors = result.Success ? [] : result.Errors;
21+
}
22+
catch (Exception e)
23+
{
24+
// 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
25+
logger.LogError(e, "Recurring payment {RecurringPaymentId}: the payment gateway could not be asked to stop charging",
26+
recurringPayment.Id);
27+
errors = [e.Message];
28+
}
29+
30+
// the status stays as it is: every cycle is paid or the payment ended, only the gateway schedule may still run
31+
if (errors.Any())
32+
await AddNote(orderService, logger, recurringPayment,
33+
$"The recurring payment is {recurringPayment.Status.ToString().ToLowerInvariant()}, but the payment gateway did not confirm it stopped charging: {string.Join(", ", errors)}");
34+
}
35+
36+
public static async Task AddNote(IOrderService orderService, ILogger logger, RecurringPayment recurringPayment,
37+
string note)
38+
{
39+
try
40+
{
41+
await orderService.InsertOrderNote(new OrderNote {
42+
OrderId = recurringPayment.InitialOrderId, Note = note, DisplayToCustomer = false,
43+
CreatedOnUtc = DateTime.UtcNow
44+
});
45+
}
46+
catch (Exception e)
47+
{
48+
// the note is a courtesy to staff; losing it must not hide the original failure or fail a recorded report
49+
logger.LogError(e, "Recurring payment {RecurringPaymentId}: the order note could not be written: {Note}",
50+
recurringPayment.Id, note);
51+
}
52+
}
53+
}
Lines changed: 85 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,85 @@
1+
using Grand.Business.Core.Commands.Checkout.Orders;
2+
using Grand.Business.Core.Events.Checkout.Orders;
3+
using Grand.Business.Core.Interfaces.Checkout.Orders;
4+
using Grand.Domain.Orders;
5+
using Grand.Mediator;
6+
using Microsoft.Extensions.Logging;
7+
8+
namespace Grand.Business.Checkout.Events.Orders;
9+
10+
/// <summary>
11+
/// Cancels the recurring payment of an initial order that was cancelled or deleted
12+
/// </summary>
13+
public class OrderCancelledRecurringPaymentHandler : INotificationHandler<OrderCancelledEvent>,
14+
INotificationHandler<OrderDeletedEvent>
15+
{
16+
private readonly ILogger<OrderCancelledRecurringPaymentHandler> _logger;
17+
private readonly IMediator _mediator;
18+
private readonly IOrderService _orderService;
19+
private readonly IRecurringPaymentService _recurringPaymentService;
20+
21+
public OrderCancelledRecurringPaymentHandler(IRecurringPaymentService recurringPaymentService,
22+
IOrderService orderService, IMediator mediator, ILogger<OrderCancelledRecurringPaymentHandler> logger)
23+
{
24+
_recurringPaymentService = recurringPaymentService;
25+
_orderService = orderService;
26+
_mediator = mediator;
27+
_logger = logger;
28+
}
29+
30+
public Task Handle(OrderCancelledEvent notification, CancellationToken cancellationToken)
31+
{
32+
return CancelRecurringPayment(notification.Order, "cancelled");
33+
}
34+
35+
public Task Handle(OrderDeletedEvent notification, CancellationToken cancellationToken)
36+
{
37+
return CancelRecurringPayment(notification.Order, "deleted");
38+
}
39+
40+
private async Task CancelRecurringPayment(Order order, string what)
41+
{
42+
// a cycle order or a plain order never owns a recurring payment, and a plain order costs no query
43+
if (order.RecurringCycleNumber != 1) return;
44+
45+
try
46+
{
47+
var recurringPayment = await _recurringPaymentService.GetRecurringPaymentByInitialOrderId(order.Id);
48+
if (recurringPayment == null) return;
49+
50+
var result = await _mediator.Send(new CancelRecurringPaymentCommand {
51+
RecurringPayment = recurringPayment,
52+
CancelledBy = $"Order #{order.OrderNumber} {what}"
53+
});
54+
if (!result.Success)
55+
await AddNote(order, what, string.Join(", ", result.Errors));
56+
}
57+
catch (Exception ex)
58+
{
59+
// the order is already cancelled or deleted: publishing must complete whatever happens here
60+
_logger.LogError(ex,
61+
"Order {OrderNumber} ({OrderId}) was {What} but its recurring payment could not be cancelled",
62+
order.OrderNumber, order.Id, what);
63+
await AddNote(order, what, ex.Message);
64+
}
65+
}
66+
67+
private async Task AddNote(Order order, string what, string reason)
68+
{
69+
try
70+
{
71+
await _orderService.InsertOrderNote(new OrderNote {
72+
OrderId = order.Id,
73+
Note =
74+
$"The order was {what}, but its recurring payment could not be cancelled, so the payment gateway may still charge: {reason}",
75+
DisplayToCustomer = false,
76+
CreatedOnUtc = DateTime.UtcNow
77+
});
78+
}
79+
catch (Exception ex)
80+
{
81+
_logger.LogError(ex, "The note about the recurring payment of order {OrderId} could not be saved",
82+
order.Id);
83+
}
84+
}
85+
}

0 commit comments

Comments
 (0)