Compare commits
5
Commits
d0ec655085
..
1.6
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
db0715ceca | ||
|
|
851ca72b46 | ||
|
|
b731ebdcea | ||
|
|
f3e71aa604 | ||
|
|
e07cd0e0fd |
@@ -0,0 +1,7 @@
|
|||||||
|
namespace MidrandBooksApi;
|
||||||
|
|
||||||
|
[AttributeUsage(AttributeTargets.Class, AllowMultiple = true)]
|
||||||
|
public sealed class ApiVersionTargetAttribute(int majorVersion) : Attribute
|
||||||
|
{
|
||||||
|
public int MajorVersion { get; } = majorVersion;
|
||||||
|
}
|
||||||
@@ -0,0 +1,7 @@
|
|||||||
|
namespace MidrandBooksApi;
|
||||||
|
|
||||||
|
public static class EndpointTags
|
||||||
|
{
|
||||||
|
public const string Books = nameof(Books);
|
||||||
|
public const string Payments = nameof(Payments);
|
||||||
|
}
|
||||||
@@ -0,0 +1,6 @@
|
|||||||
|
namespace MidrandBooksApi;
|
||||||
|
|
||||||
|
public interface IEndpoint
|
||||||
|
{
|
||||||
|
void Map(IEndpointRouteBuilder builder);
|
||||||
|
}
|
||||||
@@ -34,7 +34,6 @@
|
|||||||
<PackageReference Include="Asp.Versioning.Mvc.ApiExplorer" Version="10.0.0" />
|
<PackageReference Include="Asp.Versioning.Mvc.ApiExplorer" Version="10.0.0" />
|
||||||
|
|
||||||
<Using Include="Asp.Versioning" />
|
<Using Include="Asp.Versioning" />
|
||||||
<Using Include="Asp.Versioning.Builder" />
|
|
||||||
</ItemGroup>
|
</ItemGroup>
|
||||||
|
|
||||||
<!-- API Documentation -->
|
<!-- API Documentation -->
|
||||||
@@ -54,13 +53,13 @@
|
|||||||
</ItemGroup>
|
</ItemGroup>
|
||||||
|
|
||||||
<ItemGroup>
|
<ItemGroup>
|
||||||
<PackageReference Include="LiteCharms.Features" Version="1.72.0" />
|
<PackageReference Include="LiteCharms.Features" Version="1.64.0" />
|
||||||
</ItemGroup>
|
</ItemGroup>
|
||||||
|
|
||||||
<!-- UI -->
|
<!-- UI -->
|
||||||
<ItemGroup>
|
<ItemGroup>
|
||||||
<PackageReference Include="ANM.Blazored.Toast" Version="0.1.1" />
|
<PackageReference Include="ANM.Blazored.Toast" Version="0.1.1" />
|
||||||
<PackageReference Include="LiteCharms.Features.MidrandBooks" Version="1.72.0" />
|
<PackageReference Include="LiteCharms.Features.MidrandBooks" Version="1.64.0" />
|
||||||
|
|
||||||
<!-- Global Usings -->
|
<!-- Global Usings -->
|
||||||
<Using Include="Blazored.Toast.Services" />
|
<Using Include="Blazored.Toast.Services" />
|
||||||
@@ -86,7 +85,6 @@
|
|||||||
|
|
||||||
<!-- Shared Global Usings -->
|
<!-- Shared Global Usings -->
|
||||||
<ItemGroup>
|
<ItemGroup>
|
||||||
<Using Include="System.Web" />
|
|
||||||
<Using Include="System.Diagnostics" />
|
<Using Include="System.Diagnostics" />
|
||||||
<Using Include="System.Reflection" />
|
<Using Include="System.Reflection" />
|
||||||
<Using Include="Microsoft.Extensions.DependencyInjection.Extensions" />
|
<Using Include="Microsoft.Extensions.DependencyInjection.Extensions" />
|
||||||
|
|||||||
@@ -0,0 +1,16 @@
|
|||||||
|
namespace MidrandBooksApi;
|
||||||
|
|
||||||
|
public sealed class OpenApiBearerSecuritySchemeTransformer : IOpenApiDocumentTransformer
|
||||||
|
{
|
||||||
|
public async Task TransformAsync(OpenApiDocument document, OpenApiDocumentTransformerContext context, CancellationToken cancellationToken)
|
||||||
|
{
|
||||||
|
var bearerScheme = new OpenApiSecurityScheme
|
||||||
|
{
|
||||||
|
Type = SecuritySchemeType.Http,
|
||||||
|
Scheme = "bearer",
|
||||||
|
Description = "JWT Authorization header using the Bearer scheme. Example: \"Bearer {token}\""
|
||||||
|
};
|
||||||
|
|
||||||
|
document.AddComponent("Bearer", bearerScheme);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -1,10 +1,7 @@
|
|||||||
using LiteCharms.Features.Abstractions;
|
using LiteCharms.Features.Hasher;
|
||||||
using LiteCharms.Features.Api;
|
|
||||||
using LiteCharms.Features.Extensions;
|
|
||||||
using LiteCharms.Features.MidrandBooks.Payments;
|
|
||||||
using LiteCharms.Features.MidrandBooks.Payments.Events;
|
using LiteCharms.Features.MidrandBooks.Payments.Events;
|
||||||
using LiteCharms.Features.MidrandBooks.Payments.Models;
|
using LiteCharms.Features.Models;
|
||||||
using static LiteCharms.Features.Extensions.Api;
|
using LiteCharms.Features.Quartz.Abstractions;
|
||||||
|
|
||||||
namespace MidrandBooksApi.Payments.Endpoints;
|
namespace MidrandBooksApi.Payments.Endpoints;
|
||||||
|
|
||||||
@@ -15,51 +12,32 @@ public sealed class ConfirmationEndpoint : IEndpoint
|
|||||||
|
|
||||||
public void Map(IEndpointRouteBuilder builder)
|
public void Map(IEndpointRouteBuilder builder)
|
||||||
{
|
{
|
||||||
builder.MapPost("payments/payfast/confirm", async (HttpRequest request, PayfastService payfastService,
|
builder.MapPost("payments/payfast/confirm", async (HttpRequest request, HashService hashService,
|
||||||
IJobOrchestrator jobOrchestrator, IConfiguration configuration, IHostEnvironment hostEnvironment, CancellationToken cancellationToken) =>
|
IJobOrchestrator jobOrchestrator, CancellationToken cancellationToken) =>
|
||||||
{
|
{
|
||||||
using Activity? activity = PaymentActivitySource.StartActivity("ReceivePayfastWebhook", ActivityKind.Server);
|
using Activity? activity = PaymentActivitySource.StartActivity("ReceivePayfastWebhook", ActivityKind.Server);
|
||||||
|
|
||||||
activity?.SetTag("messaging.system", "payfast");
|
activity?.SetTag("messaging.system", "payfast");
|
||||||
activity?.SetTag("messaging.destination.name", "payments/confirm");
|
activity?.SetTag("messaging.destination.name", "payments/confirm");
|
||||||
|
|
||||||
string? remoteIp = request.HttpContext.Connection.RemoteIpAddress?.ToString();
|
|
||||||
|
|
||||||
var ipValidation = await payfastService.ValidateReferrerIpAsync(remoteIp!, !hostEnvironment.IsProduction(), cancellationToken);
|
|
||||||
|
|
||||||
if (ipValidation.IsFailed || !ipValidation.Value) return Results.Unauthorized();
|
|
||||||
|
|
||||||
var formCollection = await request.ReadFormAsync(cancellationToken);
|
var formCollection = await request.ReadFormAsync(cancellationToken);
|
||||||
|
|
||||||
if (!formCollection.TryGetValue("signature", out var signatureValues) || string.IsNullOrWhiteSpace(signatureValues.ToString()))
|
if (!formCollection.TryGetValue("signature", out var signatureValues) || string.IsNullOrWhiteSpace(signatureValues.ToString()))
|
||||||
return Results.BadRequest("Missing Payfast validation signature.");
|
return Results.BadRequest("Missing Payfast validation signature.");
|
||||||
|
|
||||||
string incomingSignature = signatureValues.ToString().Trim();
|
string incomingSignature = signatureValues.ToString();
|
||||||
var payload = ParseForm(formCollection, incomingSignature);
|
|
||||||
|
|
||||||
var paramDictionary = payload.ToParamDictionary();
|
var payload = new PayfastWebhookPayload
|
||||||
string? passphrase = configuration["HasherSettings:PayfastPassphrase"];
|
{
|
||||||
|
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 signatureCheck = PayfastService.GenerateSignature(paramDictionary, passphrase);
|
var validationResult = hashService.VerifyPayfastWebhookSignature(payload, incomingSignature);
|
||||||
|
|
||||||
if (signatureCheck.IsFailed || !string.Equals(signatureCheck.Value, incomingSignature, StringComparison.OrdinalIgnoreCase))
|
if (validationResult.IsFailed || !validationResult.Value) return Results.Unauthorized();
|
||||||
return Results.Unauthorized();
|
|
||||||
|
|
||||||
var formPairs = formCollection.Select(kvp => $"{kvp.Key}={HttpUtility.UrlEncode(kvp.Value.ToString())}");
|
await jobOrchestrator.SendAsync(PayfastPaymentConfirmationReceivedEvent.Create(payload, payload.MPaymentId!), cancellationToken);
|
||||||
|
|
||||||
string rawQueryParamString = string.Join("&", formPairs);
|
|
||||||
|
|
||||||
bool isSandbox = !hostEnvironment.IsProduction();
|
|
||||||
|
|
||||||
var serverConfirmation = await payfastService.ValidateServerConfirmationAsync(rawQueryParamString, isSandbox, cancellationToken);
|
|
||||||
|
|
||||||
if (serverConfirmation.IsFailed || !serverConfirmation.Value)
|
|
||||||
return Results.Unauthorized();
|
|
||||||
|
|
||||||
var notification = PayfastPaymentConfirmationReceivedEvent.Create(payload, payload.MerchantPaymentId!,
|
|
||||||
allowLoopback: !hostEnvironment.IsProduction(), performBackgroundChecks: false); // Set to false because comprehensive checks are completed inline above
|
|
||||||
|
|
||||||
await jobOrchestrator.SendAsync(notification, cancellationToken);
|
|
||||||
|
|
||||||
activity?.SetStatus(ActivityStatusCode.Ok);
|
activity?.SetStatus(ActivityStatusCode.Ok);
|
||||||
|
|
||||||
@@ -71,27 +49,6 @@ public sealed class ConfirmationEndpoint : IEndpoint
|
|||||||
.Produces(StatusCodes.Status200OK)
|
.Produces(StatusCodes.Status200OK)
|
||||||
.Produces(StatusCodes.Status400BadRequest)
|
.Produces(StatusCodes.Status400BadRequest)
|
||||||
.Produces(StatusCodes.Status401Unauthorized)
|
.Produces(StatusCodes.Status401Unauthorized)
|
||||||
.WithTags(Api.Payments);
|
.WithTags(EndpointTags.Payments);
|
||||||
}
|
}
|
||||||
|
}
|
||||||
private static PayfastWebhookPayload ParseForm(IFormCollection formCollection, string incomingSignature) => new()
|
|
||||||
{
|
|
||||||
MerchantId = formCollection.TryGetValue("merchant_id", out var mId) ? mId.ToString() : null,
|
|
||||||
MerchantKey = formCollection.TryGetValue("merchant_key", out var mKey) ? mKey.ToString() : null,
|
|
||||||
Signature = incomingSignature,
|
|
||||||
MerchantPaymentId = formCollection.TryGetValue("m_payment_id", out var mPayId) ? mPayId.ToString() : null,
|
|
||||||
PaymentId = formCollection.TryGetValue("pf_payment_id", out var pfPayId) ? pfPayId.ToString() : null,
|
|
||||||
PaymentStatus = formCollection.TryGetValue("payment_status", out var status) ? status.ToString() : null,
|
|
||||||
ItemName = formCollection.TryGetValue("item_name", out var item) ? item.ToString() : null,
|
|
||||||
ItemDescription = formCollection.TryGetValue("item_description", out var desc) ? desc.ToString() : null,
|
|
||||||
AmountGross = formCollection.TryGetValue("amount_gross", out var gross) ? gross.ToString() : null,
|
|
||||||
AmountFee = formCollection.TryGetValue("amount_fee", out var fee) ? fee.ToString() : null,
|
|
||||||
AmountNet = formCollection.TryGetValue("amount_net", out var net) ? net.ToString() : null,
|
|
||||||
NameFirst = formCollection.TryGetValue("name_first", out var first) ? first.ToString() : null,
|
|
||||||
NameLast = formCollection.TryGetValue("name_last", out var last) ? last.ToString() : null,
|
|
||||||
EmailAddress = formCollection.TryGetValue("email_address", out var email) ? email.ToString() : null,
|
|
||||||
CustomStr1 = formCollection.TryGetValue("custom_str1", out var cStr1) ? cStr1.ToString() : null,
|
|
||||||
CustomInt1 = formCollection.TryGetValue("custom_int1", out var cInt1) ? cInt1.ToString() : null,
|
|
||||||
Token = formCollection.TryGetValue("token", out var tok) ? tok.ToString() : null
|
|
||||||
};
|
|
||||||
}
|
|
||||||
|
|||||||
@@ -1,6 +1,9 @@
|
|||||||
|
using Asp.Versioning.Builder;
|
||||||
|
using k8s.Models;
|
||||||
using LiteCharms.Features.Extensions;
|
using LiteCharms.Features.Extensions;
|
||||||
using LiteCharms.Features.Mediator;
|
using LiteCharms.Features.Mediator;
|
||||||
using LiteCharms.Features.MidrandBooks.Extensions;
|
using LiteCharms.Features.MidrandBooks.Extensions;
|
||||||
|
using MidrandBooksApi;
|
||||||
using static LiteCharms.Features.Extensions.Quartz;
|
using static LiteCharms.Features.Extensions.Quartz;
|
||||||
|
|
||||||
var builder = WebApplication.CreateBuilder(args);
|
var builder = WebApplication.CreateBuilder(args);
|
||||||
|
|||||||
@@ -0,0 +1,88 @@
|
|||||||
|
namespace MidrandBooksApi;
|
||||||
|
|
||||||
|
public static class Setup
|
||||||
|
{
|
||||||
|
public static IApplicationBuilder MapEndpoints(this WebApplication app, Dictionary<int, RouteGroupBuilder> versionGroups)
|
||||||
|
{
|
||||||
|
var endpoints = app.Services.GetRequiredService<IEnumerable<IEndpoint>>();
|
||||||
|
|
||||||
|
foreach (var endpoint in endpoints)
|
||||||
|
{
|
||||||
|
var versionAttributes = endpoint.GetType().GetCustomAttributes<ApiVersionTargetAttribute>().ToList();
|
||||||
|
|
||||||
|
if (versionAttributes.Count != 0)
|
||||||
|
{
|
||||||
|
foreach (var attr in versionAttributes)
|
||||||
|
if (versionGroups.TryGetValue(attr.MajorVersion, out var targetGroup))
|
||||||
|
endpoint.Map(targetGroup);
|
||||||
|
}
|
||||||
|
else
|
||||||
|
endpoint.Map(app);
|
||||||
|
}
|
||||||
|
|
||||||
|
return app;
|
||||||
|
}
|
||||||
|
|
||||||
|
public static IServiceCollection AddEndpoints(this IServiceCollection services, Assembly assembly)
|
||||||
|
{
|
||||||
|
ServiceDescriptor[] discriptors = [.. assembly.DefinedTypes
|
||||||
|
.Where(t => t is { IsInterface: false, IsAbstract: false })
|
||||||
|
.Where(t => t.IsAssignableTo(typeof(IEndpoint)))
|
||||||
|
.Select(t => ServiceDescriptor.Transient(typeof(IEndpoint), t))];
|
||||||
|
|
||||||
|
services.TryAddEnumerable(discriptors);
|
||||||
|
|
||||||
|
return services;
|
||||||
|
}
|
||||||
|
|
||||||
|
public static string ToEndpointName(this Type target, string? annotation = "") =>
|
||||||
|
$"{target.Name.Replace("Endpoint", string.Empty)}{annotation}".ToLower();
|
||||||
|
|
||||||
|
public static IServiceCollection AddApiServices(this IServiceCollection services, IConfiguration configuration)
|
||||||
|
{
|
||||||
|
services.AddApiVersioning(options =>
|
||||||
|
{
|
||||||
|
options.DefaultApiVersion = new ApiVersion(1);
|
||||||
|
options.ReportApiVersions = true;
|
||||||
|
options.AssumeDefaultVersionWhenUnspecified = true;
|
||||||
|
options.ApiVersionReader = ApiVersionReader.Combine(new UrlSegmentApiVersionReader(),
|
||||||
|
new QueryStringApiVersionReader("version"),
|
||||||
|
new QueryStringApiVersionReader("version"),
|
||||||
|
new MediaTypeApiVersionReader("version"));
|
||||||
|
})
|
||||||
|
.AddApiExplorer(options =>
|
||||||
|
{
|
||||||
|
options.GroupNameFormat = "'v'VVV";
|
||||||
|
options.SubstituteApiVersionInUrl = true;
|
||||||
|
});
|
||||||
|
|
||||||
|
var urls = configuration["ASPNETCORE_URLS"] ?? configuration["Urls"];
|
||||||
|
var healthUrl = "http://localhost:8080/health";
|
||||||
|
|
||||||
|
if (!string.IsNullOrWhiteSpace(urls))
|
||||||
|
{
|
||||||
|
string firstUrl = urls.Split(';').FirstOrDefault(s => s.Contains("http://"))!
|
||||||
|
.Replace("*", "localhost").Replace("+", "localhost");
|
||||||
|
|
||||||
|
healthUrl = $"{firstUrl.TrimEnd('/')}/health";
|
||||||
|
}
|
||||||
|
|
||||||
|
services.AddHealthChecksUI(setup =>
|
||||||
|
{
|
||||||
|
setup.SetNotifyUnHealthyOneTimeUntilChange();
|
||||||
|
setup.AddHealthCheckEndpoint("primary, heal", healthUrl);
|
||||||
|
setup.SetHeaderText("Midrand Books");
|
||||||
|
})
|
||||||
|
.AddInMemoryStorage();
|
||||||
|
|
||||||
|
services.AddOutputCache(options =>
|
||||||
|
{
|
||||||
|
options.AddBasePolicy(builder => builder.Cache());
|
||||||
|
options.DefaultExpirationTimeSpan = TimeSpan.FromSeconds(10);
|
||||||
|
});
|
||||||
|
|
||||||
|
services.AddOpenApi(options => options.AddDocumentTransformer<OpenApiBearerSecuritySchemeTransformer>());
|
||||||
|
|
||||||
|
return services;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -1,13 +1,4 @@
|
|||||||
{
|
{
|
||||||
"ValidPayfastHosts": [
|
|
||||||
"www.payfast.co.za",
|
|
||||||
"sandbox.payfast.co.za",
|
|
||||||
"w1w.payfast.co.za",
|
|
||||||
"w2w.payfast.co.za",
|
|
||||||
"ips.payfast.co.za",
|
|
||||||
"api.payfast.co.za",
|
|
||||||
"payment.payfast.io"
|
|
||||||
],
|
|
||||||
"HasherSettings": {
|
"HasherSettings": {
|
||||||
"MinHashLength": 11
|
"MinHashLength": 11
|
||||||
},
|
},
|
||||||
|
|||||||
@@ -0,0 +1,8 @@
|
|||||||
|
## Payfast Payment Confirmation
|
||||||
|
# This endpoint is used by Payfast to confirm the payment status of a transaction.
|
||||||
|
# It receives a POST request with the payment details and updates the order status accordingly.
|
||||||
|
|
||||||
|
POST {{baseUrl}}/v1/payments/payfast/confirm
|
||||||
|
Content-Type: application/x-www-form-urlencoded
|
||||||
|
|
||||||
|
amount={{amount}}&item_name={{item_name}}&m_payment_id={{paymentId}}&signature={{signature}}
|
||||||
@@ -19,13 +19,6 @@ data:
|
|||||||
BookshopS3Settings__Region: "garage"
|
BookshopS3Settings__Region: "garage"
|
||||||
BookshopS3Settings__BucketName: "bookshop"
|
BookshopS3Settings__BucketName: "bookshop"
|
||||||
BookshopS3Settings__CdnBaseUrl: "https://bookshop.cdn.khongisa.co.za"
|
BookshopS3Settings__CdnBaseUrl: "https://bookshop.cdn.khongisa.co.za"
|
||||||
ValidPayfastHosts__0: "www.payfast.co.za"
|
|
||||||
ValidPayfastHosts__1: "sandbox.payfast.co.za"
|
|
||||||
ValidPayfastHosts__2: "w1w.payfast.co.za"
|
|
||||||
ValidPayfastHosts__3: "w2w.payfast.co.za"
|
|
||||||
ValidPayfastHosts__4: "ips.payfast.co.za"
|
|
||||||
ValidPayfastHosts__5: "api.payfast.co.za"
|
|
||||||
ValidPayfastHosts__6: "payment.payfast.io"
|
|
||||||
---
|
---
|
||||||
apiVersion: v1
|
apiVersion: v1
|
||||||
kind: Secret
|
kind: Secret
|
||||||
|
|||||||
Reference in New Issue
Block a user