| 1 | import { AuthenticationError, HBankConnectionError, HBankError } from "./errors.js"; |
| 2 | import type { |
| 3 | Amount, CreatePaymentParams, CreateSubscriptionParams, Payment, PaymentCode, Rate, RefundParams, RefundResult, |
| 4 | Subscription, SubscriptionCheckout, SubscriptionCheckoutParams, SubscriptionsCheckout, SubscriptionsCheckoutParams, |
| 5 | } from "./types.js"; |
| 6 | |
| 7 | export const DEFAULT_BASE_URL = "https://bank.thehsi.cloud"; |
| 8 | |
| 9 | export interface HBankOptions { |
| 10 | apiKey: string; |
| 11 | /** Default: https://bank.thehsi.cloud */ |
| 12 | baseUrl?: string; |
| 13 | /** Per request, in milliseconds. Default 30000. */ |
| 14 | timeoutMs?: number; |
| 15 | /** A custom fetch (for tests, proxies or older runtimes). Default: the global fetch. */ |
| 16 | fetch?: typeof fetch; |
| 17 | } |
| 18 | |
| 19 | type Json = Record<string, unknown>; |
| 20 | |
| 21 | /** |
| 22 | * Client for the HBank merchant API (v1). Server side only: it needs your secret API key. |
| 23 | * |
| 24 | * ```ts |
| 25 | * const bank = new HBank({ apiKey: process.env.HBANK_API_KEY! }); |
| 26 | * const tid = await bank.createPayment({ amount: "24.90", currency: "EUR", callback_url: "https://shop.example/hbank/callback" }); |
| 27 | * res.redirect(bank.checkoutUrl(tid)); |
| 28 | * ``` |
| 29 | */ |
| 30 | export class HBank { |
| 31 | readonly baseUrl: string; |
| 32 | private readonly apiKey: string; |
| 33 | private readonly timeoutMs: number; |
| 34 | private readonly fetchImpl: typeof fetch; |
| 35 | |
| 36 | constructor(options: HBankOptions) { |
| 37 | if (!options?.apiKey) throw new TypeError("apiKey is required"); |
| 38 | this.apiKey = options.apiKey; |
| 39 | this.baseUrl = (options.baseUrl ?? DEFAULT_BASE_URL).replace(/\/+$/, ""); |
| 40 | this.timeoutMs = options.timeoutMs ?? 30_000; |
| 41 | const f = options.fetch ?? globalThis.fetch; |
| 42 | if (typeof f !== "function") throw new TypeError("No fetch available: use Node 18+ or pass options.fetch"); |
| 43 | this.fetchImpl = f.bind(globalThis); |
| 44 | } |
| 45 | |
| 46 | // ── Payments ───────────────────────────────────────────── |
| 47 | |
| 48 | /** Creates a pending payment request and returns its transaction id. It stays payable for one hour. */ |
| 49 | async createPayment(params: CreatePaymentParams): Promise<string> { |
| 50 | const body = compact({ ...params, amount: amount(params.amount) }); |
| 51 | return (await this.post("payment/request", body)).transaction_id as string; |
| 52 | } |
| 53 | |
| 54 | /** A QR code / link for a pending payment. Calling it again returns the same code. */ |
| 55 | async createPaymentCode(transactionId: string): Promise<PaymentCode> { |
| 56 | const d = await this.post("payment/code", { transaction_id: transactionId }); |
| 57 | return { code: d.code as string, url: d.url as string, qr_svg: d.qr_svg as string }; |
| 58 | } |
| 59 | |
| 60 | /** The current state of one of your payments. Check `status === "completed"` here before handing out goods. */ |
| 61 | async getPayment(transactionId: string): Promise<Payment> { |
| 62 | return (await this.post("payment/details", { transaction_id: transactionId })).transaction as Payment; |
| 63 | } |
| 64 | |
| 65 | /** |
| 66 | * Refunds (part of) a completed payment. Not safe to blindly retry after a timeout: check `refunded` with |
| 67 | * `getPayment` first. |
| 68 | */ |
| 69 | async refund(transactionId: string, params: RefundParams = {}): Promise<RefundResult> { |
| 70 | const body = compact({ transaction_id: transactionId, amount: params.amount === undefined ? undefined : amount(params.amount), reason: params.reason }); |
| 71 | const d = await this.post("payment/refund", body); |
| 72 | return { refund: d.refund, transaction: d.transaction } as RefundResult; |
| 73 | } |
| 74 | |
| 75 | /** The hosted checkout (card number + PIN) for a payment. The payment needs a `callback_url`. */ |
| 76 | checkoutUrl(transactionId: string): string { |
| 77 | return `${this.baseUrl}/api/payment?tid=${encodeURIComponent(String(transactionId))}`; |
| 78 | } |
| 79 | |
| 80 | // ── Subscriptions ──────────────────────────────────────── |
| 81 | |
| 82 | /** Offers a subscription. Send the customer its `url` (or show `qr_svg`). */ |
| 83 | async createSubscription(params: CreateSubscriptionParams): Promise<Subscription> { |
| 84 | return (await this.post("subscriptions", offer(params))).subscription as Subscription; |
| 85 | } |
| 86 | |
| 87 | /** Offers a subscription and creates its first payment, for the pay button / hosted checkout. */ |
| 88 | async createSubscriptionCheckout(params: SubscriptionCheckoutParams): Promise<SubscriptionCheckout> { |
| 89 | const d = await this.post("subscriptions/checkout", compact({ ...offer(params), callback_url: params.callback_url })); |
| 90 | return { transaction_id: d.transaction_id, subscription: d.subscription } as SubscriptionCheckout; |
| 91 | } |
| 92 | |
| 93 | /** |
| 94 | * One first payment for several subscriptions (up to 20, one currency): offer ids or new offers. Paying it starts them |
| 95 | * all; after that each renews on its own. When one is refused, nothing is offered. |
| 96 | */ |
| 97 | async createSubscriptionsCheckout(params: SubscriptionsCheckoutParams): Promise<SubscriptionsCheckout> { |
| 98 | const items = params.subscriptions.map((item) => (typeof item === "string" ? item : offer(item))); |
| 99 | const d = await this.post("subscriptions/checkout", compact({ subscriptions: items, description: params.description, callback_url: params.callback_url })); |
| 100 | return { transaction_id: d.transaction_id, subscriptions: d.subscriptions } as SubscriptionsCheckout; |
| 101 | } |
| 102 | |
| 103 | /** A new first payment for a subscription already offered (`not_open` once someone subscribed). */ |
| 104 | async checkoutSubscription(subscriptionId: string, params: { callback_url?: string } = {}): Promise<SubscriptionCheckout> { |
| 105 | const d = await this.post(`subscriptions/${encodeURIComponent(subscriptionId)}/checkout`, compact({ callback_url: params.callback_url })); |
| 106 | return { transaction_id: d.transaction_id, subscription: d.subscription } as SubscriptionCheckout; |
| 107 | } |
| 108 | |
| 109 | /** Your subscriptions, newest first (up to 100). */ |
| 110 | async listSubscriptions(): Promise<Subscription[]> { |
| 111 | return (await this.get("subscriptions")).subscriptions as Subscription[]; |
| 112 | } |
| 113 | |
| 114 | async getSubscription(subscriptionId: string): Promise<Subscription> { |
| 115 | return (await this.get(`subscriptions/${encodeURIComponent(subscriptionId)}`)).subscription as Subscription; |
| 116 | } |
| 117 | |
| 118 | /** No more charges. It stays in its `active_period` until `current_period_end`. */ |
| 119 | async cancelSubscription(subscriptionId: string): Promise<Subscription> { |
| 120 | return (await this.post(`subscriptions/${encodeURIComponent(subscriptionId)}/cancel`, {})).subscription as Subscription; |
| 121 | } |
| 122 | |
| 123 | // ── Currencies ─────────────────────────────────────────── |
| 124 | |
| 125 | async convert(value: Amount, currencyFrom: string, currencyTo: string): Promise<number> { |
| 126 | const d = await this.get("currency/convert", { amount: amount(value), currency_from: currencyFrom, currency_to: currencyTo }); |
| 127 | return d.amount as number; |
| 128 | } |
| 129 | |
| 130 | async rate(currencyFrom: string, currencyTo: string): Promise<Rate> { |
| 131 | const d = await this.get("currency/rate", { currency_from: currencyFrom, currency_to: currencyTo }); |
| 132 | return { to_rate: d.to_rate as number, from_rate: d.from_rate as number }; |
| 133 | } |
| 134 | |
| 135 | // ── Transport ──────────────────────────────────────────── |
| 136 | |
| 137 | private get(path: string, query?: Record<string, string>): Promise<Json> { |
| 138 | return this.send("GET", path + (query ? "?" + new URLSearchParams(query).toString() : "")); |
| 139 | } |
| 140 | |
| 141 | private post(path: string, body: Json): Promise<Json> { |
| 142 | return this.send("POST", path, JSON.stringify(body)); |
| 143 | } |
| 144 | |
| 145 | private async send(method: string, path: string, body?: string): Promise<Json> { |
| 146 | const headers: Record<string, string> = { Authorization: `Bearer ${this.apiKey}`, Accept: "application/json" }; |
| 147 | if (body !== undefined) headers["Content-Type"] = "application/json"; |
| 148 | |
| 149 | const controller = new AbortController(); |
| 150 | const timer = setTimeout(() => controller.abort(), this.timeoutMs); |
| 151 | let status: number; |
| 152 | let text: string; |
| 153 | try { |
| 154 | const res = await this.fetchImpl(`${this.baseUrl}/api/v1/${path}`, { method, headers, body, signal: controller.signal }); |
| 155 | status = res.status; |
| 156 | text = await res.text(); |
| 157 | } catch (e) { |
| 158 | if (controller.signal.aborted) throw new HBankConnectionError("timeout", `No answer within ${this.timeoutMs} ms`, e); |
| 159 | throw new HBankConnectionError("connection_failed", e instanceof Error ? e.message : String(e), e); |
| 160 | } finally { |
| 161 | clearTimeout(timer); |
| 162 | } |
| 163 | |
| 164 | if (status === 401) throw new AuthenticationError("missing_api_key", status, text.trim() || undefined); |
| 165 | if (status === 403) throw new AuthenticationError("invalid_api_key", status, text.trim() || undefined); |
| 166 | |
| 167 | let data: unknown; |
| 168 | try { |
| 169 | data = JSON.parse(text); |
| 170 | } catch { |
| 171 | throw new HBankError("invalid_response", status, text.slice(0, 200) || undefined, text); |
| 172 | } |
| 173 | if (typeof data !== "object" || data === null || Array.isArray(data)) |
| 174 | throw new HBankError("invalid_response", status, text.slice(0, 200), data); |
| 175 | const json = data as Json; |
| 176 | if (status < 200 || status >= 300 || json.success === false) { |
| 177 | const code = typeof json.error === "string" ? json.error : `http_${status}`; |
| 178 | throw new HBankError(code, status, typeof json.message === "string" ? json.message : undefined, json); |
| 179 | } |
| 180 | return json; |
| 181 | } |
| 182 | } |
| 183 | |
| 184 | /** Sends amounts as strings so no digits are lost: 24.9 -> "24.9", "24.90" stays "24.90". */ |
| 185 | function amount(value: Amount): string { |
| 186 | if (typeof value === "number") { |
| 187 | if (!Number.isFinite(value)) throw new TypeError("amount must be a finite number"); |
| 188 | return String(value); |
| 189 | } |
| 190 | if (typeof value === "string") return value.trim(); |
| 191 | throw new TypeError("amount must be a number or a numeric string"); |
| 192 | } |
| 193 | |
| 194 | |
| 195 | function offer(p: CreateSubscriptionParams): Json { |
| 196 | return compact({ amount: amount(p.amount), currency: p.currency, interval: p.interval, interval_count: p.interval_count ?? 1, description: p.description }); |
| 197 | } |
| 198 | |
| 199 | function compact(o: Record<string, unknown>): Json { |
| 200 | return Object.fromEntries(Object.entries(o).filter(([, v]) => v !== undefined && v !== null)); |
| 201 | } |