Added payment gateway ledger service to payments feature
This commit is contained in:
@@ -0,0 +1,11 @@
|
||||
using LiteCharms.Features.MidrandBooks.Orders.Entities;
|
||||
|
||||
namespace LiteCharms.Features.MidrandBooks.Payments.Entities;
|
||||
|
||||
[EntityTypeConfiguration<PaymentGatewayLedgerConfiguration, PaymentGatewayLedger>]
|
||||
public class PaymentGatewayLedger : Models.PaymentGatewayLedger
|
||||
{
|
||||
public virtual Order? Order { get; set; }
|
||||
|
||||
public virtual Payment? Payment { get; set; }
|
||||
}
|
||||
+30
@@ -0,0 +1,30 @@
|
||||
namespace LiteCharms.Features.MidrandBooks.Payments.Entities;
|
||||
|
||||
public sealed class PaymentGatewayLedgerConfiguration : IEntityTypeConfiguration<PaymentGatewayLedger>
|
||||
{
|
||||
public void Configure(EntityTypeBuilder<PaymentGatewayLedger> builder)
|
||||
{
|
||||
builder.ToTable("GatewayLedger");
|
||||
|
||||
builder.HasKey(f => f.Id);
|
||||
builder.Property(f => f.CreatedAt).IsRequired().ValueGeneratedOnAdd().HasDefaultValueSql("now()");
|
||||
builder.Property(f => f.OrderId).IsRequired();
|
||||
builder.Property(f => f.PaymentId).IsRequired();
|
||||
builder.Property(f => f.PayfastPaymentId).IsRequired();
|
||||
builder.Property(f => f.MerchantPaymentId).IsRequired();
|
||||
builder.Property(f => f.AmountGross).IsRequired().HasPrecision(18, 2);
|
||||
builder.Property(f => f.AmountFee).IsRequired().HasPrecision(18, 2);
|
||||
builder.Property(f => f.AmountNet).IsRequired().HasPrecision(18, 2);
|
||||
builder.Property(f => f.CustomerEmail).IsRequired(false);
|
||||
|
||||
builder.HasOne(f => f.Order)
|
||||
.WithMany()
|
||||
.HasForeignKey(f => f.OrderId)
|
||||
.OnDelete(DeleteBehavior.Cascade);
|
||||
|
||||
builder.HasOne(f => f.Payment)
|
||||
.WithMany()
|
||||
.HasForeignKey(f => f.PaymentId)
|
||||
.OnDelete(DeleteBehavior.Cascade);
|
||||
}
|
||||
}
|
||||
@@ -11,6 +11,4 @@ public class PaymentLedger : Models.PaymentLedger
|
||||
public virtual Order? Order { get; set; }
|
||||
|
||||
public virtual Customer? Customer { get; set; }
|
||||
|
||||
public virtual PaymentGateway? Gateway { get; set; }
|
||||
}
|
||||
|
||||
@@ -9,8 +9,7 @@ public sealed class PaymentLedgerConfiguration : IEntityTypeConfiguration<Paymen
|
||||
builder.HasKey(f => f.Id);
|
||||
builder.Property(f => f.CreatedAt).IsRequired().ValueGeneratedOnAdd().HasDefaultValueSql("now()");
|
||||
builder.Property(f => f.Status).IsRequired();
|
||||
builder.Property(f => f.PaymentGatewayReference).IsRequired(false);
|
||||
builder.Property(f => f.PaymentGatewayId).IsRequired(false);
|
||||
builder.Property(f => f.MerchantPaymentId).IsRequired(false);
|
||||
builder.Property(f => f.OrderId).IsRequired();
|
||||
builder.Property(f => f.CustomerId).IsRequired();
|
||||
builder.Property(f => f.PaymentId).IsRequired();
|
||||
@@ -31,11 +30,5 @@ public sealed class PaymentLedgerConfiguration : IEntityTypeConfiguration<Paymen
|
||||
.WithMany()
|
||||
.IsRequired()
|
||||
.HasForeignKey(f => f.CustomerId);
|
||||
|
||||
builder.HasOne(f => f.Gateway)
|
||||
.WithMany()
|
||||
.IsRequired(false)
|
||||
.HasForeignKey(f => f.PaymentGatewayId)
|
||||
.OnDelete(DeleteBehavior.Cascade);
|
||||
}
|
||||
}
|
||||
|
||||
+130
-58
@@ -1,86 +1,158 @@
|
||||
using LiteCharms.Features.Hasher;
|
||||
using LiteCharms.Features.Hasher.Configuration;
|
||||
using LiteCharms.Features.MidrandBooks.Orders;
|
||||
using LiteCharms.Features.MidrandBooks.Payments.Models;
|
||||
|
||||
namespace LiteCharms.Features.MidrandBooks.Payments.Events.Handlers;
|
||||
|
||||
public sealed class PayfastPaymentConfirmationReceivedEventHandler(IServiceProvider services, ILogger<PayfastPaymentConfirmationReceivedEvent> logger) :
|
||||
public sealed class PayfastPaymentConfirmationReceivedEventHandler(IServiceProvider services, IOptions<HasherSettings> hasherOptions, ILogger<PayfastPaymentConfirmationReceivedEvent> logger) :
|
||||
INotificationHandler<PayfastPaymentConfirmationReceivedEvent>
|
||||
{
|
||||
private readonly HasherSettings hasherSettings = hasherOptions.Value;
|
||||
|
||||
public async ValueTask Handle(PayfastPaymentConfirmationReceivedEvent notification, CancellationToken cancellationToken)
|
||||
{
|
||||
await using var scope = services.CreateAsyncScope();
|
||||
var hashService = scope.ServiceProvider.GetRequiredService<HashService>();
|
||||
var orderService = scope.ServiceProvider.GetRequiredService<OrderService>();
|
||||
var paymentService = scope.ServiceProvider.GetRequiredService<PaymentService>();
|
||||
var payfastService = scope.ServiceProvider.GetRequiredService<PayfastService>();
|
||||
|
||||
PaymentService paymentService = scope.ServiceProvider.GetRequiredService<PaymentService>();
|
||||
OrderService orderService = scope.ServiceProvider.GetRequiredService<OrderService>();
|
||||
HashService hashService = scope.ServiceProvider.GetRequiredService<HashService>();
|
||||
var payload = notification.Payload ?? throw new Exception("Payload metadata context context is null.");
|
||||
|
||||
var hashResult = hashService.DecodeLongIdHash(notification.Payload?.MPaymentId!);
|
||||
if (hashResult.IsFailed)
|
||||
var dict = payload.ToParamDictionary();
|
||||
var localSignature = PayfastService.GenerateSignature(dict, hasherSettings.PayfastPassphrase);
|
||||
|
||||
if(localSignature.IsFailed)
|
||||
throw new Exception("Failed to generate local signature for incoming webhook payload.");
|
||||
|
||||
if (!string.Equals(localSignature.Value, payload.Signature, StringComparison.OrdinalIgnoreCase))
|
||||
{
|
||||
logger.LogError("Failed to decode payment ID hash: {Hash}. Errors: {Errors}", notification.Payload?.MPaymentId, string.Join(", ", hashResult.Errors.Select(e => e.Message)));
|
||||
throw new Exception($"Failed to decode payment ID hash: {notification.Payload?.MPaymentId}.");
|
||||
}
|
||||
logger.LogCritical("Incoming webhook signature verification failed. Possible payload tampering.");
|
||||
|
||||
var orderResult = await orderService.GetOrderAsync(hashResult.Value, cancellationToken);
|
||||
if (orderResult.IsFailed)
|
||||
{
|
||||
logger.LogError("Failed to retrieve order for payment ID: {PaymentId}. Errors: {Errors}", notification.Payload?.MPaymentId, string.Join(", ", orderResult.Errors.Select(e => e.Message)));
|
||||
throw new Exception($"Failed to retrieve order for payment ID: {notification.Payload?.MPaymentId}.");
|
||||
}
|
||||
|
||||
var paymentResult = await paymentService.GetOrderPaymentAsync(orderResult.Value.CustomerId, cancellationToken);
|
||||
if (paymentResult.IsFailed)
|
||||
{
|
||||
logger.LogError("Failed to retrieve payment for order ID: {OrderId}. Errors: {Errors}", orderResult.Value.Id, string.Join(", ", paymentResult.Errors.Select(e => e.Message)));
|
||||
throw new Exception($"Failed to retrieve payment for order ID: {orderResult.Value.Id}.");
|
||||
}
|
||||
|
||||
var isAlreadyProcessed = await paymentService.HasLedgerEntryAsync(orderResult.Value.Id, paymentResult.Value.Id, 1, cancellationToken);
|
||||
|
||||
if (isAlreadyProcessed.IsFailed)
|
||||
{
|
||||
logger.LogError("Failed to check existing ledger entry for order ID: {OrderId} and payment ID: {PaymentId}. Errors: {Errors}", orderResult.Value.Id, paymentResult.Value.Id, string.Join(", ", isAlreadyProcessed.Errors.Select(e => e.Message)));
|
||||
throw new Exception($"Failed to check existing ledger entry for order ID: {orderResult.Value.Id} and payment ID: {paymentResult.Value.Id}.");
|
||||
}
|
||||
|
||||
if (isAlreadyProcessed.Value)
|
||||
{
|
||||
logger.LogInformation("Payment confirmation for payment ID: {PaymentId} has already been processed. Skipping.", notification.Payload?.MPaymentId);
|
||||
return;
|
||||
}
|
||||
|
||||
var ledgerResult = await paymentService.WriteLedgerEntryAsync(new Models.CreateLedgerEntry
|
||||
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.");
|
||||
|
||||
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!, 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
|
||||
{
|
||||
CustomerId = orderResult.Value.CustomerId,
|
||||
OrderId = orderResult.Value.Id,
|
||||
PaymentId = paymentResult.Value.Id,
|
||||
Status = LedgerStatuses.Received,
|
||||
PaymentGatewayId = 1,
|
||||
PaymentGatewayReference = notification.CorrelationId,
|
||||
MerchantPaymentId = payload.MerchantPaymentId!,
|
||||
PayfastPaymentId = payload.PaymentId,
|
||||
CustomerEmail = payload.EmailAddress,
|
||||
AmountFee = fee,
|
||||
AmountGross = gross,
|
||||
AmountNet = net,
|
||||
PaymentStatus = status,
|
||||
}, cancellationToken);
|
||||
|
||||
if (ledgerResult.IsFailed)
|
||||
if (status.Equals("COMPLETE", StringComparison.OrdinalIgnoreCase))
|
||||
{
|
||||
logger.LogError("Failed to write ledger entry for payment ID: {PaymentId}. Errors: {Errors}", notification.Payload?.MPaymentId, string.Join(", ", ledgerResult.Errors.Select(e => e.Message)));
|
||||
throw new Exception($"Failed to write ledger entry for payment ID: {notification.Payload?.MPaymentId}.");
|
||||
}
|
||||
var ledgerWriteResult = await paymentService.WriteLedgerEntryAsync(new CreateLedgerEntry
|
||||
{
|
||||
OrderId = orderResult.Value.Id,
|
||||
PaymentId = paymentResult.Value.Id,
|
||||
PaymentGatewayReference = payload.PaymentId!,
|
||||
Status = LedgerStatuses.Completed,
|
||||
CustomerId = orderResult.Value.CustomerId,
|
||||
}, cancellationToken);
|
||||
|
||||
var paymentCompletedResult = await paymentService.CompletePaymentAsync(paymentResult.Value.Id, PaymentStatuses.Paid, cancellationToken);
|
||||
if (paymentCompletedResult.IsFailed)
|
||||
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.");
|
||||
|
||||
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.");
|
||||
|
||||
logger.LogInformation("Order payment verified secure and cleared successfully.");
|
||||
}
|
||||
else
|
||||
{
|
||||
logger.LogError("Failed to complete payment for order ID: {OrderId}. Errors: {Errors}", orderResult.Value.Id, string.Join(", ", paymentCompletedResult.Errors.Select(e => e.Message)));
|
||||
throw new Exception($"Failed to complete payment for order ID: {orderResult.Value.Id}.");
|
||||
LedgerStatuses ledgerStatus;
|
||||
|
||||
if (status.Equals("CANCELLED", StringComparison.OrdinalIgnoreCase))
|
||||
ledgerStatus = LedgerStatuses.Cancelled;
|
||||
else
|
||||
ledgerStatus = LedgerStatuses.Failed;
|
||||
|
||||
var ledgerWriteResult = await paymentService.WriteLedgerEntryAsync(new CreateLedgerEntry
|
||||
{
|
||||
OrderId = orderResult.Value.Id,
|
||||
PaymentId = paymentResult.Value.Id,
|
||||
PaymentGatewayReference = payload.PaymentId!,
|
||||
Status = ledgerStatus,
|
||||
CustomerId = orderResult.Value.CustomerId,
|
||||
}, cancellationToken);
|
||||
|
||||
logger.LogInformation("Webhook validation pipeline passed checks successfully, logged entry to ledger with status: {Status}", status);
|
||||
}
|
||||
|
||||
var orderCompletedResult = await orderService.UpdateOrderStatusAsync(orderResult.Value.Id, OrderStatus.Completed, cancellationToken);
|
||||
if (orderCompletedResult.IsFailed)
|
||||
{
|
||||
logger.LogError("Failed to update order status to Completed for order ID: {OrderId}. Errors: {Errors}", orderResult.Value.Id, string.Join(", ", orderCompletedResult.Errors.Select(e => e.Message)));
|
||||
throw new Exception($"Failed to update order status to Completed for order ID: {orderResult.Value.Id}.");
|
||||
}
|
||||
|
||||
logger.LogInformation("Received Payfast payment confirmation for payment ID: {PaymentId}", notification.Payload?.MPaymentId);
|
||||
|
||||
// TODO: Publish MediatR notifications or queue downstream Quartz jobs (Discord, Shipping, Customer Email, Royalties)
|
||||
}
|
||||
}
|
||||
|
||||
+9
-4
@@ -1,5 +1,5 @@
|
||||
using LiteCharms.Features.Abstractions;
|
||||
using LiteCharms.Features.Models;
|
||||
using LiteCharms.Features.MidrandBooks.Payments.Models;
|
||||
|
||||
namespace LiteCharms.Features.MidrandBooks.Payments.Events;
|
||||
|
||||
@@ -9,14 +9,19 @@ public sealed class PayfastPaymentConfirmationReceivedEvent : EventBase, IEvent
|
||||
|
||||
public PayfastWebhookPayload? Payload { get; set; }
|
||||
|
||||
public string? RemoteIpAddress { get; set; }
|
||||
|
||||
public bool PerformBackgroundChecks { get; set; }
|
||||
|
||||
public PayfastPaymentConfirmationReceivedEvent() { }
|
||||
|
||||
private PayfastPaymentConfirmationReceivedEvent(PayfastWebhookPayload? payload, string paymentId)
|
||||
private PayfastPaymentConfirmationReceivedEvent(PayfastWebhookPayload? payload, string paymentId, bool performBackgroundChecks = true)
|
||||
{
|
||||
Payload = payload;
|
||||
CorrelationId = paymentId;
|
||||
PerformBackgroundChecks = performBackgroundChecks;
|
||||
}
|
||||
|
||||
public static PayfastPaymentConfirmationReceivedEvent Create(PayfastWebhookPayload? payload, string paymentId) =>
|
||||
new(payload, paymentId);
|
||||
public static PayfastPaymentConfirmationReceivedEvent Create(PayfastWebhookPayload? payload, string paymentId, bool performBackgroundChecks = true) =>
|
||||
new(payload, paymentId, performBackgroundChecks);
|
||||
}
|
||||
|
||||
@@ -0,0 +1,59 @@
|
||||
namespace LiteCharms.Features.MidrandBooks.Payments.Models;
|
||||
|
||||
public sealed class PayfastWebhookPayload
|
||||
{
|
||||
public string? MerchantId { get; set; }
|
||||
|
||||
public string? MerchantKey { get; set; }
|
||||
|
||||
public string? Signature { get; set; }
|
||||
|
||||
public string? MerchantPaymentId { get; set; }
|
||||
|
||||
public string? PaymentId { get; set; }
|
||||
|
||||
public string? PaymentStatus { get; set; }
|
||||
|
||||
public string? ItemName { get; set; }
|
||||
|
||||
public string? ItemDescription { get; set; }
|
||||
|
||||
public string? AmountGross { get; set; }
|
||||
|
||||
public string? AmountFee { get; set; }
|
||||
|
||||
public string? AmountNet { get; set; }
|
||||
|
||||
public string? NameFirst { get; set; }
|
||||
|
||||
public string? NameLast { get; set; }
|
||||
|
||||
public string? EmailAddress { get; set; }
|
||||
|
||||
public string? CustomStr1 { get; set; }
|
||||
|
||||
public string? CustomInt1 { get; set; }
|
||||
|
||||
public string? Token { get; set; }
|
||||
|
||||
public IDictionary<string, string?> ToParamDictionary() => new Dictionary<string, string?>
|
||||
(StringComparer.Ordinal)
|
||||
{
|
||||
{ "merchant_id", MerchantId },
|
||||
{ "merchant_key", MerchantKey },
|
||||
{ "m_payment_id", MerchantPaymentId },
|
||||
{ "pf_payment_id", PaymentId },
|
||||
{ "payment_status", PaymentStatus },
|
||||
{ "item_name", ItemName },
|
||||
{ "item_description", ItemDescription },
|
||||
{ "amount_gross", AmountGross },
|
||||
{ "amount_fee", AmountFee },
|
||||
{ "amount_net", AmountNet },
|
||||
{ "custom_str1", CustomStr1 },
|
||||
{ "custom_int1", CustomInt1 },
|
||||
{ "name_first", NameFirst },
|
||||
{ "name_last", NameLast },
|
||||
{ "email_address", EmailAddress },
|
||||
{ "token", Token }
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,26 @@
|
||||
namespace LiteCharms.Features.MidrandBooks.Payments.Models;
|
||||
|
||||
public class PaymentGatewayLedger
|
||||
{
|
||||
public long Id { get; set; }
|
||||
|
||||
public DateTime CreatedAt { get; set; }
|
||||
|
||||
public string? CustomerEmail { get; set; }
|
||||
|
||||
public long OrderId { get; set; }
|
||||
|
||||
public long PaymentId { get; set; }
|
||||
|
||||
public string? MerchantPaymentId { get; set; }
|
||||
|
||||
public string? PayfastPaymentId { get; set; }
|
||||
|
||||
public string? PaymentStatus { get; set; }
|
||||
|
||||
public decimal AmountGross { get; set; }
|
||||
|
||||
public decimal AmountFee { get; set; }
|
||||
|
||||
public decimal AmountNet { get; set; }
|
||||
}
|
||||
@@ -14,7 +14,5 @@ public class PaymentLedger
|
||||
|
||||
public long CustomerId { get; set; }
|
||||
|
||||
public string? PaymentGatewayReference { get; set; }
|
||||
|
||||
public long? PaymentGatewayId { get; set; }
|
||||
public string? MerchantPaymentId { get; set; }
|
||||
}
|
||||
|
||||
@@ -1,5 +1,26 @@
|
||||
namespace LiteCharms.Features.MidrandBooks.Payments.Models;
|
||||
|
||||
public sealed record CreateGatewayLedgerEntry
|
||||
{
|
||||
public string? CustomerEmail { get; set; }
|
||||
|
||||
public required long OrderId { get; set; }
|
||||
|
||||
public required long PaymentId { get; set; }
|
||||
|
||||
public string? MerchantPaymentId { get; set; }
|
||||
|
||||
public string? PayfastPaymentId { get; set; }
|
||||
|
||||
public string? PaymentStatus { get; set; }
|
||||
|
||||
public decimal AmountGross { get; set; }
|
||||
|
||||
public decimal AmountFee { get; set; }
|
||||
|
||||
public decimal AmountNet { get; set; }
|
||||
}
|
||||
|
||||
public sealed record UpdateRefund
|
||||
{
|
||||
public long OrderId { get; set; }
|
||||
|
||||
@@ -0,0 +1,171 @@
|
||||
using LiteCharms.Features.Abstractions;
|
||||
using LiteCharms.Features.Hasher;
|
||||
using LiteCharms.Features.MidrandBooks.Payments.Models;
|
||||
using LiteCharms.Features.MidrandBooks.Postgres;
|
||||
|
||||
namespace LiteCharms.Features.MidrandBooks.Payments;
|
||||
|
||||
public sealed partial class PayfastService(IDbContextFactory<MidrandBooksDbContext> contextFactory,
|
||||
ILogger<PayfastService> logger, IHttpClientFactory httpClientFactory, IConfiguration configuration) : IService
|
||||
{
|
||||
[GeneratedRegex(@"%[0-9A-Fa-f]{2}", RegexOptions.None, matchTimeoutMilliseconds: 1000)]
|
||||
public static partial Regex PercentEncodingRegex { get; }
|
||||
|
||||
public readonly string[] ValidHosts = configuration.GetSection("ValidPayfastHosts").Get<string[]>() ?? [];
|
||||
|
||||
public async ValueTask<Result<long>> WriteLedgerEntryAsync(CreateGatewayLedgerEntry request, CancellationToken cancellationToken = default)
|
||||
{
|
||||
try
|
||||
{
|
||||
await using var context = await contextFactory.CreateDbContextAsync(cancellationToken);
|
||||
|
||||
if(!await context.Orders.AnyAsync(o => o.Id == request.OrderId, cancellationToken))
|
||||
return Result.Fail<long>("Referenced order ID does not exist in database.");
|
||||
|
||||
if(!await context.Payments.AnyAsync(p => p.Id == request.PaymentId, cancellationToken))
|
||||
return Result.Fail<long>("Referenced payment ID does not exist in database.");
|
||||
|
||||
var entry = context.GatewayLedger.Add(new Entities.PaymentGatewayLedger
|
||||
{
|
||||
CustomerEmail = request.CustomerEmail,
|
||||
OrderId = request.OrderId,
|
||||
PaymentId = request.PaymentId,
|
||||
MerchantPaymentId = request.MerchantPaymentId,
|
||||
PayfastPaymentId = request.PayfastPaymentId,
|
||||
PaymentStatus = request.PaymentStatus,
|
||||
AmountGross = request.AmountGross,
|
||||
AmountFee = request.AmountFee,
|
||||
AmountNet = request.AmountNet,
|
||||
CreatedAt = DateTime.UtcNow,
|
||||
});
|
||||
|
||||
return await context.SaveChangesAsync(cancellationToken) > 0
|
||||
? Result.Ok(entry.Entity.Id)
|
||||
: Result.Fail<long>("Failed to save Payfast ledger entry to database.");
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
return Result.Fail<long>(new Error("Failed to write Payfast ledger entry to database.").CausedBy(ex));
|
||||
}
|
||||
}
|
||||
|
||||
public async ValueTask<Result<bool>> ValidateReferrerIpAsync(string remoteIpAddress, CancellationToken cancellationToken = default)
|
||||
{
|
||||
if (string.IsNullOrWhiteSpace(remoteIpAddress))
|
||||
return Result.Fail<bool>("Remote IP address is null or whitespace.");
|
||||
|
||||
try
|
||||
{
|
||||
var validIps = new HashSet<IPAddress>();
|
||||
|
||||
foreach (var host in ValidHosts)
|
||||
{
|
||||
try
|
||||
{
|
||||
var addresses = await Dns.GetHostAddressesAsync(host, cancellationToken);
|
||||
|
||||
foreach (var addr in addresses) validIps.Add(addr);
|
||||
}
|
||||
catch (SocketException ex)
|
||||
{
|
||||
logger.LogWarning(ex, "DNS warning: Failed to resolve Payfast node '{Host}'. It may be decommissioned or unreachable.", host);
|
||||
}
|
||||
}
|
||||
|
||||
if (IPAddress.TryParse(remoteIpAddress, out var incomingIp))
|
||||
{
|
||||
bool isValid = validIps.Contains(incomingIp);
|
||||
|
||||
if (!isValid)
|
||||
logger.LogWarning("SECURITY ALERT: Webhook IP '{RemoteIp}' originated from an unlisted host schema.", remoteIpAddress);
|
||||
|
||||
return Result.Ok(isValid);
|
||||
}
|
||||
|
||||
return Result.Fail<bool>("Invalid remote IP address format.");
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
return Result.Fail<bool>(new Error("DNS Verification error while scanning Payfast IP nodes.").CausedBy(ex));
|
||||
}
|
||||
}
|
||||
|
||||
public Result<bool> ValidatePaymentAmount(decimal expectedTotal, string? amountGrossString)
|
||||
{
|
||||
if (!decimal.TryParse(amountGrossString, CultureInfo.InvariantCulture, out decimal grossAmount))
|
||||
return Result.Fail<bool>("Failed to parse payment amount.");
|
||||
|
||||
decimal delta = Math.Abs(expectedTotal - grossAmount);
|
||||
|
||||
bool isAmountValid = delta <= 0.01m;
|
||||
|
||||
if (!isAmountValid)
|
||||
logger.LogError("FINANCIAL DRIFT EXCEPTION: Expected order total R{Expected} but gateway cleared R{Cleared}.", expectedTotal, grossAmount);
|
||||
|
||||
return Result.Ok(isAmountValid);
|
||||
}
|
||||
|
||||
public async ValueTask<Result<bool>> ValidateServerConfirmationAsync(string rawQueryParamString, bool isSandbox, CancellationToken ct)
|
||||
{
|
||||
try
|
||||
{
|
||||
string host = isSandbox ? "sandbox.payfast.co.za" : "www.payfast.co.za";
|
||||
string targetUrl = $"https://{host}/eng/query/validate";
|
||||
|
||||
using var content = new StringContent(rawQueryParamString, Encoding.UTF8, "application/x-www-form-urlencoded");
|
||||
|
||||
var httpClient = httpClientFactory.CreateClient();
|
||||
|
||||
var response = await httpClient.PostAsync(targetUrl, content, ct);
|
||||
|
||||
if (!response.IsSuccessStatusCode) return Result.Fail<bool>("Failed to validate server confirmation.");
|
||||
|
||||
string responseText = await response.Content.ReadAsStringAsync(ct);
|
||||
|
||||
bool isValidated = string.Equals(responseText.Trim(), "VALID", StringComparison.OrdinalIgnoreCase);
|
||||
|
||||
if (!isValidated)
|
||||
logger.LogWarning("SECURITY WARNING: Payfast back-channel returned validation response: '{Response}'", responseText);
|
||||
|
||||
return Result.Ok(isValidated);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
return Result.Fail<bool>(new Error("Failed to complete back-channel cURL verification handshakes with Payfast remote endpoints.").CausedBy(ex));
|
||||
}
|
||||
}
|
||||
|
||||
public static Result<string> GenerateSignature(IDictionary<string, string?> data, string? passPhrase = null)
|
||||
{
|
||||
var pfOutput = new StringBuilder();
|
||||
|
||||
foreach (var kvp in data)
|
||||
{
|
||||
if (string.IsNullOrEmpty(kvp.Value))
|
||||
continue;
|
||||
|
||||
string key = kvp.Key;
|
||||
|
||||
string encodedVal = HttpUtility.UrlEncode(kvp.Value.Trim());
|
||||
|
||||
string val = PercentEncodingRegex.Replace(encodedVal, m => m.Value.ToLowerInvariant());
|
||||
|
||||
pfOutput.Append($"{key}={val}&");
|
||||
}
|
||||
|
||||
string getString = pfOutput.Length > 0
|
||||
? pfOutput.ToString()[..^1]
|
||||
: string.Empty;
|
||||
|
||||
if (!string.IsNullOrWhiteSpace(passPhrase))
|
||||
{
|
||||
string encodedPassphrase = HttpUtility.UrlEncode(passPhrase.Trim());
|
||||
|
||||
string safePassphrase = PercentEncodingRegex.Replace(encodedPassphrase, m => m.Value.ToLowerInvariant());
|
||||
|
||||
getString += $"&passphrase={safePassphrase}";
|
||||
}
|
||||
|
||||
return HashService.ToMd5Hash(getString);
|
||||
}
|
||||
}
|
||||
@@ -116,7 +116,7 @@ public sealed class PaymentService(IDbContextFactory<MidrandBooksDbContext> cont
|
||||
}
|
||||
}
|
||||
|
||||
public async ValueTask<Result<bool>> HasLedgerEntryAsync(long orderId, long paymentId, long gatewayId, CancellationToken cancellationToken = default)
|
||||
public async ValueTask<Result<bool>> HasLedgerEntryAsync(long orderId, long paymentId, CancellationToken cancellationToken = default)
|
||||
{
|
||||
try
|
||||
{
|
||||
@@ -124,8 +124,7 @@ public sealed class PaymentService(IDbContextFactory<MidrandBooksDbContext> cont
|
||||
|
||||
var exists = await context.Ledger.AnyAsync(l =>
|
||||
l.OrderId == orderId &&
|
||||
l.PaymentId == paymentId &&
|
||||
l.PaymentGatewayId == gatewayId, cancellationToken);
|
||||
l.PaymentId == paymentId, cancellationToken);
|
||||
|
||||
return Result.Ok(exists);
|
||||
}
|
||||
@@ -162,8 +161,6 @@ public sealed class PaymentService(IDbContextFactory<MidrandBooksDbContext> cont
|
||||
CreatedAt = DateTime.UtcNow,
|
||||
CustomerId = request.CustomerId,
|
||||
OrderId = request.OrderId,
|
||||
PaymentGatewayId = request.PaymentGatewayId,
|
||||
PaymentGatewayReference = request.PaymentGatewayReference,
|
||||
PaymentId = request.PaymentId,
|
||||
Status = request.Status,
|
||||
});
|
||||
|
||||
Reference in New Issue
Block a user