HBankClient.php

PHP SDK · 11.6 KB · 246 lines

1<?php
2
3declare(strict_types=1);
4
5namespace HBank;
6
7/**
8 * Client for the HBank merchant API (v1). Needs the curl extension.
9 *
10 * $bank = new \HBank\HBankClient(getenv('HBANK_API_KEY'));
11 * $tid = $bank->createPayment('24.90', 'EUR', 'Order 1042', 'https://shop.example/hbank/callback');
12 * header('Location: ' . $bank->checkoutUrl($tid));
13 *
14 * Answers are associative arrays with the API's field names (see the API docs). Pass amounts as strings ('24.90')
15 * to avoid float rounding; they're sent as strings, which the API accepts. Failures throw HBankException.
16 */
17final class HBankClient
18{
19 public const DEFAULT_BASE_URL = 'https://bank.thehsi.cloud';
20
21 private string $baseUrl;
22
23 public function __construct(
24 private readonly string $apiKey,
25 ?string $baseUrl = null,
26 private readonly int $timeoutSeconds = 30,
27 ) {
28 if ($apiKey === '') {
29 throw new \InvalidArgumentException('API key is required');
30 }
31 $this->baseUrl = rtrim($baseUrl ?? self::DEFAULT_BASE_URL, '/');
32 }
33
34 // ── Payments ─────────────────────────────────────────────
35
36 /** Creates a pending payment request and returns its transaction id. It stays payable for one hour. */
37 public function createPayment(string|int|float $amount, string $currency, ?string $description = null, ?string $callbackUrl = null): string
38 {
39 $body = self::compact(['amount' => self::amount($amount), 'currency' => $currency,
40 'description' => $description, 'callback_url' => $callbackUrl]);
41 return (string) $this->post('payment/request', $body)['transaction_id'];
42 }
43
44 /**
45 * A QR code / link for a pending payment. Calling it again returns the same code.
46 * @return array{code: string, url: string, qr_svg: string}
47 */
48 public function createPaymentCode(string $transactionId): array
49 {
50 $d = $this->post('payment/code', ['transaction_id' => $transactionId]);
51 return ['code' => $d['code'], 'url' => $d['url'], 'qr_svg' => $d['qr_svg']];
52 }
53
54 /**
55 * The current state of one of your payments. Check `status === 'completed'` before handing out goods.
56 * @return array{id: string, type: string, amount: float, currency: string, status: string, description: string,
57 * reference: ?string, payment_code: ?string, refunded: float, refundable: float, refund_of: ?string, subscription_id: ?string,
58 * subscription_ids: list<string>} (subscription_ids: every subscription the payment belongs to)
59 */
60 public function getPayment(string $transactionId): array
61 {
62 return $this->post('payment/details', ['transaction_id' => $transactionId])['transaction'];
63 }
64
65 /**
66 * Refunds (part of) a completed payment: $amount in its currency, or everything that's left when null.
67 * Not safe to blindly retry after a timeout: check `refunded` with getPayment() first.
68 * @return array{refund: array, transaction: array}
69 */
70 public function refund(string $transactionId, string|int|float|null $amount = null, ?string $reason = null): array
71 {
72 $d = $this->post('payment/refund', self::compact(['transaction_id' => $transactionId,
73 'amount' => $amount === null ? null : self::amount($amount), 'reason' => $reason]));
74 return ['refund' => $d['refund'], 'transaction' => $d['transaction']];
75 }
76
77 /** The hosted checkout (card number + PIN) for a payment. The payment needs a callback URL. */
78 public function checkoutUrl(string $transactionId): string
79 {
80 return $this->baseUrl . '/api/payment?tid=' . rawurlencode($transactionId);
81 }
82
83 // ── Subscriptions ────────────────────────────────────────
84
85 /** Offers a subscription ($interval: day, week, month or year). Send the customer its `url`. */
86 public function createSubscription(string|int|float $amount, string $currency, string $interval, int $intervalCount = 1, ?string $description = null): array
87 {
88 return $this->post('subscriptions', self::offer($amount, $currency, $interval, $intervalCount, $description))['subscription'];
89 }
90
91 /**
92 * Offers a subscription and creates its first payment, for the pay button / hosted checkout.
93 * @return array{transaction_id: string, subscription: array}
94 */
95 public function createSubscriptionCheckout(string|int|float $amount, string $currency, string $interval, int $intervalCount = 1,
96 ?string $description = null, ?string $callbackUrl = null): array
97 {
98 $body = self::offer($amount, $currency, $interval, $intervalCount, $description) + self::compact(['callback_url' => $callbackUrl]);
99 $d = $this->post('subscriptions/checkout', $body);
100 return ['transaction_id' => (string) $d['transaction_id'], 'subscription' => $d['subscription']];
101 }
102
103 /**
104 * One first payment for several subscriptions (up to 20, one currency). Each item is the id of a subscription you
105 * offered ('sub_…') or a new offer's fields: ['amount' => …, 'currency' => …, 'interval' => …, 'interval_count' => …,
106 * 'description' => …]. Paying it starts them all; after that each renews on its own. When one is refused, nothing
107 * is offered.
108 * @param list<string|array> $subscriptions
109 * @return array{transaction_id: string, subscriptions: list<array>}
110 */
111 public function createSubscriptionsCheckout(array $subscriptions, ?string $description = null, ?string $callbackUrl = null): array
112 {
113 $items = array_map(fn ($item) => is_string($item) ? $item : self::offer($item['amount'], $item['currency'], $item['interval'],
114 (int) ($item['interval_count'] ?? 1), $item['description'] ?? null), array_values($subscriptions));
115 $body = ['subscriptions' => $items] + self::compact(['description' => $description, 'callback_url' => $callbackUrl]);
116 $d = $this->post('subscriptions/checkout', $body);
117 return ['transaction_id' => (string) $d['transaction_id'], 'subscriptions' => $d['subscriptions']];
118 }
119
120 /**
121 * A new first payment for a subscription already offered (`not_open` once someone subscribed).
122 * @return array{transaction_id: string, subscription: array}
123 */
124 public function checkoutSubscription(string $subscriptionId, ?string $callbackUrl = null): array
125 {
126 $d = $this->post("subscriptions/" . rawurlencode($subscriptionId) . "/checkout", self::compact(['callback_url' => $callbackUrl]));
127 return ['transaction_id' => (string) $d['transaction_id'], 'subscription' => $d['subscription']];
128 }
129
130 /** Your subscriptions, newest first (up to 100). */
131 public function listSubscriptions(): array
132 {
133 return $this->get('subscriptions')['subscriptions'];
134 }
135
136 public function getSubscription(string $subscriptionId): array
137 {
138 return $this->get("subscriptions/" . rawurlencode($subscriptionId))['subscription'];
139 }
140
141 /** No more charges. It stays in its `active_period` until `current_period_end`. */
142 public function cancelSubscription(string $subscriptionId): array
143 {
144 return $this->post("subscriptions/" . rawurlencode($subscriptionId) . "/cancel", [])['subscription'];
145 }
146
147 // ── Currencies ───────────────────────────────────────────
148
149 public function convert(string|int|float $amount, string $from, string $to): float
150 {
151 $q = http_build_query(['amount' => self::amount($amount), 'currency_from' => $from, 'currency_to' => $to]);
152 return (float) $this->get('currency/convert?' . $q)['amount'];
153 }
154
155 /** @return array{to_rate: float, from_rate: float} to_rate converts $from into $to; from_rate the other way. */
156 public function rate(string $from, string $to): array
157 {
158 $d = $this->get('currency/rate?' . http_build_query(['currency_from' => $from, 'currency_to' => $to]));
159 return ['to_rate' => (float) $d['to_rate'], 'from_rate' => (float) $d['from_rate']];
160 }
161
162 // ── Transport ────────────────────────────────────────────
163
164 private function get(string $path): array
165 {
166 return $this->send('GET', $path, null);
167 }
168
169 private function post(string $path, array $body): array
170 {
171 return $this->send('POST', $path, json_encode((object) $body, JSON_THROW_ON_ERROR | JSON_UNESCAPED_SLASHES));
172 }
173
174 private function send(string $method, string $path, ?string $body): array
175 {
176 $headers = ['Authorization: Bearer ' . $this->apiKey, 'Accept: application/json'];
177 if ($body !== null) {
178 $headers[] = 'Content-Type: application/json';
179 }
180 $ch = curl_init($this->baseUrl . '/api/v1/' . $path);
181 curl_setopt_array($ch, [
182 CURLOPT_CUSTOMREQUEST => $method,
183 CURLOPT_HTTPHEADER => $headers,
184 CURLOPT_RETURNTRANSFER => true,
185 CURLOPT_TIMEOUT => $this->timeoutSeconds,
186 CURLOPT_CONNECTTIMEOUT => min(10, $this->timeoutSeconds),
187 CURLOPT_USERAGENT => 'hbank-php/1.0',
188 ]);
189 if ($body !== null) {
190 curl_setopt($ch, CURLOPT_POSTFIELDS, $body);
191 }
192 $text = curl_exec($ch);
193 $status = (int) curl_getinfo($ch, CURLINFO_RESPONSE_CODE);
194 if ($text === false) {
195 $timedOut = curl_errno($ch) === CURLE_OPERATION_TIMEDOUT;
196 $error = curl_error($ch);
197 curl_close($ch);
198 throw new HBankException($timedOut ? 'timeout' : 'connection_failed', 0, $error);
199 }
200 curl_close($ch);
201
202 $trimmed = trim((string) $text);
203 if ($status === 401) {
204 throw new HBankException('missing_api_key', $status, $trimmed ?: null);
205 }
206 if ($status === 403) {
207 throw new HBankException('invalid_api_key', $status, $trimmed ?: null);
208 }
209 $json = json_decode((string) $text, true, 64, JSON_BIGINT_AS_STRING);
210 if (!is_array($json)) {
211 throw new HBankException('invalid_response', $status, substr($trimmed, 0, 200) ?: null);
212 }
213 if ($status < 200 || $status >= 300 || ($json['success'] ?? null) === false) {
214 throw new HBankException(is_string($json['error'] ?? null) ? $json['error'] : "http_{$status}", $status,
215 is_string($json['message'] ?? null) ? $json['message'] : null, $json);
216 }
217 return $json;
218 }
219
220 private static function amount(string|int|float $value): string
221 {
222 if (is_float($value)) {
223 if (!is_finite($value)) {
224 throw new \InvalidArgumentException('amount must be finite');
225 }
226 // Shortest text that round-trips (serialize_precision -1), e.g. 24.9 -> "24.9". The API doesn't take
227 // exponents, so tiny/huge values fall back to fixed notation.
228 $text = json_encode($value);
229 return str_contains($text, 'e') || str_contains($text, 'E')
230 ? rtrim(rtrim(number_format($value, 10, '.', ''), '0'), '.')
231 : $text;
232 }
233 return trim((string) $value);
234 }
235
236 private static function offer(string|int|float $amount, string $currency, string $interval, int $intervalCount, ?string $description): array
237 {
238 return self::compact(['amount' => self::amount($amount), 'currency' => $currency, 'interval' => $interval,
239 'interval_count' => $intervalCount, 'description' => $description]);
240 }
241
242 private static function compact(array $a): array
243 {
244 return array_filter($a, static fn ($v) => $v !== null);
245 }
246}