Compare commits

..

10 Commits

Author SHA1 Message Date
khwezi f5ad8e2d50 Merge pull request 'Ensured the merchant payment id makes it to the ledger' (#115) from payments into master
Reviewed-on: #115
2026-06-13 17:01:36 +02:00
Khwezi Mngoma 8e2942487d Ensured the merchant payment id makes it to the ledger
continuous-integration/drone/pr Build is passing
2026-06-13 17:00:08 +02:00
khwezi fa79a58004 Merge pull request 'Fixed package mismatches' (#114) from payments into master
Reviewed-on: #114
2026-06-13 16:33:05 +02:00
Khwezi Mngoma 9997d4f0ed Fixed package mismatches
continuous-integration/drone/pr Build is passing
2026-06-13 16:32:39 +02:00
khwezi 33edae9eff Merge pull request 'Simplified PayfastPaymentConfirmationReceivedEventHandler' (#113) from payments into master
Reviewed-on: #113
2026-06-13 16:27:28 +02:00
Khwezi Mngoma c1e52ea908 Simplified PayfastPaymentConfirmationReceivedEventHandler
continuous-integration/drone/pr Build is failing
2026-06-13 16:26:47 +02:00
khwezi 0d5702f0fe Merge pull request 'Using IFormCollection for VerifyIncomingSignatureFromForm' (#112) from payments into master
Reviewed-on: #112
2026-06-13 16:05:57 +02:00
Khwezi Mngoma e4c3779092 Using IFormCollection for VerifyIncomingSignatureFromForm
continuous-integration/drone/pr Build is passing
2026-06-13 16:03:31 +02:00
khwezi da5f233c3b Merge pull request 'refactored incoming signature validator to use form fields instead of httprequest' (#111) from payments into master
Reviewed-on: #111
2026-06-13 15:58:58 +02:00
Khwezi Mngoma 02d89eec4f refactored incoming signature validator to use form fields instead of httprequest
continuous-integration/drone/pr Build is passing
2026-06-13 15:58:30 +02:00
7 changed files with 48 additions and 109 deletions
@@ -11,7 +11,7 @@
<!-- Quartz Scheduler--> <!-- Quartz Scheduler-->
<ItemGroup> <ItemGroup>
<PackageReference Include="Bogus" Version="35.6.5" /> <PackageReference Include="Bogus" Version="35.6.5" />
<PackageReference Include="Meziantou.Analyzer" Version="3.0.102"> <PackageReference Include="Meziantou.Analyzer" Version="3.0.103">
<PrivateAssets>all</PrivateAssets> <PrivateAssets>all</PrivateAssets>
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets> <IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
</PackageReference> </PackageReference>
@@ -116,8 +116,8 @@
<!-- Amazon S3 SDK --> <!-- Amazon S3 SDK -->
<ItemGroup> <ItemGroup>
<PackageReference Include="AWSSDK.Extensions.NetCore.Setup" Version="4.0.4.6" /> <PackageReference Include="AWSSDK.Extensions.NetCore.Setup" Version="4.0.4.7" />
<PackageReference Include="AWSSDK.S3" Version="4.0.24.3" /> <PackageReference Include="AWSSDK.S3" Version="4.0.24.4" />
<ProjectReference Include="..\LiteCharms.Features\LiteCharms.Features.csproj" /> <ProjectReference Include="..\LiteCharms.Features\LiteCharms.Features.csproj" />
<!-- global Usings --> <!-- global Usings -->
@@ -32,7 +32,7 @@
<!-- Quartz Scheduler--> <!-- Quartz Scheduler-->
<ItemGroup> <ItemGroup>
<PackageReference Include="Humanizer" Version="3.0.10" /> <PackageReference Include="Humanizer" Version="3.0.10" />
<PackageReference Include="Meziantou.Analyzer" Version="3.0.102"> <PackageReference Include="Meziantou.Analyzer" Version="3.0.103">
<PrivateAssets>all</PrivateAssets> <PrivateAssets>all</PrivateAssets>
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets> <IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
</PackageReference> </PackageReference>
@@ -136,8 +136,8 @@
<!-- Amazon S3 SDK --> <!-- Amazon S3 SDK -->
<ItemGroup> <ItemGroup>
<PackageReference Include="AWSSDK.Extensions.NetCore.Setup" Version="4.0.4.6" /> <PackageReference Include="AWSSDK.Extensions.NetCore.Setup" Version="4.0.4.7" />
<PackageReference Include="AWSSDK.S3" Version="4.0.24.3" /> <PackageReference Include="AWSSDK.S3" Version="4.0.24.4" />
<ProjectReference Include="..\LiteCharms.Features\LiteCharms.Features.csproj" /> <ProjectReference Include="..\LiteCharms.Features\LiteCharms.Features.csproj" />
<!-- global Usings --> <!-- global Usings -->
@@ -1,17 +1,13 @@
using LiteCharms.Features.Api.Configuration; using LiteCharms.Features.Hasher;
using LiteCharms.Features.Hasher;
using LiteCharms.Features.Mediator; using LiteCharms.Features.Mediator;
using LiteCharms.Features.MidrandBooks.Orders; using LiteCharms.Features.MidrandBooks.Orders;
using LiteCharms.Features.MidrandBooks.Payments.Models; using LiteCharms.Features.MidrandBooks.Payments.Models;
namespace LiteCharms.Features.MidrandBooks.Payments.Events.Handlers; namespace LiteCharms.Features.MidrandBooks.Payments.Events.Handlers;
public sealed class PayfastPaymentConfirmationReceivedEventHandler(IServiceProvider services, public sealed class PayfastPaymentConfirmationReceivedEventHandler(IServiceProvider services, ILogger<PayfastPaymentConfirmationReceivedEvent> logger) :
IOptions<PayfastSettings> payfastOptions, ILogger<PayfastPaymentConfirmationReceivedEvent> logger) :
INotificationHandler<PayfastPaymentConfirmationReceivedEvent> INotificationHandler<PayfastPaymentConfirmationReceivedEvent>
{ {
private readonly PayfastSettings pasfastSettings = payfastOptions.Value;
public async ValueTask Handle(PayfastPaymentConfirmationReceivedEvent notification, CancellationToken cancellationToken) public async ValueTask Handle(PayfastPaymentConfirmationReceivedEvent notification, CancellationToken cancellationToken)
{ {
using var activity = MediatorTelemetry.Source.StartActivity($"Quartz: {typeof(PayfastPaymentConfirmationReceivedEvent).Name}"); using var activity = MediatorTelemetry.Source.StartActivity($"Quartz: {typeof(PayfastPaymentConfirmationReceivedEvent).Name}");
@@ -23,83 +19,34 @@ public sealed class PayfastPaymentConfirmationReceivedEventHandler(IServiceProvi
var paymentService = scope.ServiceProvider.GetRequiredService<PaymentService>(); var paymentService = scope.ServiceProvider.GetRequiredService<PaymentService>();
var payfastService = scope.ServiceProvider.GetRequiredService<PayfastService>(); var payfastService = scope.ServiceProvider.GetRequiredService<PayfastService>();
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 hashResult = hashService.DecodeLongIdHash(payload.MerchantPaymentId!);
var localSignature = PayfastService.GenerateSignature(dict, pasfastSettings.Passphrase); if (hashResult.IsFailed) throw new Exception("Failed to decode application tracking hash key identifier.");
if (localSignature.IsFailed) var orderResult = await orderService.GetOrderAsync(hashResult.Value, cancellationToken);
throw new Exception("Failed to generate local signature for incoming webhook payload."); 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; return;
} }
var hashResult = hashService.DecodeLongIdHash(payload.MerchantPaymentId!); var isAmountValid = payfastService.ValidatePaymentAmount(orderResult.Value.Total, payload.AmountGross);
if (!isAmountValid.Value)
if (hashResult.IsFailed) throw new Exception("Failed to decode application tracking hash key identifier."); throw new Exception("Security validation exception: Transaction cost variance bounds breached (Price Tampering Detected).");
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.");
decimal.TryParse(payload.AmountGross, CultureInfo.InvariantCulture, out var gross); decimal.TryParse(payload.AmountGross, CultureInfo.InvariantCulture, out var gross);
decimal.TryParse(payload.AmountFee, CultureInfo.InvariantCulture, out var fee); decimal.TryParse(payload.AmountFee, CultureInfo.InvariantCulture, out var fee);
decimal.TryParse(payload.AmountNet, CultureInfo.InvariantCulture, out var net); decimal.TryParse(payload.AmountNet, CultureInfo.InvariantCulture, out var net);
string status = payload.PaymentStatus ?? "UNKNOWN"; 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<string>();
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 await payfastService.WriteLedgerEntryAsync(new CreateGatewayLedgerEntry
{ {
OrderId = orderResult.Value.Id, OrderId = orderResult.Value.Id,
@@ -124,31 +71,23 @@ public sealed class PayfastPaymentConfirmationReceivedEventHandler(IServiceProvi
CustomerId = orderResult.Value.CustomerId, CustomerId = orderResult.Value.CustomerId,
}, cancellationToken); }, cancellationToken);
if (ledgerWriteResult.IsFailed) if (ledgerWriteResult.IsFailed) throw new Exception("Failed to write ledger entry for payment confirmation.");
throw new Exception("Failed to write ledger entry for payment confirmation.");
var completePaymentResult = await paymentService.CompletePaymentAsync(paymentResult.Value.Id, PaymentStatuses.Paid, cancellationToken); var completePaymentResult = await paymentService.CompletePaymentAsync(paymentResult.Value.Id, PaymentStatuses.Paid, cancellationToken);
if (completePaymentResult.IsFailed) throw new Exception("Failed to update payment status to 'Paid'.");
if (completePaymentResult.IsFailed)
throw new Exception("Failed to update payment status to 'Paid' for payment confirmation.");
var updateOrderResult = await orderService.UpdateOrderStatusAsync(orderResult.Value.Id, OrderStatus.Completed, cancellationToken); var updateOrderResult = await orderService.UpdateOrderStatusAsync(orderResult.Value.Id, OrderStatus.Completed, cancellationToken);
if (updateOrderResult.IsFailed) throw new Exception("Failed to update order status to 'Completed'.");
if (updateOrderResult.IsFailed)
throw new Exception("Failed to update order status to 'Completed' for payment confirmation.");
logger.LogInformation("Order payment verified secure and cleared successfully."); logger.LogInformation("Order payment verified secure and cleared successfully.");
} }
else else
{ {
LedgerStatuses ledgerStatus; LedgerStatuses ledgerStatus = status.Equals("CANCELLED", StringComparison.OrdinalIgnoreCase)
? LedgerStatuses.Cancelled
: LedgerStatuses.Failed;
if (status.Equals("CANCELLED", StringComparison.OrdinalIgnoreCase)) await paymentService.WriteLedgerEntryAsync(new CreateLedgerEntry
ledgerStatus = LedgerStatuses.Cancelled;
else
ledgerStatus = LedgerStatuses.Failed;
var ledgerWriteResult = await paymentService.WriteLedgerEntryAsync(new CreateLedgerEntry
{ {
OrderId = orderResult.Value.Id, OrderId = orderResult.Value.Id,
PaymentId = paymentResult.Value.Id, PaymentId = paymentResult.Value.Id,
@@ -157,8 +96,9 @@ public sealed class PayfastPaymentConfirmationReceivedEventHandler(IServiceProvi
CustomerId = orderResult.Value.CustomerId, CustomerId = orderResult.Value.CustomerId,
}, cancellationToken); }, 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); activity?.SetStatus(ActivityStatusCode.Ok);
} }
} }
@@ -48,26 +48,24 @@ public sealed partial class PayfastService(IDbContextFactory<MidrandBooksDbConte
} }
} }
public static bool VerifyIncomingSignature(HttpRequest request, string passphrase) public static bool VerifyIncomingSignatureFromForm(IFormCollection formCollection, string passphrase)
{ {
var formFields = new Dictionary<string, string>(StringComparer.Ordinal); var sortedFields = new Dictionary<string, string>(StringComparer.Ordinal);
foreach (var file in request.Form) foreach (var field in formCollection)
formFields.Add(file.Key, file.Value.ToString()); {
sortedFields.Add(field.Key, field.Value.ToString());
}
if (!formFields.TryGetValue("signature", out string? incomingSignature)) if (!sortedFields.TryGetValue("signature", out var incomingSignature)) return false;
return false;
var stringBuilder = new StringBuilder(); var stringBuilder = new StringBuilder();
foreach (var key in formFields.Keys) foreach (var key in sortedFields.Keys)
{ {
if (key.Equals("signature", StringComparison.OrdinalIgnoreCase)) if (key.Equals("signature", StringComparison.OrdinalIgnoreCase)) continue;
continue;
string rawValue = formFields[key] ?? string.Empty; string encodedVal = HttpUtility.UrlEncode(sortedFields[key].Trim());
string encodedVal = HttpUtility.UrlEncode(rawValue.Trim());
string cleanVal = PercentEncodingRegex.Replace(encodedVal, m => m.Value.ToUpperInvariant()); string cleanVal = PercentEncodingRegex.Replace(encodedVal, m => m.Value.ToUpperInvariant());
stringBuilder.Append($"{key}={cleanVal}&"); stringBuilder.Append($"{key}={cleanVal}&");
@@ -162,7 +162,8 @@ public sealed class PaymentService(IDbContextFactory<MidrandBooksDbContext> cont
CustomerId = request.CustomerId, CustomerId = request.CustomerId,
OrderId = request.OrderId, OrderId = request.OrderId,
PaymentId = request.PaymentId, PaymentId = request.PaymentId,
Status = request.Status, MerchantPaymentId = request.PaymentGatewayReference,
Status = request.Status,
}); });
return await context.SaveChangesAsync(cancellationToken) > 0 return await context.SaveChangesAsync(cancellationToken) > 0
@@ -136,8 +136,8 @@
<!-- Amazon S3 SDK --> <!-- Amazon S3 SDK -->
<ItemGroup> <ItemGroup>
<PackageReference Include="AWSSDK.Extensions.NetCore.Setup" Version="4.0.4.6" /> <PackageReference Include="AWSSDK.Extensions.NetCore.Setup" Version="4.0.4.7" />
<PackageReference Include="AWSSDK.S3" Version="4.0.24.3" /> <PackageReference Include="AWSSDK.S3" Version="4.0.24.4" />
<ProjectReference Include="..\LiteCharms.Features\LiteCharms.Features.csproj" /> <ProjectReference Include="..\LiteCharms.Features\LiteCharms.Features.csproj" />
<!-- global Usings --> <!-- global Usings -->
@@ -79,7 +79,7 @@
<!-- Quartz Scheduler--> <!-- Quartz Scheduler-->
<ItemGroup> <ItemGroup>
<PackageReference Include="Hashids.net" Version="1.7.0" /> <PackageReference Include="Hashids.net" Version="1.7.0" />
<PackageReference Include="Meziantou.Analyzer" Version="3.0.102"> <PackageReference Include="Meziantou.Analyzer" Version="3.0.103">
<PrivateAssets>all</PrivateAssets> <PrivateAssets>all</PrivateAssets>
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets> <IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
</PackageReference> </PackageReference>
@@ -183,8 +183,8 @@
<!-- Amazon S3 SDK --> <!-- Amazon S3 SDK -->
<ItemGroup> <ItemGroup>
<PackageReference Include="AWSSDK.Extensions.NetCore.Setup" Version="4.0.4.6" /> <PackageReference Include="AWSSDK.Extensions.NetCore.Setup" Version="4.0.4.7" />
<PackageReference Include="AWSSDK.S3" Version="4.0.24.3" /> <PackageReference Include="AWSSDK.S3" Version="4.0.24.4" />
<!-- global Usings --> <!-- global Usings -->
<Using Include="Amazon.S3" /> <Using Include="Amazon.S3" />