hbank.rb

Ruby SDK · 13.1 KB · 293 lines

1# frozen_string_literal: true
2
3require "bigdecimal"
4require "json"
5require "net/http"
6require "openssl"
7require "uri"
8
9# Client for the HBank merchant API (v1). Standard library only.
10#
11# bank = HBank::Client.new(api_key: ENV.fetch("HBANK_API_KEY"))
12# tid = bank.create_payment(amount: "24.90", currency: "EUR", description: "Order 1042",
13# callback_url: "https://shop.example/hbank/callback")
14# redirect_to bank.checkout_url(tid), allow_other_host: true
15#
16# Answers are Hashes with symbol keys and the API's field names; amounts are BigDecimal, so no digits are lost.
17module HBank
18 VERSION = "1.2.0"
19 DEFAULT_BASE_URL = "https://bank.thehsi.cloud"
20
21 # The API answered with an error. +code+ is machine-readable ("invalid_amount", "transaction_not_found", ...),
22 # +status+ the HTTP status (nil when HBank couldn't be reached), +detail+ the readable message some errors carry.
23 class Error < StandardError
24 attr_reader :code, :status, :detail, :body
25
26 def initialize(code, status = nil, detail = nil, body = nil)
27 super(detail ? "#{code}: #{detail}" : code.to_s)
28 @code = code
29 @status = status
30 @detail = detail
31 @body = body
32 end
33 end
34
35 # 401 missing_api_key or 403 invalid_api_key.
36 class AuthenticationError < Error; end
37
38 # HBank couldn't be reached or didn't answer in time ("connection_failed" / "timeout"). The request may or may not
39 # have reached HBank: before retrying a refund, check :refunded with get_payment.
40 class ConnectionError < Error; end
41
42 class Client
43 attr_reader :base_url
44
45 def initialize(api_key:, base_url: DEFAULT_BASE_URL, timeout: 30)
46 raise ArgumentError, "api_key is required" if api_key.nil? || api_key.empty?
47
48 @api_key = api_key
49 @base_url = base_url.sub(%r{/+\z}, "")
50 @timeout = timeout
51 end
52
53 # ── Payments ─────────────────────────────────────────────
54
55 # Creates a pending payment request and returns its transaction id. It stays payable for one hour.
56 def create_payment(amount:, currency:, description: nil, callback_url: nil)
57 post("payment/request", compact(amount: amount_text(amount), currency: currency,
58 description: description, callback_url: callback_url))[:transaction_id]
59 end
60
61 # A QR code / link for a pending payment: { code:, url:, qr_svg: }. Calling it again returns the same code.
62 def create_payment_code(transaction_id)
63 post("payment/code", transaction_id: transaction_id).slice(:code, :url, :qr_svg)
64 end
65
66 # The current state of one of your payments. Check payment[:status] == "completed" before handing out goods.
67 def get_payment(transaction_id)
68 post("payment/details", transaction_id: transaction_id)[:transaction]
69 end
70
71 # Refunds (part of) a completed payment: amount in its currency, or everything that's left when nil.
72 # Returns { refund:, transaction: }. Not safe to blindly retry after a timeout: check :refunded first.
73 def refund(transaction_id, amount: nil, reason: nil)
74 post("payment/refund", compact(transaction_id: transaction_id, amount: amount && amount_text(amount),
75 reason: reason)).slice(:refund, :transaction)
76 end
77
78 # The hosted checkout (card number + PIN) for a payment. The payment needs a callback URL.
79 def checkout_url(transaction_id)
80 "#{@base_url}/api/payment?tid=#{URI.encode_www_form_component(transaction_id.to_s)}"
81 end
82
83 # ── Subscriptions ────────────────────────────────────────
84
85 # Offers a subscription (interval: "day", "week", "month" or "year"). Send the customer its :url.
86 def create_subscription(amount:, currency:, interval:, interval_count: 1, description: nil)
87 post("subscriptions", offer(amount, currency, interval, interval_count, description))[:subscription]
88 end
89
90 # Offers a subscription and creates its first payment: { transaction_id:, subscription: }.
91 def create_subscription_checkout(amount:, currency:, interval:, interval_count: 1, description: nil, callback_url: nil)
92 body = offer(amount, currency, interval, interval_count, description).merge(compact(callback_url: callback_url))
93 post("subscriptions/checkout", body).slice(:transaction_id, :subscription)
94 end
95
96 # One first payment for several subscriptions (up to 20, one currency): { transaction_id:, subscriptions: }. Each item
97 # is the id of a subscription you offered ("sub_…") or a new offer's fields as a hash (amount:, currency:, interval:,
98 # interval_count:, description:). Paying it starts them all; after that each renews on its own. When one is
99 # refused, nothing is offered. Payment details list them in :subscription_ids.
100 def create_subscriptions_checkout(subscriptions, description: nil, callback_url: nil)
101 items = subscriptions.map do |item|
102 next item.to_s unless item.is_a?(Hash)
103
104 offer(item.fetch(:amount), item.fetch(:currency), item.fetch(:interval), item.fetch(:interval_count, 1), item[:description])
105 end
106 post("subscriptions/checkout", { subscriptions: items }.merge(compact(description: description, callback_url: callback_url)))
107 .slice(:transaction_id, :subscriptions)
108 end
109
110 # A new first payment for a subscription already offered ("not_open" once someone subscribed).
111 def checkout_subscription(subscription_id, callback_url: nil)
112 post("subscriptions/#{URI.encode_www_form_component(subscription_id.to_s)}/checkout", compact(callback_url: callback_url))
113 .slice(:transaction_id, :subscription)
114 end
115
116 # Your subscriptions, newest first (up to 100).
117 def list_subscriptions
118 get("subscriptions")[:subscriptions]
119 end
120
121 def get_subscription(subscription_id)
122 get("subscriptions/#{URI.encode_www_form_component(subscription_id.to_s)}")[:subscription]
123 end
124
125 # No more charges. It stays in its :active_period until :current_period_end.
126 def cancel_subscription(subscription_id)
127 post("subscriptions/#{URI.encode_www_form_component(subscription_id.to_s)}/cancel", {})[:subscription]
128 end
129
130 # ── Currencies ───────────────────────────────────────────
131
132 def convert(amount, from, to)
133 get("currency/convert", amount: amount_text(amount), currency_from: from, currency_to: to)[:amount]
134 end
135
136 # { to_rate:, from_rate: }: to_rate converts from into to; from_rate the other way.
137 def rate(from, to)
138 get("currency/rate", currency_from: from, currency_to: to).slice(:to_rate, :from_rate)
139 end
140
141 private
142
143 def get(path, query = nil)
144 path += "?#{URI.encode_www_form(query)}" if query
145 send_request(Net::HTTP::Get.new(uri(path)))
146 end
147
148 def post(path, body)
149 request = Net::HTTP::Post.new(uri(path))
150 request["Content-Type"] = "application/json"
151 request.body = JSON.generate(body)
152 send_request(request)
153 end
154
155 def uri(path)
156 URI("#{@base_url}/api/v1/#{path}")
157 end
158
159 def send_request(request)
160 request["Authorization"] = "Bearer #{@api_key}"
161 request["Accept"] = "application/json"
162 request["User-Agent"] = "hbank-ruby/#{VERSION}"
163 target = request.uri
164 begin
165 response = Net::HTTP.start(target.host, target.port, use_ssl: target.scheme == "https",
166 open_timeout: [@timeout, 10].min, read_timeout: @timeout,
167 write_timeout: @timeout) { |http| http.request(request) }
168 rescue Net::OpenTimeout, Net::ReadTimeout, Net::WriteTimeout => e
169 raise ConnectionError.new("timeout", nil, e.message)
170 rescue SystemCallError, SocketError, IOError, OpenSSL::SSL::SSLError => e
171 raise ConnectionError.new("connection_failed", nil, e.message)
172 end
173
174 status = response.code.to_i
175 text = response.body.to_s
176 raise AuthenticationError.new("missing_api_key", status, text.strip) if status == 401
177 raise AuthenticationError.new("invalid_api_key", status, text.strip) if status == 403
178
179 json = begin
180 JSON.parse(text, symbolize_names: true, decimal_class: BigDecimal)
181 rescue JSON::ParserError
182 nil
183 end
184 raise Error.new("invalid_response", status, text[0, 200]) unless json.is_a?(Hash)
185
186 if status < 200 || status >= 300 || json[:success] == false
187 code = json[:error].is_a?(String) ? json[:error] : "http_#{status}"
188 raise Error.new(code, status, json[:message], json)
189 end
190 json
191 end
192
193 # Amounts go over the wire as strings, which the API accepts, so no digits are lost.
194 def amount_text(value)
195 case value
196 when BigDecimal then value.to_s("F")
197 when Integer, Float, String then value.to_s.strip
198 else raise ArgumentError, "amount must be a number or a numeric string"
199 end
200 end
201
202 def offer(amount, currency, interval, interval_count, description)
203 compact(amount: amount_text(amount), currency: currency, interval: interval, interval_count: interval_count,
204 description: description)
205 end
206
207 def compact(hash)
208 hash.reject { |_, v| v.nil? }
209 end
210 end
211
212 # HBank's callback: right before charging a customer, HBank POSTs the payment to its callback URL and charges only
213 # if you answer 200 with {"resume": true} as application/json within 10 seconds.
214 #
215 # It's signed: check the HBank-Signature header with your business's signing secret (business settings → Callback
216 # URLs) before you approve, with verify_signature (or rack(secret: ...)). Also check that id and amount match an order
217 # you created, and confirm with get_payment before handing out goods.
218 #
219 # # Rails (skip_forgery_protection in this controller)
220 # def hbank_callback
221 # unless HBank::Callback.verify_signature(ENV["HBANK_CALLBACK_SECRET"], request.headers["HBank-Signature"], request.raw_post)
222 # return render json: HBank::Callback.refuse("Invalid callback")
223 # end
224 # cb = HBank::Callback.parse(request.raw_post)
225 # order = Order.find_by(hbank_transaction_id: cb.id)
226 # render json: order&.total == cb.amount ? HBank::Callback.approve : HBank::Callback.refuse("Out of stock")
227 # end
228 Callback = Struct.new(:id, :amount, :currency, :status, :description, keyword_init: true) do
229 # Reads a callback body. Raises HBank::Error("invalid_callback") if it isn't one.
230 def self.parse(body)
231 d = JSON.parse(body, decimal_class: BigDecimal)
232 unless d.is_a?(Hash) && d["id"].is_a?(String) && !d["id"].empty? && d["amount"] && d["currency"].is_a?(String)
233 raise Error.new("invalid_callback", nil, "missing or invalid id, amount or currency")
234 end
235
236 new(id: d["id"], amount: BigDecimal(d["amount"].to_s), currency: d["currency"],
237 status: d["status"].to_s, description: d["description"].to_s)
238 rescue JSON::ParserError, ArgumentError => e
239 raise Error.new("invalid_callback", nil, e.message)
240 end
241
242 # Whether header (the request's HBank-Signature: "t=<unix time>,v1=<hex>") signs body (the raw request body, exactly
243 # as received) with secret, and was made within tolerance seconds of now.
244 def self.verify_signature(secret, header, body, tolerance: 300, now: Time.now.to_i)
245 return false if secret.nil? || secret.empty? || header.nil? || header.empty?
246
247 parts = {}
248 header.split(",").each do |part|
249 key, value = part.split("=", 2)
250 parts[key] ||= value if value
251 end
252 t = parts["t"].to_s
253 return false unless t.match?(/\A\d{1,18}\z/) && (now - t.to_i).abs <= tolerance
254
255 expected = OpenSSL::HMAC.hexdigest("SHA256", secret, "#{t}.#{body}")
256 given = parts["v1"].to_s
257 expected.bytesize == given.bytesize && OpenSSL.fixed_length_secure_compare(expected, given)
258 end
259
260 # Lets HBank charge the customer.
261 def self.approve
262 { resume: true }
263 end
264
265 # Refuses the payment; the customer sees error.
266 def self.refuse(error = nil)
267 error ? { resume: false, error: error } : { resume: false }
268 end
269
270 # A Rack app for the callback URL (Sinatra, Hanami, Roda, or `mount` in Rails routes):
271 # map("/hbank/callback") { run HBank::Callback.rack { |cb| Order.matches?(cb.id, cb.amount) } }
272 # The block returns true (charge), false, or a String shown to the customer (refuse). With secret:, a callback
273 # without a valid HBank-Signature is refused ("Invalid callback") before the block runs.
274 def self.rack(secret: nil, &decide)
275 lambda do |env|
276 answer = begin
277 body = env["rack.input"].read
278 if secret && !verify_signature(secret, env["HTTP_HBANK_SIGNATURE"], body)
279 raise Error.new("invalid_callback", nil, "bad or missing HBank-Signature")
280 end
281
282 decision = decide.call(parse(body))
283 decision == true ? approve : refuse(decision.is_a?(String) ? decision : nil)
284 rescue Error
285 refuse("Invalid callback")
286 rescue StandardError
287 refuse("The shop couldn't confirm this order")
288 end
289 [200, { "content-type" => "application/json" }, [JSON.generate(answer)]]
290 end
291 end
292 end
293end