using System.Globalization; using System.Net.Http.Headers; using System.Text; using System.Text.Json; using System.Text.Json.Nodes; namespace HBank.Sdk; /// /// Client for the HBank merchant API (v1). Thread-safe; register it as a singleton. /// /// var bank = new HBankClient(Environment.GetEnvironmentVariable("HBANK_API_KEY")!); /// var tid = await bank.CreatePaymentAsync(24.90m, "EUR", "Order 1042", "https://shop.example/hbank/callback"); /// return Redirect(bank.CheckoutUrl(tid)); /// /// public sealed class HBankClient : IDisposable { public const string DefaultBaseUrl = "https://bank.thehsi.cloud"; private static readonly JsonSerializerOptions Json = new() { PropertyNameCaseInsensitive = true }; private readonly HttpClient _http; private readonly bool _ownsHttp; private readonly string _apiKey; /// Your secret API key. /// Default https://bank.thehsi.cloud. /// /// Optional, e.g. from IHttpClientFactory; its Timeout applies. Without one, the client makes its own (30 s timeout). /// public HBankClient(string apiKey, string? baseUrl = null, HttpClient? httpClient = null) { if (string.IsNullOrWhiteSpace(apiKey)) throw new ArgumentException("API key is required.", nameof(apiKey)); _apiKey = apiKey; BaseUrl = (baseUrl ?? DefaultBaseUrl).TrimEnd('/'); _ownsHttp = httpClient is null; _http = httpClient ?? new HttpClient { Timeout = TimeSpan.FromSeconds(30) }; } public string BaseUrl { get; } // ── Payments ───────────────────────────────────────────── /// Creates a pending payment request and returns its transaction id. It stays payable for one hour. public async Task CreatePaymentAsync(decimal amount, string currency, string? description = null, string? callbackUrl = null, CancellationToken ct = default) { var body = new JsonObject { ["amount"] = Amount(amount), ["currency"] = currency }; Put(body, "description", description); Put(body, "callback_url", callbackUrl); return (await SendAsync(HttpMethod.Post, "payment/request", body, ct))["transaction_id"]!.GetValue(); } /// A QR code / link for a pending payment. Calling it again returns the same code. public async Task CreatePaymentCodeAsync(string transactionId, CancellationToken ct = default) => Read(await SendAsync(HttpMethod.Post, "payment/code", new JsonObject { ["transaction_id"] = transactionId }, ct)); /// The current state of one of your payments. Check Completed before handing out goods. public async Task GetPaymentAsync(string transactionId, CancellationToken ct = default) => Read((await SendAsync(HttpMethod.Post, "payment/details", new JsonObject { ["transaction_id"] = transactionId }, ct))["transaction"]); /// /// Refunds (part of) a completed payment: in its currency, or everything that's left when /// null. Not safe to blindly retry after a timeout: check Refunded with GetPaymentAsync first. /// public async Task RefundAsync(string transactionId, decimal? amount = null, string? reason = null, CancellationToken ct = default) { var body = new JsonObject { ["transaction_id"] = transactionId }; if (amount is { } a) body["amount"] = Amount(a); Put(body, "reason", reason); return Read(await SendAsync(HttpMethod.Post, "payment/refund", body, ct)); } /// The hosted checkout (card number + PIN) for a payment. The payment needs a callback URL. public string CheckoutUrl(string transactionId) => $"{BaseUrl}/api/payment?tid={Uri.EscapeDataString(transactionId)}"; // ── Subscriptions ──────────────────────────────────────── /// Offers a subscription (interval: day, week, month or year). Send the customer its Url. public async Task CreateSubscriptionAsync(decimal amount, string currency, string interval, int intervalCount = 1, string? description = null, CancellationToken ct = default) => Read((await SendAsync(HttpMethod.Post, "subscriptions", Offer(amount, currency, interval, intervalCount, description), ct))["subscription"]); /// Offers a subscription and creates its first payment, for the pay button / hosted checkout. public async Task CreateSubscriptionCheckoutAsync(decimal amount, string currency, string interval, int intervalCount = 1, string? description = null, string? callbackUrl = null, CancellationToken ct = default) { var body = Offer(amount, currency, interval, intervalCount, description); Put(body, "callback_url", callbackUrl); return Read(await SendAsync(HttpMethod.Post, "subscriptions/checkout", body, ct)); } /// /// One first payment for several subscriptions (up to 20, one currency): ones you offered /// (SubscriptionCheckoutItem.Existing("sub_…"), or just the id) or new offers (SubscriptionCheckoutItem.New(…)). /// Paying it starts them all; after that each renews on its own. When one is refused, nothing is offered. /// public async Task CreateSubscriptionsCheckoutAsync(IEnumerable subscriptions, string? description = null, string? callbackUrl = null, CancellationToken ct = default) { var items = new JsonArray(); foreach (var item in subscriptions) items.Add(item.SubscriptionId is { } id ? JsonValue.Create(id) : Offer(item.Amount, item.Currency, item.Interval, item.IntervalCount, item.Description)); var body = new JsonObject { ["subscriptions"] = items }; Put(body, "description", description); Put(body, "callback_url", callbackUrl); return Read(await SendAsync(HttpMethod.Post, "subscriptions/checkout", body, ct)); } /// A new first payment for a subscription already offered (not_open once someone subscribed). public async Task CheckoutSubscriptionAsync(string subscriptionId, string? callbackUrl = null, CancellationToken ct = default) { var body = new JsonObject(); Put(body, "callback_url", callbackUrl); return Read(await SendAsync(HttpMethod.Post, $"subscriptions/{Uri.EscapeDataString(subscriptionId)}/checkout", body, ct)); } /// Your subscriptions, newest first (up to 100). public async Task> ListSubscriptionsAsync(CancellationToken ct = default) => Read>((await SendAsync(HttpMethod.Get, "subscriptions", null, ct))["subscriptions"]); public async Task GetSubscriptionAsync(string subscriptionId, CancellationToken ct = default) => Read((await SendAsync(HttpMethod.Get, $"subscriptions/{Uri.EscapeDataString(subscriptionId)}", null, ct))["subscription"]); /// No more charges. It stays in its ActivePeriod until CurrentPeriodEnd. public async Task CancelSubscriptionAsync(string subscriptionId, CancellationToken ct = default) => Read((await SendAsync(HttpMethod.Post, $"subscriptions/{Uri.EscapeDataString(subscriptionId)}/cancel", new JsonObject(), ct))["subscription"]); // ── Currencies ─────────────────────────────────────────── public async Task ConvertAsync(decimal amount, string currencyFrom, string currencyTo, CancellationToken ct = default) { var path = $"currency/convert?amount={Amount(amount)}¤cy_from={Uri.EscapeDataString(currencyFrom)}¤cy_to={Uri.EscapeDataString(currencyTo)}"; return (await SendAsync(HttpMethod.Get, path, null, ct))["amount"]!.GetValue(); } public async Task RateAsync(string currencyFrom, string currencyTo, CancellationToken ct = default) => Read(await SendAsync(HttpMethod.Get, $"currency/rate?currency_from={Uri.EscapeDataString(currencyFrom)}¤cy_to={Uri.EscapeDataString(currencyTo)}", null, ct)); // ── Transport ──────────────────────────────────────────── private async Task SendAsync(HttpMethod method, string path, JsonObject? body, CancellationToken ct) { using var request = new HttpRequestMessage(method, $"{BaseUrl}/api/v1/{path}"); request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", _apiKey); request.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); if (body is not null) request.Content = new StringContent(body.ToJsonString(), Encoding.UTF8, "application/json"); int status; string text; try { using var response = await _http.SendAsync(request, ct).ConfigureAwait(false); status = (int)response.StatusCode; text = await response.Content.ReadAsStringAsync().ConfigureAwait(false); } catch (TaskCanceledException e) when (!ct.IsCancellationRequested) { throw new HBankConnectionException("timeout", "HBank didn't answer in time.", e); } catch (HttpRequestException e) { throw new HBankConnectionException("connection_failed", e.Message, e); } if (status == 401) throw new HBankAuthenticationException("missing_api_key", status, NullIfEmpty(text)); if (status == 403) throw new HBankAuthenticationException("invalid_api_key", status, NullIfEmpty(text)); JsonObject? json; try { json = JsonNode.Parse(text) as JsonObject; } catch (JsonException) { json = null; } if (json is null) throw new HBankException("invalid_response", status, NullIfEmpty(text.Length > 200 ? text[..200] : text)); var failed = json["success"] is JsonValue s && s.TryGetValue(out var ok) && !ok; if (status is < 200 or >= 300 || failed) throw new HBankException(json["error"]?.GetValue() ?? $"http_{status}", status, json["message"]?.GetValue()); return json; } private static T Read(JsonNode? node) => node.Deserialize(Json) ?? throw new HBankException("invalid_response", null, $"Expected {typeof(T).Name}"); /// Amounts go over the wire as strings, which the API accepts, so no digits are lost. private static string Amount(decimal value) => value.ToString(CultureInfo.InvariantCulture); private static JsonObject Offer(decimal amount, string currency, string interval, int intervalCount, string? description) { var body = new JsonObject { ["amount"] = Amount(amount), ["currency"] = currency, ["interval"] = interval, ["interval_count"] = intervalCount, }; Put(body, "description", description); return body; } private static void Put(JsonObject body, string key, string? value) { if (value is not null) body[key] = value; } private static string? NullIfEmpty(string text) => string.IsNullOrWhiteSpace(text) ? null : text.Trim(); public void Dispose() { if (_ownsHttp) _http.Dispose(); } }