55 lines
2.6 KiB
C#
55 lines
2.6 KiB
C#
using LiteCharms.Features.Hasher;
|
|
using LiteCharms.Features.MidrandBooks.Payments.Events;
|
|
using LiteCharms.Features.Models;
|
|
using LiteCharms.Features.Quartz.Abstractions;
|
|
|
|
namespace MidrandBooksApi.Payments.Endpoints;
|
|
|
|
[ApiVersionTarget(1)]
|
|
public sealed class ConfirmationEndpoint : IEndpoint
|
|
{
|
|
private static readonly ActivitySource PaymentActivitySource = new("MidrandBooksApi.Payments");
|
|
|
|
public void Map(IEndpointRouteBuilder builder)
|
|
{
|
|
builder.MapPost("payments/payfast/confirm", async (HttpRequest request, HashService hashService,
|
|
IJobOrchestrator jobOrchestrator, CancellationToken cancellationToken) =>
|
|
{
|
|
using Activity? activity = PaymentActivitySource.StartActivity("ReceivePayfastWebhook", ActivityKind.Server);
|
|
activity?.SetTag("messaging.system", "payfast");
|
|
activity?.SetTag("messaging.destination.name", "payments/confirm");
|
|
|
|
var formCollection = await request.ReadFormAsync(cancellationToken);
|
|
|
|
if (!formCollection.TryGetValue("signature", out var signatureValues) || string.IsNullOrWhiteSpace(signatureValues.ToString()))
|
|
return Results.BadRequest("Missing Payfast validation signature.");
|
|
|
|
string incomingSignature = signatureValues.ToString();
|
|
|
|
var payload = new PayfastWebhookPayload
|
|
{
|
|
Amount = formCollection.TryGetValue("amount", out var amountValues) ? amountValues.ToString() : null,
|
|
ItemName = formCollection.TryGetValue("item_name", out var itemValues) ? itemValues.ToString() : null,
|
|
MPaymentId = formCollection.TryGetValue("m_payment_id", out var paymentIdValues) ? paymentIdValues.ToString() : null
|
|
};
|
|
|
|
var validationResult = hashService.VerifyPayfastWebhookSignature(payload, incomingSignature);
|
|
|
|
if (validationResult.IsFailed || !validationResult.Value) return Results.Unauthorized();
|
|
|
|
await jobOrchestrator.SendAsync(PayfastPaymentConfirmationReceivedEvent.Create(payload, payload.MPaymentId!), cancellationToken);
|
|
|
|
activity?.SetStatus(ActivityStatusCode.Ok);
|
|
|
|
return Results.Ok();
|
|
})
|
|
.WithDescription("Securely confirm and process an incoming Payfast merchant payment callback.")
|
|
.WithName(typeof(ConfirmationEndpoint).ToEndpointName())
|
|
.MapToApiVersion(new ApiVersion(1))
|
|
.Produces(StatusCodes.Status200OK)
|
|
.Produces(StatusCodes.Status400BadRequest)
|
|
.Produces(StatusCodes.Status401Unauthorized)
|
|
.WithTags(EndpointTags.Payments);
|
|
}
|
|
}
|