| 1 | using System.Globalization; |
| 2 | using System.Net.Http.Headers; |
| 3 | using System.Text; |
| 4 | using System.Text.Json; |
| 5 | using System.Text.Json.Nodes; |
| 6 | |
| 7 | namespace HBank.Sdk; |
| 8 | |
| 9 | /// <summary> |
| 10 | /// Client for the HBank merchant API (v1). Thread-safe; register it as a singleton. |
| 11 | /// <code> |
| 12 | /// var bank = new HBankClient(Environment.GetEnvironmentVariable("HBANK_API_KEY")!); |
| 13 | /// var tid = await bank.CreatePaymentAsync(24.90m, "EUR", "Order 1042", "https://shop.example/hbank/callback"); |
| 14 | /// return Redirect(bank.CheckoutUrl(tid)); |
| 15 | /// </code> |
| 16 | /// </summary> |
| 17 | public sealed class HBankClient : IDisposable |
| 18 | { |
| 19 | public const string DefaultBaseUrl = "https://bank.thehsi.cloud"; |
| 20 | |
| 21 | private static readonly JsonSerializerOptions Json = new() { PropertyNameCaseInsensitive = true }; |
| 22 | private readonly HttpClient _http; |
| 23 | private readonly bool _ownsHttp; |
| 24 | private readonly string _apiKey; |
| 25 | |
| 26 | /// <param name="apiKey">Your secret API key.</param> |
| 27 | /// <param name="baseUrl">Default https://bank.thehsi.cloud.</param> |
| 28 | /// <param name="httpClient"> |
| 29 | /// Optional, e.g. from IHttpClientFactory; its Timeout applies. Without one, the client makes its own (30 s timeout). |
| 30 | /// </param> |
| 31 | public HBankClient(string apiKey, string? baseUrl = null, HttpClient? httpClient = null) |
| 32 | { |
| 33 | if (string.IsNullOrWhiteSpace(apiKey)) throw new ArgumentException("API key is required.", nameof(apiKey)); |
| 34 | _apiKey = apiKey; |
| 35 | BaseUrl = (baseUrl ?? DefaultBaseUrl).TrimEnd('/'); |
| 36 | _ownsHttp = httpClient is null; |
| 37 | _http = httpClient ?? new HttpClient { Timeout = TimeSpan.FromSeconds(30) }; |
| 38 | } |
| 39 | |
| 40 | public string BaseUrl { get; } |
| 41 | |
| 42 | // ── Payments ───────────────────────────────────────────── |
| 43 | |
| 44 | /// <summary>Creates a pending payment request and returns its transaction id. It stays payable for one hour.</summary> |
| 45 | public async Task<string> CreatePaymentAsync(decimal amount, string currency, string? description = null, |
| 46 | string? callbackUrl = null, CancellationToken ct = default) |
| 47 | { |
| 48 | var body = new JsonObject { ["amount"] = Amount(amount), ["currency"] = currency }; |
| 49 | Put(body, "description", description); |
| 50 | Put(body, "callback_url", callbackUrl); |
| 51 | return (await SendAsync(HttpMethod.Post, "payment/request", body, ct))["transaction_id"]!.GetValue<string>(); |
| 52 | } |
| 53 | |
| 54 | /// <summary>A QR code / link for a pending payment. Calling it again returns the same code.</summary> |
| 55 | public async Task<PaymentCode> CreatePaymentCodeAsync(string transactionId, CancellationToken ct = default) => |
| 56 | Read<PaymentCode>(await SendAsync(HttpMethod.Post, "payment/code", new JsonObject { ["transaction_id"] = transactionId }, ct)); |
| 57 | |
| 58 | /// <summary>The current state of one of your payments. Check <c>Completed</c> before handing out goods.</summary> |
| 59 | public async Task<Payment> GetPaymentAsync(string transactionId, CancellationToken ct = default) => |
| 60 | Read<Payment>((await SendAsync(HttpMethod.Post, "payment/details", new JsonObject { ["transaction_id"] = transactionId }, ct))["transaction"]); |
| 61 | |
| 62 | /// <summary> |
| 63 | /// Refunds (part of) a completed payment: <paramref name="amount"/> in its currency, or everything that's left when |
| 64 | /// null. Not safe to blindly retry after a timeout: check <c>Refunded</c> with GetPaymentAsync first. |
| 65 | /// </summary> |
| 66 | public async Task<RefundResult> RefundAsync(string transactionId, decimal? amount = null, string? reason = null, |
| 67 | CancellationToken ct = default) |
| 68 | { |
| 69 | var body = new JsonObject { ["transaction_id"] = transactionId }; |
| 70 | if (amount is { } a) body["amount"] = Amount(a); |
| 71 | Put(body, "reason", reason); |
| 72 | return Read<RefundResult>(await SendAsync(HttpMethod.Post, "payment/refund", body, ct)); |
| 73 | } |
| 74 | |
| 75 | /// <summary>The hosted checkout (card number + PIN) for a payment. The payment needs a callback URL.</summary> |
| 76 | public string CheckoutUrl(string transactionId) => $"{BaseUrl}/api/payment?tid={Uri.EscapeDataString(transactionId)}"; |
| 77 | |
| 78 | // ── Subscriptions ──────────────────────────────────────── |
| 79 | |
| 80 | /// <summary>Offers a subscription (interval: day, week, month or year). Send the customer its Url.</summary> |
| 81 | public async Task<Subscription> CreateSubscriptionAsync(decimal amount, string currency, string interval, |
| 82 | int intervalCount = 1, string? description = null, CancellationToken ct = default) => |
| 83 | Read<Subscription>((await SendAsync(HttpMethod.Post, "subscriptions", Offer(amount, currency, interval, intervalCount, description), ct))["subscription"]); |
| 84 | |
| 85 | /// <summary>Offers a subscription and creates its first payment, for the pay button / hosted checkout.</summary> |
| 86 | public async Task<SubscriptionCheckout> CreateSubscriptionCheckoutAsync(decimal amount, string currency, string interval, |
| 87 | int intervalCount = 1, string? description = null, string? callbackUrl = null, CancellationToken ct = default) |
| 88 | { |
| 89 | var body = Offer(amount, currency, interval, intervalCount, description); |
| 90 | Put(body, "callback_url", callbackUrl); |
| 91 | return Read<SubscriptionCheckout>(await SendAsync(HttpMethod.Post, "subscriptions/checkout", body, ct)); |
| 92 | } |
| 93 | |
| 94 | /// <summary> |
| 95 | /// One first payment for several subscriptions (up to 20, one currency): ones you offered |
| 96 | /// (<c>SubscriptionCheckoutItem.Existing("sub_…")</c>, or just the id) or new offers (<c>SubscriptionCheckoutItem.New(…)</c>). |
| 97 | /// Paying it starts them all; after that each renews on its own. When one is refused, nothing is offered. |
| 98 | /// </summary> |
| 99 | public async Task<SubscriptionsCheckout> CreateSubscriptionsCheckoutAsync(IEnumerable<SubscriptionCheckoutItem> subscriptions, |
| 100 | string? description = null, string? callbackUrl = null, CancellationToken ct = default) |
| 101 | { |
| 102 | var items = new JsonArray(); |
| 103 | foreach (var item in subscriptions) |
| 104 | items.Add(item.SubscriptionId is { } id |
| 105 | ? JsonValue.Create(id) |
| 106 | : Offer(item.Amount, item.Currency, item.Interval, item.IntervalCount, item.Description)); |
| 107 | var body = new JsonObject { ["subscriptions"] = items }; |
| 108 | Put(body, "description", description); |
| 109 | Put(body, "callback_url", callbackUrl); |
| 110 | return Read<SubscriptionsCheckout>(await SendAsync(HttpMethod.Post, "subscriptions/checkout", body, ct)); |
| 111 | } |
| 112 | |
| 113 | /// <summary>A new first payment for a subscription already offered (<c>not_open</c> once someone subscribed).</summary> |
| 114 | public async Task<SubscriptionCheckout> CheckoutSubscriptionAsync(string subscriptionId, string? callbackUrl = null, |
| 115 | CancellationToken ct = default) |
| 116 | { |
| 117 | var body = new JsonObject(); |
| 118 | Put(body, "callback_url", callbackUrl); |
| 119 | return Read<SubscriptionCheckout>(await SendAsync(HttpMethod.Post, $"subscriptions/{Uri.EscapeDataString(subscriptionId)}/checkout", body, ct)); |
| 120 | } |
| 121 | |
| 122 | /// <summary>Your subscriptions, newest first (up to 100).</summary> |
| 123 | public async Task<IReadOnlyList<Subscription>> ListSubscriptionsAsync(CancellationToken ct = default) => |
| 124 | Read<List<Subscription>>((await SendAsync(HttpMethod.Get, "subscriptions", null, ct))["subscriptions"]); |
| 125 | |
| 126 | public async Task<Subscription> GetSubscriptionAsync(string subscriptionId, CancellationToken ct = default) => |
| 127 | Read<Subscription>((await SendAsync(HttpMethod.Get, $"subscriptions/{Uri.EscapeDataString(subscriptionId)}", null, ct))["subscription"]); |
| 128 | |
| 129 | /// <summary>No more charges. It stays in its ActivePeriod until CurrentPeriodEnd.</summary> |
| 130 | public async Task<Subscription> CancelSubscriptionAsync(string subscriptionId, CancellationToken ct = default) => |
| 131 | Read<Subscription>((await SendAsync(HttpMethod.Post, $"subscriptions/{Uri.EscapeDataString(subscriptionId)}/cancel", new JsonObject(), ct))["subscription"]); |
| 132 | |
| 133 | // ── Currencies ─────────────────────────────────────────── |
| 134 | |
| 135 | public async Task<decimal> ConvertAsync(decimal amount, string currencyFrom, string currencyTo, CancellationToken ct = default) |
| 136 | { |
| 137 | var path = $"currency/convert?amount={Amount(amount)}¤cy_from={Uri.EscapeDataString(currencyFrom)}¤cy_to={Uri.EscapeDataString(currencyTo)}"; |
| 138 | return (await SendAsync(HttpMethod.Get, path, null, ct))["amount"]!.GetValue<decimal>(); |
| 139 | } |
| 140 | |
| 141 | public async Task<Rate> RateAsync(string currencyFrom, string currencyTo, CancellationToken ct = default) => |
| 142 | Read<Rate>(await SendAsync(HttpMethod.Get, |
| 143 | $"currency/rate?currency_from={Uri.EscapeDataString(currencyFrom)}¤cy_to={Uri.EscapeDataString(currencyTo)}", null, ct)); |
| 144 | |
| 145 | // ── Transport ──────────────────────────────────────────── |
| 146 | |
| 147 | private async Task<JsonObject> SendAsync(HttpMethod method, string path, JsonObject? body, CancellationToken ct) |
| 148 | { |
| 149 | using var request = new HttpRequestMessage(method, $"{BaseUrl}/api/v1/{path}"); |
| 150 | request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", _apiKey); |
| 151 | request.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); |
| 152 | if (body is not null) |
| 153 | request.Content = new StringContent(body.ToJsonString(), Encoding.UTF8, "application/json"); |
| 154 | |
| 155 | int status; |
| 156 | string text; |
| 157 | try |
| 158 | { |
| 159 | using var response = await _http.SendAsync(request, ct).ConfigureAwait(false); |
| 160 | status = (int)response.StatusCode; |
| 161 | text = await response.Content.ReadAsStringAsync().ConfigureAwait(false); |
| 162 | } |
| 163 | catch (TaskCanceledException e) when (!ct.IsCancellationRequested) |
| 164 | { |
| 165 | throw new HBankConnectionException("timeout", "HBank didn't answer in time.", e); |
| 166 | } |
| 167 | catch (HttpRequestException e) |
| 168 | { |
| 169 | throw new HBankConnectionException("connection_failed", e.Message, e); |
| 170 | } |
| 171 | |
| 172 | if (status == 401) throw new HBankAuthenticationException("missing_api_key", status, NullIfEmpty(text)); |
| 173 | if (status == 403) throw new HBankAuthenticationException("invalid_api_key", status, NullIfEmpty(text)); |
| 174 | |
| 175 | JsonObject? json; |
| 176 | try |
| 177 | { |
| 178 | json = JsonNode.Parse(text) as JsonObject; |
| 179 | } |
| 180 | catch (JsonException) |
| 181 | { |
| 182 | json = null; |
| 183 | } |
| 184 | if (json is null) |
| 185 | throw new HBankException("invalid_response", status, NullIfEmpty(text.Length > 200 ? text[..200] : text)); |
| 186 | |
| 187 | var failed = json["success"] is JsonValue s && s.TryGetValue<bool>(out var ok) && !ok; |
| 188 | if (status is < 200 or >= 300 || failed) |
| 189 | throw new HBankException(json["error"]?.GetValue<string>() ?? $"http_{status}", status, json["message"]?.GetValue<string>()); |
| 190 | return json; |
| 191 | } |
| 192 | |
| 193 | private static T Read<T>(JsonNode? node) => |
| 194 | node.Deserialize<T>(Json) ?? throw new HBankException("invalid_response", null, $"Expected {typeof(T).Name}"); |
| 195 | |
| 196 | /// <summary>Amounts go over the wire as strings, which the API accepts, so no digits are lost.</summary> |
| 197 | private static string Amount(decimal value) => value.ToString(CultureInfo.InvariantCulture); |
| 198 | |
| 199 | private static JsonObject Offer(decimal amount, string currency, string interval, int intervalCount, string? description) |
| 200 | { |
| 201 | var body = new JsonObject |
| 202 | { |
| 203 | ["amount"] = Amount(amount), ["currency"] = currency, ["interval"] = interval, ["interval_count"] = intervalCount, |
| 204 | }; |
| 205 | Put(body, "description", description); |
| 206 | return body; |
| 207 | } |
| 208 | |
| 209 | private static void Put(JsonObject body, string key, string? value) |
| 210 | { |
| 211 | if (value is not null) body[key] = value; |
| 212 | } |
| 213 | |
| 214 | private static string? NullIfEmpty(string text) => string.IsNullOrWhiteSpace(text) ? null : text.Trim(); |
| 215 | |
| 216 | public void Dispose() |
| 217 | { |
| 218 | if (_ownsHttp) _http.Dispose(); |
| 219 | } |
| 220 | } |