HBankCallback.cs

C# / .NET SDK · 5.1 KB · 99 lines

1using System.Security.Cryptography;
2using System.Text;
3using System.Text.Json;
4using System.Text.Json.Serialization;
5
6namespace HBank.Sdk;
7
8/// <summary>
9/// HBank's callback: right before charging a customer, HBank POSTs the payment to its callback URL and charges only if
10/// you answer 200 with <c>{"resume": true}</c> as application/json within 10 seconds.
11/// It's signed: check the HBank-Signature header with your business's signing secret (business settings → Callback
12/// URLs) before you approve, with <see cref="VerifySignature"/>. Also check that Id and Amount match an order you
13/// created, and confirm with GetPaymentAsync before handing out goods.
14/// <code>
15/// // ASP.NET Core minimal API
16/// app.MapPost("/hbank/callback", async (HttpRequest req, Orders orders) =>
17/// {
18/// var body = await new StreamReader(req.Body).ReadToEndAsync();
19/// if (!HBankCallback.VerifySignature(secret, req.Headers["HBank-Signature"], body))
20/// return Results.Json(HBankCallback.Refuse("Invalid callback"));
21/// var cb = HBankCallback.Parse(body);
22/// return Results.Json(await orders.MatchesAsync(cb.Id, cb.Amount)
23/// ? HBankCallback.Approve() : HBankCallback.Refuse("This order is no longer available"));
24/// });
25/// </code>
26/// </summary>
27public sealed record HBankCallback(
28 [property: JsonPropertyName("id")] string Id,
29 [property: JsonPropertyName("amount")] decimal Amount,
30 [property: JsonPropertyName("currency")] string Currency,
31 [property: JsonPropertyName("status")] string? Status,
32 [property: JsonPropertyName("description")] string? Description)
33{
34 /// <summary>Reads a callback request body. Throws HBankException("invalid_callback") if it isn't one.</summary>
35 public static async Task<HBankCallback> ReadAsync(Stream body, CancellationToken ct = default)
36 {
37 try
38 {
39 var cb = await JsonSerializer.DeserializeAsync<HBankCallback>(body, cancellationToken: ct).ConfigureAwait(false);
40 return Validate(cb);
41 }
42 catch (JsonException e)
43 {
44 throw new HBankException("invalid_callback", null, e.Message);
45 }
46 }
47
48 /// <summary>Reads a callback request body. Throws HBankException("invalid_callback") if it isn't one.</summary>
49 public static HBankCallback Parse(string body)
50 {
51 try
52 {
53 return Validate(JsonSerializer.Deserialize<HBankCallback>(body));
54 }
55 catch (JsonException e)
56 {
57 throw new HBankException("invalid_callback", null, e.Message);
58 }
59 }
60
61 private static HBankCallback Validate(HBankCallback? cb) =>
62 cb is { Id.Length: > 0 } && !string.IsNullOrEmpty(cb.Currency)
63 ? cb
64 : throw new HBankException("invalid_callback", null, "missing id, amount or currency");
65
66 /// <summary>How old a callback's signature may be.</summary>
67 public static readonly TimeSpan SignatureTolerance = TimeSpan.FromMinutes(5);
68
69 /// <summary>
70 /// Whether <paramref name="header"/> (the request's HBank-Signature: <c>t=&lt;unix time&gt;,v1=&lt;hex&gt;</c>) signs
71 /// <paramref name="body"/> (the raw request body, exactly as received) with <paramref name="secret"/>, and was made
72 /// within <see cref="SignatureTolerance"/> of <paramref name="now"/> (default: now).
73 /// </summary>
74 public static bool VerifySignature(string secret, string? header, string body, DateTimeOffset? now = null) =>
75 VerifySignature(secret, header, Encoding.UTF8.GetBytes(body), now);
76
77 /// <inheritdoc cref="VerifySignature(string, string?, string, DateTimeOffset?)"/>
78 public static bool VerifySignature(string secret, string? header, byte[] body, DateTimeOffset? now = null)
79 {
80 if (string.IsNullOrEmpty(secret) || string.IsNullOrEmpty(header)) return false;
81 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]);
82 if (!parts.TryGetValue("t", out var t) || !long.TryParse(t, System.Globalization.NumberStyles.None, null, out var timestamp)) return false;
83 var age = (now ?? DateTimeOffset.UtcNow) - DateTimeOffset.FromUnixTimeSeconds(timestamp);
84 if (age.Duration() > SignatureTolerance) return false;
85 var signed = Encoding.ASCII.GetBytes(t + ".").Concat(body).ToArray();
86 var expected = Convert.ToHexString(HMACSHA256.HashData(Encoding.UTF8.GetBytes(secret), signed)).ToLowerInvariant();
87 return CryptographicOperations.FixedTimeEquals(Encoding.ASCII.GetBytes(expected), Encoding.ASCII.GetBytes(parts.GetValueOrDefault("v1") ?? ""));
88 }
89
90 /// <summary>Lets HBank charge the customer. Serialize as JSON, status 200.</summary>
91 public static CallbackAnswer Approve() => new(true, null);
92
93 /// <summary>Refuses the payment; the customer sees <paramref name="error"/>. Serialize as JSON, status 200.</summary>
94 public static CallbackAnswer Refuse(string? error = null) => new(false, error);
95}
96
97public sealed record CallbackAnswer(
98 [property: JsonPropertyName("resume")] bool Resume,
99 [property: JsonPropertyName("error"), JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] string? Error);