Compare commits
12 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| b09af460f1 | |||
| 7c5b5f1728 | |||
| 50db61b3ee | |||
| 94b0084d75 | |||
| f5ad8e2d50 | |||
| 8e2942487d | |||
| fa79a58004 | |||
| 9997d4f0ed | |||
| 33edae9eff | |||
| c1e52ea908 | |||
| 0d5702f0fe | |||
| e4c3779092 |
@@ -11,7 +11,7 @@
|
||||
<!-- Quartz Scheduler-->
|
||||
<ItemGroup>
|
||||
<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>
|
||||
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
|
||||
</PackageReference>
|
||||
@@ -116,8 +116,8 @@
|
||||
|
||||
<!-- Amazon S3 SDK -->
|
||||
<ItemGroup>
|
||||
<PackageReference Include="AWSSDK.Extensions.NetCore.Setup" Version="4.0.4.6" />
|
||||
<PackageReference Include="AWSSDK.S3" Version="4.0.24.3" />
|
||||
<PackageReference Include="AWSSDK.Extensions.NetCore.Setup" Version="4.0.4.7" />
|
||||
<PackageReference Include="AWSSDK.S3" Version="4.0.24.4" />
|
||||
<ProjectReference Include="..\LiteCharms.Features\LiteCharms.Features.csproj" />
|
||||
|
||||
<!-- global Usings -->
|
||||
|
||||
@@ -32,7 +32,7 @@
|
||||
<!-- Quartz Scheduler-->
|
||||
<ItemGroup>
|
||||
<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>
|
||||
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
|
||||
</PackageReference>
|
||||
@@ -136,8 +136,8 @@
|
||||
|
||||
<!-- Amazon S3 SDK -->
|
||||
<ItemGroup>
|
||||
<PackageReference Include="AWSSDK.Extensions.NetCore.Setup" Version="4.0.4.6" />
|
||||
<PackageReference Include="AWSSDK.S3" Version="4.0.24.3" />
|
||||
<PackageReference Include="AWSSDK.Extensions.NetCore.Setup" Version="4.0.4.7" />
|
||||
<PackageReference Include="AWSSDK.S3" Version="4.0.24.4" />
|
||||
<ProjectReference Include="..\LiteCharms.Features\LiteCharms.Features.csproj" />
|
||||
|
||||
<!-- global Usings -->
|
||||
|
||||
+27
-87
@@ -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<PayfastSettings> payfastOptions, ILogger<PayfastPaymentConfirmationReceivedEvent> logger) :
|
||||
public sealed class PayfastPaymentConfirmationReceivedEventHandler(IServiceProvider services, ILogger<PayfastPaymentConfirmationReceivedEvent> logger) :
|
||||
INotificationHandler<PayfastPaymentConfirmationReceivedEvent>
|
||||
{
|
||||
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<PaymentService>();
|
||||
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 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<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
|
||||
{
|
||||
OrderId = orderResult.Value.Id,
|
||||
@@ -119,46 +66,39 @@ public sealed class PayfastPaymentConfirmationReceivedEventHandler(IServiceProvi
|
||||
{
|
||||
OrderId = orderResult.Value.Id,
|
||||
PaymentId = paymentResult.Value.Id,
|
||||
PaymentGatewayReference = payload.PaymentId!,
|
||||
PaymentGatewayReference = payload.MerchantPaymentId!,
|
||||
Status = LedgerStatuses.Completed,
|
||||
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,
|
||||
PaymentGatewayReference = payload.PaymentId!,
|
||||
PaymentGatewayReference = payload.MerchantPaymentId!,
|
||||
Status = ledgerStatus,
|
||||
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);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -48,21 +48,24 @@ public sealed partial class PayfastService(IDbContextFactory<MidrandBooksDbConte
|
||||
}
|
||||
}
|
||||
|
||||
public static bool VerifyIncomingSignature(IDictionary<string, string> formFields, string passphrase)
|
||||
public static bool VerifyIncomingSignatureFromForm(IFormCollection formCollection, string passphrase)
|
||||
{
|
||||
if (!formFields.TryGetValue("signature", out string? incomingSignature))
|
||||
return false;
|
||||
var sortedFields = new Dictionary<string, string>(StringComparer.Ordinal);
|
||||
|
||||
foreach (var field in formCollection)
|
||||
{
|
||||
sortedFields.Add(field.Key, field.Value.ToString());
|
||||
}
|
||||
|
||||
if (!sortedFields.TryGetValue("signature", out var incomingSignature)) return false;
|
||||
|
||||
var stringBuilder = new StringBuilder();
|
||||
|
||||
foreach (var key in formFields.Keys)
|
||||
foreach (var key in sortedFields.Keys)
|
||||
{
|
||||
if (key.Equals("signature", StringComparison.OrdinalIgnoreCase))
|
||||
continue;
|
||||
if (key.Equals("signature", StringComparison.OrdinalIgnoreCase)) continue;
|
||||
|
||||
string rawValue = formFields[key] ?? string.Empty;
|
||||
|
||||
string encodedVal = HttpUtility.UrlEncode(rawValue.Trim());
|
||||
string encodedVal = HttpUtility.UrlEncode(sortedFields[key].Trim());
|
||||
string cleanVal = PercentEncodingRegex.Replace(encodedVal, m => m.Value.ToUpperInvariant());
|
||||
|
||||
stringBuilder.Append($"{key}={cleanVal}&");
|
||||
|
||||
@@ -123,8 +123,7 @@ public sealed class PaymentService(IDbContextFactory<MidrandBooksDbContext> cont
|
||||
await using var context = await contextFactory.CreateDbContextAsync(cancellationToken);
|
||||
|
||||
var exists = await context.Ledger.AnyAsync(l =>
|
||||
l.OrderId == orderId &&
|
||||
l.PaymentId == paymentId, cancellationToken);
|
||||
l.OrderId == orderId && l.PaymentId == paymentId && l.Status == LedgerStatuses.Completed, cancellationToken);
|
||||
|
||||
return Result.Ok(exists);
|
||||
}
|
||||
@@ -162,7 +161,8 @@ public sealed class PaymentService(IDbContextFactory<MidrandBooksDbContext> cont
|
||||
CustomerId = request.CustomerId,
|
||||
OrderId = request.OrderId,
|
||||
PaymentId = request.PaymentId,
|
||||
Status = request.Status,
|
||||
MerchantPaymentId = request.PaymentGatewayReference,
|
||||
Status = request.Status,
|
||||
});
|
||||
|
||||
return await context.SaveChangesAsync(cancellationToken) > 0
|
||||
|
||||
@@ -136,8 +136,8 @@
|
||||
|
||||
<!-- Amazon S3 SDK -->
|
||||
<ItemGroup>
|
||||
<PackageReference Include="AWSSDK.Extensions.NetCore.Setup" Version="4.0.4.6" />
|
||||
<PackageReference Include="AWSSDK.S3" Version="4.0.24.3" />
|
||||
<PackageReference Include="AWSSDK.Extensions.NetCore.Setup" Version="4.0.4.7" />
|
||||
<PackageReference Include="AWSSDK.S3" Version="4.0.24.4" />
|
||||
<ProjectReference Include="..\LiteCharms.Features\LiteCharms.Features.csproj" />
|
||||
|
||||
<!-- global Usings -->
|
||||
|
||||
@@ -79,7 +79,7 @@
|
||||
<!-- Quartz Scheduler-->
|
||||
<ItemGroup>
|
||||
<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>
|
||||
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
|
||||
</PackageReference>
|
||||
@@ -183,8 +183,8 @@
|
||||
|
||||
<!-- Amazon S3 SDK -->
|
||||
<ItemGroup>
|
||||
<PackageReference Include="AWSSDK.Extensions.NetCore.Setup" Version="4.0.4.6" />
|
||||
<PackageReference Include="AWSSDK.S3" Version="4.0.24.3" />
|
||||
<PackageReference Include="AWSSDK.Extensions.NetCore.Setup" Version="4.0.4.7" />
|
||||
<PackageReference Include="AWSSDK.S3" Version="4.0.24.4" />
|
||||
|
||||
<!-- global Usings -->
|
||||
<Using Include="Amazon.S3" />
|
||||
|
||||
Reference in New Issue
Block a user