Compare commits
54
Commits
5ab2d29aac
..
1.59.0
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
adc14038db | ||
|
|
61cb6c2228 | ||
|
|
e7a798b5e9 | ||
|
|
41b6b71b31 | ||
|
|
ee6beef603 | ||
|
|
1c3f3eaf0d | ||
|
|
2e77666d9e | ||
|
|
1977b6b301 | ||
|
|
0ab14d8b63 | ||
|
|
466458e230 | ||
|
|
141d32f591 | ||
|
|
d9e7f225ae | ||
|
|
6ae63e2ad1 | ||
|
|
f5efdde37c | ||
|
|
1592d5dc8f | ||
|
|
50a8a59d92 | ||
|
|
b70d9559b0 | ||
|
|
81d5e8f07c | ||
|
|
20a53942b5 | ||
|
|
9edb2aa4aa | ||
|
|
6ed023f2cf | ||
|
|
2c9f5a846c | ||
|
|
41f7c05be3 | ||
|
|
1a03355e84 | ||
|
|
7743c3178e | ||
|
|
ab3d8e6e9a | ||
|
|
db4c348288 | ||
|
|
6683234642 | ||
|
|
6ddbb9479a | ||
|
|
6c7349a0f8 | ||
|
|
e97fd6cd3f | ||
|
|
184c7c252a | ||
|
|
bfe8c458d6 | ||
|
|
e6e0475db1 | ||
|
|
5090c60797 | ||
|
|
9432252e15 | ||
|
|
47111a1a3a | ||
|
|
6eb3d50375 | ||
|
|
4deb732804 | ||
|
|
20d9387d0b | ||
|
|
9f6d0ccaa0 | ||
|
|
1acbc4d213 | ||
|
|
8c99668fac | ||
|
|
ad44f46204 | ||
|
|
49d999c1e3 | ||
|
|
9ed4777a18 | ||
|
|
0cf44f68cc | ||
|
|
41ed5a4288 | ||
|
|
bbcba5e06c | ||
|
|
502cc326dd | ||
|
|
4675d4c5fc | ||
|
|
f80bb2fff9 | ||
|
|
6767906b0d | ||
|
|
a344af4498 |
-86
@@ -1,86 +0,0 @@
|
||||
using LiteCharms.Features.Hasher;
|
||||
using LiteCharms.Features.MidrandBooks.Orders;
|
||||
|
||||
namespace LiteCharms.Features.MidrandBooks.Payments.Events.Handlers;
|
||||
|
||||
public sealed class PayfastPaymentConfirmationReceivedEventHandler(IServiceProvider services, ILogger<PayfastPaymentConfirmationReceivedEvent> logger) :
|
||||
INotificationHandler<PayfastPaymentConfirmationReceivedEvent>
|
||||
{
|
||||
public async ValueTask Handle(PayfastPaymentConfirmationReceivedEvent notification, CancellationToken cancellationToken)
|
||||
{
|
||||
await using var scope = services.CreateAsyncScope();
|
||||
|
||||
PaymentService paymentService = scope.ServiceProvider.GetRequiredService<PaymentService>();
|
||||
OrderService orderService = scope.ServiceProvider.GetRequiredService<OrderService>();
|
||||
HashService hashService = scope.ServiceProvider.GetRequiredService<HashService>();
|
||||
|
||||
var hashResult = hashService.DecodeLongIdHash(notification.Payload?.MPaymentId!);
|
||||
if (hashResult.IsFailed)
|
||||
{
|
||||
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}.");
|
||||
}
|
||||
|
||||
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
|
||||
{
|
||||
CustomerId = orderResult.Value.CustomerId,
|
||||
OrderId = orderResult.Value.Id,
|
||||
PaymentId = paymentResult.Value.Id,
|
||||
Status = LedgerStatuses.Received,
|
||||
PaymentGatewayId = 1,
|
||||
PaymentGatewayReference = notification.CorrelationId,
|
||||
}, cancellationToken);
|
||||
|
||||
if (ledgerResult.IsFailed)
|
||||
{
|
||||
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 paymentCompletedResult = await paymentService.CompletePaymentAsync(paymentResult.Value.Id, PaymentStatuses.Paid, cancellationToken);
|
||||
if (paymentCompletedResult.IsFailed)
|
||||
{
|
||||
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}.");
|
||||
}
|
||||
|
||||
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)
|
||||
}
|
||||
}
|
||||
-22
@@ -1,22 +0,0 @@
|
||||
using LiteCharms.Features.Abstractions;
|
||||
using LiteCharms.Features.Models;
|
||||
|
||||
namespace LiteCharms.Features.MidrandBooks.Payments.Events;
|
||||
|
||||
public sealed class PayfastPaymentConfirmationReceivedEvent : EventBase, IEvent
|
||||
{
|
||||
public string Name { get; set; } = nameof(PayfastPaymentConfirmationReceivedEvent);
|
||||
|
||||
public PayfastWebhookPayload? Payload { get; set; }
|
||||
|
||||
public PayfastPaymentConfirmationReceivedEvent() { }
|
||||
|
||||
private PayfastPaymentConfirmationReceivedEvent(PayfastWebhookPayload? payload, string paymentId)
|
||||
{
|
||||
Payload = payload;
|
||||
CorrelationId = paymentId;
|
||||
}
|
||||
|
||||
public static PayfastPaymentConfirmationReceivedEvent Create(PayfastWebhookPayload? payload, string paymentId) =>
|
||||
new(payload, paymentId);
|
||||
}
|
||||
@@ -7,27 +7,6 @@ namespace LiteCharms.Features.MidrandBooks.Payments;
|
||||
|
||||
public sealed class PaymentService(IDbContextFactory<MidrandBooksDbContext> contextFactory) : IService
|
||||
{
|
||||
public async ValueTask<Result<Payment>> GetOrderPaymentAsync(long orderId, CancellationToken cancellationToken = default)
|
||||
{
|
||||
try
|
||||
{
|
||||
await using var context = await contextFactory.CreateDbContextAsync(cancellationToken);
|
||||
|
||||
var payment = await context.Payments.AsNoTracking()
|
||||
.Where(p => p.OrderId == orderId)
|
||||
.OrderByDescending(p => p.Id)
|
||||
.FirstOrDefaultAsync(cancellationToken);
|
||||
|
||||
return payment is not null
|
||||
? Result.Ok(payment.ToModel())
|
||||
: Result.Fail<Payment>("Could not find payment for the order");
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
return Result.Fail<Payment>(new Error(ex.Message).CausedBy(ex));
|
||||
}
|
||||
}
|
||||
|
||||
public async ValueTask<Result<Refund>> GetRefundAsync(long refundId, CancellationToken cancellationToken = default)
|
||||
{
|
||||
try
|
||||
@@ -116,25 +95,6 @@ public sealed class PaymentService(IDbContextFactory<MidrandBooksDbContext> cont
|
||||
}
|
||||
}
|
||||
|
||||
public async ValueTask<Result<bool>> HasLedgerEntryAsync(long orderId, long paymentId, long gatewayId, CancellationToken cancellationToken = default)
|
||||
{
|
||||
try
|
||||
{
|
||||
await using var context = await contextFactory.CreateDbContextAsync(cancellationToken);
|
||||
|
||||
var exists = await context.Ledger.AnyAsync(l =>
|
||||
l.OrderId == orderId &&
|
||||
l.PaymentId == paymentId &&
|
||||
l.PaymentGatewayId == gatewayId, cancellationToken);
|
||||
|
||||
return Result.Ok(exists);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
return Result.Fail(new Error(ex.Message).CausedBy(ex));
|
||||
}
|
||||
}
|
||||
|
||||
public async ValueTask<Result> WriteLedgerEntryAsync(CreateLedgerEntry request, CancellationToken cancellationToken = default)
|
||||
{
|
||||
try
|
||||
|
||||
@@ -1,6 +1,4 @@
|
||||
using LiteCharms.Features.Hasher;
|
||||
using LiteCharms.Features.Models;
|
||||
using static LiteCharms.Features.Extensions.Hash;
|
||||
|
||||
namespace LiteCharms.Features.Tests;
|
||||
|
||||
@@ -67,18 +65,17 @@ public class HashServiceFeatureTests(Fixture fixture) : IClassFixture<Fixture>
|
||||
{
|
||||
var paymentId = hashService.HashEncodeLongId(1001).Value;
|
||||
|
||||
var payload = new PayfastWebhookPayload
|
||||
var incomingForm = new Dictionary<string, string>
|
||||
{
|
||||
Amount = "350.00",
|
||||
ItemName = "System Architecture Book",
|
||||
MPaymentId = paymentId,
|
||||
{ "m_payment_id", paymentId },
|
||||
{ "amount", "350.00" },
|
||||
{ "item_name", "System Architecture Book" }
|
||||
};
|
||||
|
||||
var rawPayload = payload.ToRawPayfastPayload(payfastPassphrase);
|
||||
|
||||
var rawPayload = $"amount=350.00&item_name=System+Architecture+Book&m_payment_id={paymentId}&passphrase={payfastPassphrase}";
|
||||
var generatedSignature = HashService.ToMd5Hash(rawPayload).Value;
|
||||
|
||||
var result = hashService.VerifyPayfastWebhookSignature(payload, generatedSignature);
|
||||
var result = hashService.VerifyPayfastWebhookSignature(incomingForm, generatedSignature);
|
||||
|
||||
Assert.True(result.IsSuccess);
|
||||
Assert.True(result.Value);
|
||||
|
||||
@@ -1,6 +1,5 @@
|
||||
using LiteCharms.Features.Hasher;
|
||||
using LiteCharms.Features.Hasher.Configuration;
|
||||
using LiteCharms.Features.Models;
|
||||
|
||||
namespace LiteCharms.Features.Extensions;
|
||||
|
||||
@@ -21,82 +20,4 @@ public static class Hash
|
||||
|
||||
return services;
|
||||
}
|
||||
|
||||
public static string ToRawPayfastPayload(this PayfastWebhookPayload input, string passphrase)
|
||||
{
|
||||
var parameters = new List<string>();
|
||||
|
||||
if (!string.IsNullOrWhiteSpace(input.Amount))
|
||||
parameters.Add($"amount={WebUtility.UrlEncode(input.Amount)}");
|
||||
|
||||
if (!string.IsNullOrWhiteSpace(input.ItemName))
|
||||
parameters.Add($"item_name={WebUtility.UrlEncode(input.ItemName)}");
|
||||
|
||||
if (!string.IsNullOrWhiteSpace(input.MPaymentId))
|
||||
parameters.Add($"m_payment_id={WebUtility.UrlEncode(input.MPaymentId)}");
|
||||
|
||||
string payload = string.Join("&", parameters);
|
||||
|
||||
if (!string.IsNullOrWhiteSpace(passphrase))
|
||||
payload += $"&passphrase={WebUtility.UrlEncode(passphrase)}";
|
||||
|
||||
return payload;
|
||||
}
|
||||
|
||||
public static (PayfastWebhookPayload Payload, string Passphrase) FromRawPayfastPayload(this string rawPayload)
|
||||
{
|
||||
string passphrase = string.Empty;
|
||||
var payload = new PayfastWebhookPayload();
|
||||
|
||||
if (string.IsNullOrWhiteSpace(rawPayload)) return (payload, passphrase);
|
||||
|
||||
var segments = rawPayload.Split('&', StringSplitOptions.RemoveEmptyEntries);
|
||||
|
||||
foreach (var segment in segments)
|
||||
{
|
||||
int delimiterIndex = segment.IndexOf('=');
|
||||
if (delimiterIndex == -1)
|
||||
continue;
|
||||
|
||||
string key = segment[..delimiterIndex].Trim();
|
||||
string rawValue = segment[(delimiterIndex + 1)..];
|
||||
|
||||
string decodedValue = WebUtility.UrlDecode(rawValue);
|
||||
|
||||
switch (key.ToLowerInvariant())
|
||||
{
|
||||
case "amount":
|
||||
payload.Amount = decodedValue;
|
||||
break;
|
||||
case "item_name":
|
||||
payload.ItemName = decodedValue;
|
||||
break;
|
||||
case "m_payment_id":
|
||||
payload.MPaymentId = decodedValue;
|
||||
break;
|
||||
case "passphrase":
|
||||
passphrase = decodedValue;
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
return (payload, passphrase);
|
||||
}
|
||||
|
||||
public static (PayfastWebhookPayload Payload, string Passphrase) FromRawPayfastPayload(this IFormCollection form)
|
||||
{
|
||||
string passphrase = string.Empty;
|
||||
var payload = new PayfastWebhookPayload();
|
||||
|
||||
if (form.IsNullOrEmpty()) return (payload, passphrase);
|
||||
|
||||
payload = new PayfastWebhookPayload
|
||||
{
|
||||
Amount = form.TryGetValue("amount", out var amountValues) ? amountValues.ToString() : null,
|
||||
ItemName = form.TryGetValue("item_name", out var itemValues) ? itemValues.ToString() : null,
|
||||
MPaymentId = form.TryGetValue("m_payment_id", out var paymentIdValues) ? paymentIdValues.ToString() : null,
|
||||
};
|
||||
|
||||
return (payload, passphrase);
|
||||
}
|
||||
}
|
||||
@@ -1,6 +1,5 @@
|
||||
using LiteCharms.Features.Abstractions;
|
||||
using LiteCharms.Features.Hasher.Configuration;
|
||||
using LiteCharms.Features.Models;
|
||||
|
||||
namespace LiteCharms.Features.Hasher;
|
||||
|
||||
@@ -41,30 +40,24 @@ public sealed partial class HashService(IHashids hasher, IOptions<HasherSettings
|
||||
return Result.Ok(Convert.ToHexString(bytes).ToLowerInvariant());
|
||||
}
|
||||
|
||||
public Result<bool> VerifyPayfastWebhookSignature(PayfastWebhookPayload payload, string incomingSignature)
|
||||
public Result<bool> VerifyPayfastWebhookSignature(IDictionary<string, string> incomingFormData, string incomingSignature)
|
||||
{
|
||||
try
|
||||
{
|
||||
if (string.IsNullOrWhiteSpace(incomingSignature))
|
||||
return Result.Fail<bool>("Validation failed: Missing signature string parameter.");
|
||||
|
||||
var parameters = new List<string>();
|
||||
var sortedFields = incomingFormData
|
||||
.Where(field => !string.Equals(field.Key, "signature", StringComparison.OrdinalIgnoreCase))
|
||||
.OrderBy(field => field.Key, StringComparer.Ordinal)
|
||||
.Select(field => $"{field.Key}={WebUtility.UrlEncode(field.Value)}");
|
||||
|
||||
if (!string.IsNullOrWhiteSpace(payload.Amount))
|
||||
parameters.Add($"amount={WebUtility.UrlEncode(payload.Amount)}");
|
||||
|
||||
if (!string.IsNullOrWhiteSpace(payload.ItemName))
|
||||
parameters.Add($"item_name={WebUtility.UrlEncode(payload.ItemName)}");
|
||||
|
||||
if (!string.IsNullOrWhiteSpace(payload.MPaymentId))
|
||||
parameters.Add($"m_payment_id={WebUtility.UrlEncode(payload.MPaymentId)}");
|
||||
|
||||
string signatureString = string.Join("&", parameters);
|
||||
string payload = string.Join("&", sortedFields);
|
||||
|
||||
if (!string.IsNullOrWhiteSpace(settings.PayfastPassphrase))
|
||||
signatureString += $"&passphrase={WebUtility.UrlEncode(settings.PayfastPassphrase)}";
|
||||
payload += $"&passphrase={WebUtility.UrlEncode(settings.PayfastPassphrase)}";
|
||||
|
||||
var localHashResult = ToMd5Hash(signatureString);
|
||||
var localHashResult = ToMd5Hash(payload);
|
||||
|
||||
if (!localHashResult.IsSuccess)
|
||||
return Result.Fail<bool>(localHashResult.Errors);
|
||||
@@ -75,7 +68,7 @@ public sealed partial class HashService(IHashids hasher, IOptions<HasherSettings
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
return Result.Fail<bool>(new Error("An error occurred during Payfast MD5 verification.").CausedBy(ex));
|
||||
return Result.Fail<bool>(new Error("An error occurred during MD5 verification loop.").CausedBy(ex));
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -147,8 +147,6 @@
|
||||
|
||||
<!-- Shared Usings -->
|
||||
<ItemGroup>
|
||||
<Using Include="Microsoft.IdentityModel.Tokens" />
|
||||
<Using Include="Microsoft.AspNetCore.Http" />
|
||||
<Using Include="HashidsNet" />
|
||||
<Using Include="System.Net" />
|
||||
<Using Include="System.Text.RegularExpressions" />
|
||||
|
||||
@@ -1,8 +0,0 @@
|
||||
namespace LiteCharms.Features.Models;
|
||||
|
||||
public sealed class PayfastWebhookPayload
|
||||
{
|
||||
public string? Amount { get; set; }
|
||||
public string? ItemName { get; set; }
|
||||
public string? MPaymentId { get; set; }
|
||||
}
|
||||
@@ -23,7 +23,7 @@ public sealed class JobOrchestrator(ISchedulerFactory schedulerFactory) : IJobOr
|
||||
|
||||
var trigger = global::Quartz.TriggerBuilder.Create()
|
||||
.WithIdentity(triggerKey)
|
||||
.StartNow()
|
||||
.StartNow()
|
||||
.Build();
|
||||
|
||||
await scheduler.ScheduleJob(job, new List<ITrigger> { trigger }.AsReadOnly(), replace: true, cancellationToken);
|
||||
|
||||
Reference in New Issue
Block a user