hbank.go

Go SDK · 16.9 KB · 428 lines

1// Package hbank is a client for the HBank merchant API (v1): payments, QR codes, refunds, subscriptions and
2// currencies. Standard library only.
3//
4// bank := hbank.New(os.Getenv("HBANK_API_KEY"))
5// tid, err := bank.CreatePayment(ctx, hbank.PaymentRequest{Amount: "24.90", Currency: "EUR",
6// Description: "Order 1042", CallbackURL: "https://shop.example/hbank/callback"})
7// http.Redirect(w, r, bank.CheckoutURL(tid), http.StatusFound)
8//
9// Amounts are decimal strings in the currency's major unit ("24.90"), sent and received without going through
10// float64. Use json.Number's Float64 or a decimal library to calculate with them.
11package hbank
12
13import (
14 "bytes"
15 "context"
16 "encoding/json"
17 "errors"
18 "fmt"
19 "io"
20 "net/http"
21 "net/url"
22 "strings"
23 "time"
24)
25
26// Version is this SDK's version. HBank's git repository (bank.thehsi.cloud/hbank/hbank-go.git) tags it as
27// v<Version>: change it whenever the SDK changes, since a published version's contents must never change.
28const Version = "1.2.0"
29
30// DefaultBaseURL is HBank's production address.
31const DefaultBaseURL = "https://bank.thehsi.cloud"
32
33// Client talks to the API. It is safe for concurrent use.
34type Client struct {
35 apiKey string
36 BaseURL string
37 HTTPClient *http.Client
38}
39
40// Option configures a Client.
41type Option func(*Client)
42
43// WithBaseURL sets another HBank address (e.g. a test instance).
44func WithBaseURL(u string) Option { return func(c *Client) { c.BaseURL = strings.TrimRight(u, "/") } }
45
46// WithHTTPClient sets the http.Client to use; its Timeout applies. Default: 30 second timeout.
47func WithHTTPClient(h *http.Client) Option { return func(c *Client) { c.HTTPClient = h } }
48
49// New creates a client for your secret API key.
50func New(apiKey string, opts ...Option) *Client {
51 c := &Client{apiKey: apiKey, BaseURL: DefaultBaseURL, HTTPClient: &http.Client{Timeout: 30 * time.Second}}
52 for _, o := range opts {
53 o(c)
54 }
55 return c
56}
57
58// Error is an error answer from the API. Code is machine-readable ("invalid_amount", "transaction_not_found",
59// "invalid_api_key", ...), Status the HTTP status (0 if HBank couldn't be reached), Message the readable text some
60// errors carry. Use errors.As to get it.
61//
62// When Code is "connection_failed" the request may or may not have reached HBank: before retrying a refund, check
63// Refunded with GetPayment.
64type Error struct {
65 Code string
66 Status int
67 Message string
68 Err error
69}
70
71func (e *Error) Error() string {
72 s := e.Code
73 if e.Status != 0 {
74 s += fmt.Sprintf(" (HTTP %d)", e.Status)
75 }
76 if e.Message != "" {
77 s += ": " + e.Message
78 }
79 return "hbank: " + s
80}
81
82func (e *Error) Unwrap() error { return e.Err }
83
84// IsCode reports whether err is an *Error with the given code.
85func IsCode(err error, code string) bool {
86 var e *Error
87 return errors.As(err, &e) && e.Code == code
88}
89
90// ── Types ───────────────────────────────────────────────────
91
92// Payment is a payment (or a refund, Type "refund").
93type Payment struct {
94 ID string `json:"id"` // "tx_…": a random string, not a number
95 Type string `json:"type"`
96 Amount json.Number `json:"amount"`
97 Currency string `json:"currency"`
98 Status string `json:"status"` // pending, completed or aborted
99 Description string `json:"description"`
100 Reference *string `json:"reference"` // set once completed
101 PaymentCode *string `json:"payment_code"`
102 Refunded json.Number `json:"refunded"`
103 Refundable json.Number `json:"refundable"`
104 RefundOf *string `json:"refund_of"`
105 SubscriptionID *string `json:"subscription_id"` // "sub_…"
106 // SubscriptionIDs lists every subscription the payment belongs to: the one it charged, or all those a checkout of
107 // several started (CreateSubscriptionsCheckout).
108 SubscriptionIDs []string `json:"subscription_ids"`
109}
110
111// Completed reports whether the payment is paid. Check it before handing out goods.
112func (p *Payment) Completed() bool { return p.Status == "completed" }
113
114// PaymentCode is a QR code for a pending payment: put URL in a QR code, or show the SVG at QRSVG.
115type PaymentCode struct {
116 Code string `json:"code"`
117 URL string `json:"url"`
118 QRSVG string `json:"qr_svg"`
119}
120
121type Refund struct {
122 ID string `json:"id"`
123 Amount json.Number `json:"amount"`
124 Currency string `json:"currency"`
125 Reference string `json:"reference"`
126 Reason *string `json:"reason"`
127}
128
129// RefundResult is the refund and the refunded payment, with updated Refunded / Refundable.
130type RefundResult struct {
131 Refund Refund `json:"refund"`
132 Payment Payment `json:"transaction"`
133}
134
135type Subscription struct {
136 ID string `json:"id"` // "sub_…": a random string, not a number
137 Status string `json:"status"` // offered, active or canceled
138 ActivePeriod bool `json:"active_period"` // within a paid period: give access while true
139 Amount json.Number `json:"amount"`
140 Currency string `json:"currency"`
141 Interval string `json:"interval"` // day, week, month or year
142 IntervalCount int `json:"interval_count"`
143 Description *string `json:"description"`
144 URL string `json:"url"` // send this to the customer
145 QRSVG string `json:"qr_svg"`
146 SubscribedAt *time.Time `json:"subscribed_at"`
147 SubscribedForDays *int `json:"subscribed_for_days"`
148 SubscribedForSeconds *int64 `json:"subscribed_for_seconds"`
149 Canceled bool `json:"canceled"`
150 CanceledAt *time.Time `json:"canceled_at"`
151 CanceledBy *string `json:"canceled_by"` // customer, merchant, bank or schedule
152 CurrentPeriodStart *time.Time `json:"current_period_start"`
153 CurrentPeriodEnd *time.Time `json:"current_period_end"`
154 NextChargeAt *time.Time `json:"next_charge_at"`
155 EndsAt *time.Time `json:"ends_at"`
156 LastDay *time.Time `json:"last_day"`
157 Charges int `json:"charges"`
158 LastError *string `json:"last_error"`
159 Customer *struct {
160 Name string `json:"name"`
161 } `json:"customer"`
162}
163
164// SubscriptionCheckout is a subscription's first payment: hand TransactionID to the pay button / hosted checkout.
165type SubscriptionCheckout struct {
166 TransactionID string `json:"transaction_id"`
167 Subscription Subscription `json:"subscription"`
168}
169
170// SubscriptionsCheckout is one first payment for several subscriptions: paying TransactionID starts all of
171// Subscriptions (in your order).
172type SubscriptionsCheckout struct {
173 TransactionID string `json:"transaction_id"`
174 Subscriptions []Subscription `json:"subscriptions"`
175}
176
177// SubscriptionCheckoutItem is one subscription in CreateSubscriptionsCheckout: one you already offered
178// (ExistingSubscription) or a new offer (NewSubscription).
179type SubscriptionCheckoutItem struct {
180 ID string // "sub_…" of an offer, or ""
181 Offer *SubscriptionRequest // the new offer's fields when ID is ""; its CallbackURL is ignored
182}
183
184// ExistingSubscription is a subscription you already offered.
185func ExistingSubscription(id string) SubscriptionCheckoutItem {
186 return SubscriptionCheckoutItem{ID: id}
187}
188
189// NewSubscription is a new offer, made with the checkout.
190func NewSubscription(s SubscriptionRequest) SubscriptionCheckoutItem {
191 return SubscriptionCheckoutItem{Offer: &s}
192}
193
194// MarshalJSON writes the offer's id, or the new offer's fields.
195func (i SubscriptionCheckoutItem) MarshalJSON() ([]byte, error) {
196 if i.ID != "" || i.Offer == nil {
197 return json.Marshal(i.ID)
198 }
199 offer := withCount(*i.Offer)
200 offer.CallbackURL = ""
201 return json.Marshal(offer)
202}
203
204// SubscriptionsCheckoutRequest is the input to CreateSubscriptionsCheckout.
205type SubscriptionsCheckoutRequest struct {
206 Subscriptions []SubscriptionCheckoutItem `json:"subscriptions"` // up to 20, in one currency
207 Description string `json:"description,omitempty"` // default: the subscriptions' descriptions
208 CallbackURL string `json:"callback_url,omitempty"`
209}
210
211// Rate: ToRate converts from into to, FromRate the other way.
212type Rate struct {
213 ToRate json.Number `json:"to_rate"`
214 FromRate json.Number `json:"from_rate"`
215}
216
217// PaymentRequest is the input to CreatePayment.
218type PaymentRequest struct {
219 Amount string `json:"amount"` // e.g. "24.90"
220 Currency string `json:"currency"` // ISO code, e.g. "EUR"
221 Description string `json:"description,omitempty"`
222 CallbackURL string `json:"callback_url,omitempty"` // required for the hosted checkout
223}
224
225// SubscriptionRequest is the input to CreateSubscription and CreateSubscriptionCheckout.
226type SubscriptionRequest struct {
227 Amount string `json:"amount"`
228 Currency string `json:"currency"`
229 Interval string `json:"interval"` // day, week, month or year
230 IntervalCount int `json:"interval_count,omitempty"` // 1 to 120; 0 means 1
231 Description string `json:"description,omitempty"`
232 CallbackURL string `json:"callback_url,omitempty"` // CreateSubscriptionCheckout only
233}
234
235// ── Payments ────────────────────────────────────────────────
236
237// CreatePayment creates a pending payment request and returns its transaction id (a random string like
238// "tx_8fK2mQ7xRb4Tn9WcYz3LpH6v"; store it as text). It stays payable for one hour.
239func (c *Client) CreatePayment(ctx context.Context, p PaymentRequest) (string, error) {
240 var out struct {
241 TransactionID string `json:"transaction_id"`
242 }
243 return out.TransactionID, c.do(ctx, http.MethodPost, "payment/request", p, &out)
244}
245
246// CreatePaymentCode gives a pending payment a QR code / link. Calling it again returns the same code.
247func (c *Client) CreatePaymentCode(ctx context.Context, transactionID string) (*PaymentCode, error) {
248 var out PaymentCode
249 return &out, c.do(ctx, http.MethodPost, "payment/code", map[string]string{"transaction_id": transactionID}, &out)
250}
251
252// GetPayment returns the current state of one of your payments.
253func (c *Client) GetPayment(ctx context.Context, transactionID string) (*Payment, error) {
254 var out struct {
255 Transaction Payment `json:"transaction"`
256 }
257 err := c.do(ctx, http.MethodPost, "payment/details", map[string]string{"transaction_id": transactionID}, &out)
258 return &out.Transaction, err
259}
260
261// Refund refunds (part of) a completed payment: amount in its currency, or everything that's left when "". reason
262// (optional, up to 200 characters) is shown to the customer.
263func (c *Client) Refund(ctx context.Context, transactionID string, amount, reason string) (*RefundResult, error) {
264 body := map[string]any{"transaction_id": transactionID}
265 if amount != "" {
266 body["amount"] = amount
267 }
268 if reason != "" {
269 body["reason"] = reason
270 }
271 var out RefundResult
272 return &out, c.do(ctx, http.MethodPost, "payment/refund", body, &out)
273}
274
275// CheckoutURL is the hosted checkout (card number + PIN) for a payment. The payment needs a callback URL.
276func (c *Client) CheckoutURL(transactionID string) string {
277 return c.BaseURL + "/api/payment?tid=" + url.QueryEscape(transactionID)
278}
279
280// ── Subscriptions ───────────────────────────────────────────
281
282// CreateSubscription offers a subscription. Send the customer its URL.
283func (c *Client) CreateSubscription(ctx context.Context, s SubscriptionRequest) (*Subscription, error) {
284 s.CallbackURL = ""
285 var out struct {
286 Subscription Subscription `json:"subscription"`
287 }
288 err := c.do(ctx, http.MethodPost, "subscriptions", withCount(s), &out)
289 return &out.Subscription, err
290}
291
292// CreateSubscriptionCheckout offers a subscription and creates its first payment, for the pay button.
293func (c *Client) CreateSubscriptionCheckout(ctx context.Context, s SubscriptionRequest) (*SubscriptionCheckout, error) {
294 var out SubscriptionCheckout
295 return &out, c.do(ctx, http.MethodPost, "subscriptions/checkout", withCount(s), &out)
296}
297
298// CreateSubscriptionsCheckout creates one first payment for several subscriptions (up to 20, one currency): offers
299// you made or new ones. Paying it starts them all; after that each renews on its own. When one is refused, nothing
300// is offered.
301func (c *Client) CreateSubscriptionsCheckout(ctx context.Context, r SubscriptionsCheckoutRequest) (*SubscriptionsCheckout, error) {
302 var out SubscriptionsCheckout
303 return &out, c.do(ctx, http.MethodPost, "subscriptions/checkout", r, &out)
304}
305
306// CheckoutSubscription creates a new first payment for a subscription already offered ("not_open" once someone
307// subscribed). callbackURL may be "".
308func (c *Client) CheckoutSubscription(ctx context.Context, subscriptionID string, callbackURL string) (*SubscriptionCheckout, error) {
309 body := map[string]string{}
310 if callbackURL != "" {
311 body["callback_url"] = callbackURL
312 }
313 var out SubscriptionCheckout
314 return &out, c.do(ctx, http.MethodPost, "subscriptions/"+url.PathEscape(subscriptionID)+"/checkout", body, &out)
315}
316
317// ListSubscriptions returns your subscriptions, newest first (up to 100).
318func (c *Client) ListSubscriptions(ctx context.Context) ([]Subscription, error) {
319 var out struct {
320 Subscriptions []Subscription `json:"subscriptions"`
321 }
322 return out.Subscriptions, c.do(ctx, http.MethodGet, "subscriptions", nil, &out)
323}
324
325func (c *Client) GetSubscription(ctx context.Context, subscriptionID string) (*Subscription, error) {
326 var out struct {
327 Subscription Subscription `json:"subscription"`
328 }
329 err := c.do(ctx, http.MethodGet, "subscriptions/"+url.PathEscape(subscriptionID), nil, &out)
330 return &out.Subscription, err
331}
332
333// CancelSubscription stops future charges. It stays in its active period until CurrentPeriodEnd.
334func (c *Client) CancelSubscription(ctx context.Context, subscriptionID string) (*Subscription, error) {
335 var out struct {
336 Subscription Subscription `json:"subscription"`
337 }
338 err := c.do(ctx, http.MethodPost, "subscriptions/"+url.PathEscape(subscriptionID)+"/cancel", map[string]any{}, &out)
339 return &out.Subscription, err
340}
341
342// ── Currencies ──────────────────────────────────────────────
343
344func (c *Client) Convert(ctx context.Context, amount, from, to string) (json.Number, error) {
345 q := url.Values{"amount": {amount}, "currency_from": {from}, "currency_to": {to}}
346 var out struct {
347 Amount json.Number `json:"amount"`
348 }
349 return out.Amount, c.do(ctx, http.MethodGet, "currency/convert?"+q.Encode(), nil, &out)
350}
351
352func (c *Client) Rate(ctx context.Context, from, to string) (*Rate, error) {
353 q := url.Values{"currency_from": {from}, "currency_to": {to}}
354 var out Rate
355 return &out, c.do(ctx, http.MethodGet, "currency/rate?"+q.Encode(), nil, &out)
356}
357
358// ── Transport ───────────────────────────────────────────────
359
360func withCount(s SubscriptionRequest) SubscriptionRequest {
361 if s.IntervalCount == 0 {
362 s.IntervalCount = 1
363 }
364 return s
365}
366
367func (c *Client) do(ctx context.Context, method, path string, body any, out any) error {
368 var reader io.Reader
369 if body != nil {
370 data, err := json.Marshal(body)
371 if err != nil {
372 return err
373 }
374 reader = bytes.NewReader(data)
375 }
376 req, err := http.NewRequestWithContext(ctx, method, c.BaseURL+"/api/v1/"+path, reader)
377 if err != nil {
378 return err
379 }
380 req.Header.Set("Authorization", "Bearer "+c.apiKey)
381 req.Header.Set("Accept", "application/json")
382 if body != nil {
383 req.Header.Set("Content-Type", "application/json")
384 }
385
386 res, err := c.HTTPClient.Do(req)
387 if err != nil {
388 return &Error{Code: "connection_failed", Message: err.Error(), Err: err}
389 }
390 defer res.Body.Close()
391 raw, err := io.ReadAll(io.LimitReader(res.Body, 10<<20))
392 if err != nil {
393 return &Error{Code: "connection_failed", Status: res.StatusCode, Message: err.Error(), Err: err}
394 }
395
396 text := strings.TrimSpace(string(raw))
397 switch res.StatusCode {
398 case http.StatusUnauthorized:
399 return &Error{Code: "missing_api_key", Status: res.StatusCode, Message: text}
400 case http.StatusForbidden:
401 return &Error{Code: "invalid_api_key", Status: res.StatusCode, Message: text}
402 }
403
404 var envelope struct {
405 Success *bool `json:"success"`
406 Error string `json:"error"`
407 Message string `json:"message"`
408 }
409 if err := json.Unmarshal(raw, &envelope); err != nil {
410 if len(text) > 200 {
411 text = text[:200]
412 }
413 return &Error{Code: "invalid_response", Status: res.StatusCode, Message: text, Err: err}
414 }
415 if res.StatusCode < 200 || res.StatusCode >= 300 || (envelope.Success != nil && !*envelope.Success) {
416 code := envelope.Error
417 if code == "" {
418 code = fmt.Sprintf("http_%d", res.StatusCode)
419 }
420 return &Error{Code: code, Status: res.StatusCode, Message: envelope.Message}
421 }
422 dec := json.NewDecoder(bytes.NewReader(raw))
423 dec.UseNumber()
424 if err := dec.Decode(out); err != nil {
425 return &Error{Code: "invalid_response", Status: res.StatusCode, Message: err.Error(), Err: err}
426 }
427 return nil
428}