using System.Security.Cryptography;
using System.Text;
using System.Text.Json;
using System.Text.Json.Serialization;
namespace HBank.Sdk;
///
/// HBank's callback: right before charging a customer, HBank POSTs the payment to its callback URL and charges only if
/// you answer 200 with {"resume": true} as application/json within 10 seconds.
/// It's signed: check the HBank-Signature header with your business's signing secret (business settings → Callback
/// URLs) before you approve, with . Also check that Id and Amount match an order you
/// created, and confirm with GetPaymentAsync before handing out goods.
///
/// // ASP.NET Core minimal API
/// app.MapPost("/hbank/callback", async (HttpRequest req, Orders orders) =>
/// {
/// var body = await new StreamReader(req.Body).ReadToEndAsync();
/// if (!HBankCallback.VerifySignature(secret, req.Headers["HBank-Signature"], body))
/// return Results.Json(HBankCallback.Refuse("Invalid callback"));
/// var cb = HBankCallback.Parse(body);
/// return Results.Json(await orders.MatchesAsync(cb.Id, cb.Amount)
/// ? HBankCallback.Approve() : HBankCallback.Refuse("This order is no longer available"));
/// });
///
///
public sealed record HBankCallback(
[property: JsonPropertyName("id")] string Id,
[property: JsonPropertyName("amount")] decimal Amount,
[property: JsonPropertyName("currency")] string Currency,
[property: JsonPropertyName("status")] string? Status,
[property: JsonPropertyName("description")] string? Description)
{
/// Reads a callback request body. Throws HBankException("invalid_callback") if it isn't one.
public static async Task ReadAsync(Stream body, CancellationToken ct = default)
{
try
{
var cb = await JsonSerializer.DeserializeAsync(body, cancellationToken: ct).ConfigureAwait(false);
return Validate(cb);
}
catch (JsonException e)
{
throw new HBankException("invalid_callback", null, e.Message);
}
}
/// Reads a callback request body. Throws HBankException("invalid_callback") if it isn't one.
public static HBankCallback Parse(string body)
{
try
{
return Validate(JsonSerializer.Deserialize(body));
}
catch (JsonException e)
{
throw new HBankException("invalid_callback", null, e.Message);
}
}
private static HBankCallback Validate(HBankCallback? cb) =>
cb is { Id.Length: > 0 } && !string.IsNullOrEmpty(cb.Currency)
? cb
: throw new HBankException("invalid_callback", null, "missing id, amount or currency");
/// How old a callback's signature may be.
public static readonly TimeSpan SignatureTolerance = TimeSpan.FromMinutes(5);
///
/// Whether (the request's HBank-Signature: t=<unix time>,v1=<hex>) signs
/// (the raw request body, exactly as received) with , and was made
/// within of (default: now).
///
public static bool VerifySignature(string secret, string? header, string body, DateTimeOffset? now = null) =>
VerifySignature(secret, header, Encoding.UTF8.GetBytes(body), now);
///
public static bool VerifySignature(string secret, string? header, byte[] body, DateTimeOffset? now = null)
{
if (string.IsNullOrEmpty(secret) || string.IsNullOrEmpty(header)) return false;
var parts = header.Split(',').Select(p => p.Split('=', 2)).Where(p => p.Length == 2).GroupBy(p => p[0]).ToDictionary(g => g.Key, g => g.First()[1]);
if (!parts.TryGetValue("t", out var t) || !long.TryParse(t, System.Globalization.NumberStyles.None, null, out var timestamp)) return false;
var age = (now ?? DateTimeOffset.UtcNow) - DateTimeOffset.FromUnixTimeSeconds(timestamp);
if (age.Duration() > SignatureTolerance) return false;
var signed = Encoding.ASCII.GetBytes(t + ".").Concat(body).ToArray();
var expected = Convert.ToHexString(HMACSHA256.HashData(Encoding.UTF8.GetBytes(secret), signed)).ToLowerInvariant();
return CryptographicOperations.FixedTimeEquals(Encoding.ASCII.GetBytes(expected), Encoding.ASCII.GetBytes(parts.GetValueOrDefault("v1") ?? ""));
}
/// Lets HBank charge the customer. Serialize as JSON, status 200.
public static CallbackAnswer Approve() => new(true, null);
/// Refuses the payment; the customer sees . Serialize as JSON, status 200.
public static CallbackAnswer Refuse(string? error = null) => new(false, error);
}
public sealed record CallbackAnswer(
[property: JsonPropertyName("resume")] bool Resume,
[property: JsonPropertyName("error"), JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] string? Error);