From c1e52ea9086a48a9527f7b3992020567ebdc13e4 Mon Sep 17 00:00:00 2001 From: Khwezi Mngoma Date: Sat, 13 Jun 2026 16:26:47 +0200 Subject: [PATCH] Simplified PayfastPaymentConfirmationReceivedEventHandler --- .../LiteCharms.Features.MidrandBooks.csproj | 6 +- ...PaymentConfirmationReceivedEventHandler.cs | 110 ++++-------------- 2 files changed, 28 insertions(+), 88 deletions(-) diff --git a/LiteCharms.Features.MidrandBooks/LiteCharms.Features.MidrandBooks.csproj b/LiteCharms.Features.MidrandBooks/LiteCharms.Features.MidrandBooks.csproj index 564430a..022093b 100644 --- a/LiteCharms.Features.MidrandBooks/LiteCharms.Features.MidrandBooks.csproj +++ b/LiteCharms.Features.MidrandBooks/LiteCharms.Features.MidrandBooks.csproj @@ -32,7 +32,7 @@ - + all runtime; build; native; contentfiles; analyzers; buildtransitive @@ -136,8 +136,8 @@ - - + + diff --git a/LiteCharms.Features.MidrandBooks/Payments/Events/Handlers/PayfastPaymentConfirmationReceivedEventHandler.cs b/LiteCharms.Features.MidrandBooks/Payments/Events/Handlers/PayfastPaymentConfirmationReceivedEventHandler.cs index 8211b4e..aeb7974 100644 --- a/LiteCharms.Features.MidrandBooks/Payments/Events/Handlers/PayfastPaymentConfirmationReceivedEventHandler.cs +++ b/LiteCharms.Features.MidrandBooks/Payments/Events/Handlers/PayfastPaymentConfirmationReceivedEventHandler.cs @@ -1,17 +1,13 @@ -using LiteCharms.Features.Api.Configuration; -using LiteCharms.Features.Hasher; +using LiteCharms.Features.Hasher; using LiteCharms.Features.Mediator; using LiteCharms.Features.MidrandBooks.Orders; using LiteCharms.Features.MidrandBooks.Payments.Models; namespace LiteCharms.Features.MidrandBooks.Payments.Events.Handlers; -public sealed class PayfastPaymentConfirmationReceivedEventHandler(IServiceProvider services, - IOptions payfastOptions, ILogger logger) : +public sealed class PayfastPaymentConfirmationReceivedEventHandler(IServiceProvider services, ILogger logger) : INotificationHandler { - private readonly PayfastSettings pasfastSettings = payfastOptions.Value; - public async ValueTask Handle(PayfastPaymentConfirmationReceivedEvent notification, CancellationToken cancellationToken) { using var activity = MediatorTelemetry.Source.StartActivity($"Quartz: {typeof(PayfastPaymentConfirmationReceivedEvent).Name}"); @@ -23,83 +19,34 @@ public sealed class PayfastPaymentConfirmationReceivedEventHandler(IServiceProvi var paymentService = scope.ServiceProvider.GetRequiredService(); var payfastService = scope.ServiceProvider.GetRequiredService(); - var payload = notification.Payload ?? throw new Exception("Payload metadata context context is null."); + var payload = notification.Payload ?? throw new Exception("Payload metadata context is null."); - var dict = payload.ToParamDictionary(); - var localSignature = PayfastService.GenerateSignature(dict, pasfastSettings.Passphrase); + var hashResult = hashService.DecodeLongIdHash(payload.MerchantPaymentId!); + if (hashResult.IsFailed) throw new Exception("Failed to decode application tracking hash key identifier."); - if (localSignature.IsFailed) - throw new Exception("Failed to generate local signature for incoming webhook payload."); + var orderResult = await orderService.GetOrderAsync(hashResult.Value, cancellationToken); + if (orderResult.IsFailed) throw new Exception("Target system order entity context cannot be traced."); - if (!string.Equals(localSignature.Value, payload.Signature, StringComparison.OrdinalIgnoreCase)) + var paymentResult = await paymentService.GetOrderPaymentAsync(orderResult.Value.Id, cancellationToken); + if (paymentResult.IsFailed) throw new Exception("Target payment ledger entity cannot be resolved."); + + var isAlreadyProcessed = await paymentService.HasLedgerEntryAsync(orderResult.Value.Id, paymentResult.Value.Id, cancellationToken); + if (isAlreadyProcessed.Value) { - logger.LogCritical("Incoming webhook signature verification failed. Possible payload tampering."); + logger.LogWarning("Webhook reference token '{Ref}' already verified. Skipping processing routines.", payload.MerchantPaymentId); return; } - var hashResult = hashService.DecodeLongIdHash(payload.MerchantPaymentId!); - - if (hashResult.IsFailed) throw new Exception("Failed to decode application tracking hash key identifier."); - - var orderResult = await orderService.GetOrderAsync(hashResult.Value, cancellationToken); - - if (orderResult.IsFailed) throw new Exception("Target system order entity context cannot be traced."); - - var paymentResult = await paymentService.GetOrderPaymentAsync(orderResult.Value.Id, cancellationToken); - - if (paymentResult.IsFailed) throw new Exception("Target payment ledger entity cannot be resolved."); + var isAmountValid = payfastService.ValidatePaymentAmount(orderResult.Value.Total, payload.AmountGross); + if (!isAmountValid.Value) + throw new Exception("Security validation exception: Transaction cost variance bounds breached (Price Tampering Detected)."); decimal.TryParse(payload.AmountGross, CultureInfo.InvariantCulture, out var gross); decimal.TryParse(payload.AmountFee, CultureInfo.InvariantCulture, out var fee); decimal.TryParse(payload.AmountNet, CultureInfo.InvariantCulture, out var net); string status = payload.PaymentStatus ?? "UNKNOWN"; - var isAlreadyProcessed = await paymentService.HasLedgerEntryAsync(orderResult.Value.Id, paymentResult.Value.Id, cancellationToken); - - if (isAlreadyProcessed.Value) - { - logger.LogWarning("Webhook reference token '{Ref}' already verified. Skipping validation routines.", payload.MerchantPaymentId); - - return; - } - - if (notification.PerformBackgroundChecks) - { - var isHostValid = await payfastService.ValidateReferrerIpAsync(notification.RemoteIpAddress!, notification.AllowLoopback, cancellationToken); - - if (isHostValid.IsFailed) - throw new Exception("Security validation exception: Webhook packet source address failed cluster validation checks."); - - if (!isHostValid.Value) - throw new Exception("Security validation exception: Webhook packet source address failed cluster validation checks."); - - var isAmountValid = payfastService.ValidatePaymentAmount(orderResult.Value.Total, payload.AmountGross); - - if (!isAmountValid.Value) - throw new Exception("Security validation exception: Transaction cost variance bounds breached."); - - var paramList = new List(); - - foreach (var kvp in dict) - { - if (!string.IsNullOrEmpty(kvp.Value)) - { - string encoded = HttpUtility.UrlEncode(kvp.Value.Trim()); - - string safeValue = PayfastService.PercentEncodingRegex.Replace(encoded, m => m.Value.ToLowerInvariant()); - paramList.Add($"{kvp.Key}={safeValue}"); - } - } - - string rawParamString = string.Join("&", paramList); - - var serverConfirmation = await payfastService.ValidateServerConfirmationAsync(rawParamString, isSandbox: true, cancellationToken); - - if (serverConfirmation.IsFailed) - throw new Exception("Security validation exception: Payfast central handshake server rejected payload legitimacy."); - } - await payfastService.WriteLedgerEntryAsync(new CreateGatewayLedgerEntry { OrderId = orderResult.Value.Id, @@ -124,31 +71,23 @@ public sealed class PayfastPaymentConfirmationReceivedEventHandler(IServiceProvi CustomerId = orderResult.Value.CustomerId, }, cancellationToken); - if (ledgerWriteResult.IsFailed) - throw new Exception("Failed to write ledger entry for payment confirmation."); + if (ledgerWriteResult.IsFailed) throw new Exception("Failed to write ledger entry for payment confirmation."); var completePaymentResult = await paymentService.CompletePaymentAsync(paymentResult.Value.Id, PaymentStatuses.Paid, cancellationToken); - - if (completePaymentResult.IsFailed) - throw new Exception("Failed to update payment status to 'Paid' for payment confirmation."); + if (completePaymentResult.IsFailed) throw new Exception("Failed to update payment status to 'Paid'."); var updateOrderResult = await orderService.UpdateOrderStatusAsync(orderResult.Value.Id, OrderStatus.Completed, cancellationToken); - - if (updateOrderResult.IsFailed) - throw new Exception("Failed to update order status to 'Completed' for payment confirmation."); + if (updateOrderResult.IsFailed) throw new Exception("Failed to update order status to 'Completed'."); logger.LogInformation("Order payment verified secure and cleared successfully."); } else { - LedgerStatuses ledgerStatus; + LedgerStatuses ledgerStatus = status.Equals("CANCELLED", StringComparison.OrdinalIgnoreCase) + ? LedgerStatuses.Cancelled + : LedgerStatuses.Failed; - if (status.Equals("CANCELLED", StringComparison.OrdinalIgnoreCase)) - ledgerStatus = LedgerStatuses.Cancelled; - else - ledgerStatus = LedgerStatuses.Failed; - - var ledgerWriteResult = await paymentService.WriteLedgerEntryAsync(new CreateLedgerEntry + await paymentService.WriteLedgerEntryAsync(new CreateLedgerEntry { OrderId = orderResult.Value.Id, PaymentId = paymentResult.Value.Id, @@ -157,8 +96,9 @@ public sealed class PayfastPaymentConfirmationReceivedEventHandler(IServiceProvi CustomerId = orderResult.Value.CustomerId, }, cancellationToken); - logger.LogInformation("Webhook validation pipeline passed checks successfully, logged entry to ledger with status: {Status}", status); + logger.LogInformation("Webhook pipeline logged non-success entry to ledger with status: {Status}", status); } + activity?.SetStatus(ActivityStatusCode.Ok); } }