Ruby SDK

hbank · v1.2.0 · Ruby 2.7+

Download .zip
README.md

hbank (Ruby)

Client for the HBank merchant API. Ruby 2.7+, standard library only.

# Gemfile
gem "hbank", path: "../HBank9/sdks/ruby"
bank = HBank::Client.new(api_key: ENV.fetch("HBANK_API_KEY"))   # base_url: "http://localhost:8000" for local

tid = bank.create_payment(amount: "24.90", currency: "EUR", description: "Order 1042",
                          callback_url: "https://shop.example.com/hbank/callback")
checkout = bank.checkout_url(tid)
qr = bank.create_payment_code(tid)                 # { code:, url:, qr_svg: }

payment = bank.get_payment(tid)
ship(order) if payment[:status] == "completed"

bank.refund(tid, amount: "10.00", reason: "Returned one item")   # no amount = everything left

sub = bank.create_subscription(amount: "9.99", currency: "EUR", interval: "month", description: "Pro plan")
bank.cancel_subscription(sub[:id])

# Several subscriptions in one checkout: offers you made and new ones, one payment starts them all
both = bank.create_subscriptions_checkout([sub[:id], { amount: "2.50", currency: "EUR", interval: "week" }])

bank.convert(100, "EUR", "USD")                    # BigDecimal("108.37")

Answers are Hashes with symbol keys (the API's field names); amounts are BigDecimal.

Errors

begin
  bank.refund(tid)
rescue HBank::AuthenticationError   # missing_api_key / invalid_api_key
rescue HBank::ConnectionError       # connection_failed / timeout: may or may not have reached HBank
rescue HBank::Error => e
  puts e.code, e.status, e.detail   # "not_refundable", 409, "…"
end

Rails

# config/initializers/hbank.rb
HBANK = HBank::Client.new(api_key: Rails.application.credentials.hbank_api_key)

class HbankController < ApplicationController
  skip_forgery_protection only: :callback

  def checkout
    cart = Cart.find(params[:cart])
    tid = HBANK.create_payment(amount: cart.total, currency: "EUR", description: "Order #{cart.id}",
                               callback_url: hbank_callback_url)
    cart.update!(hbank_transaction_id: tid)
    redirect_to HBANK.checkout_url(tid), allow_other_host: true
  end

  def callback
    cb = HBank::Callback.parse(request.raw_post)
    cart = Cart.find_by(hbank_transaction_id: cb.id)
    render json: cart&.total == cb.amount ? HBank::Callback.approve : HBank::Callback.refuse("Out of stock")
  end
end

Sinatra / any Rack app

# config.ru
map("/hbank/callback") { run HBank::Callback.rack { |cb| Order.matches?(cb.id, cb.amount) || "Out of stock" } }

The block returns true (charge), false, or a String shown to the customer (refuse). Callbacks are signed: pass secret: (your signing secret (business settings → Callback URLs)) to HBank::Callback.rack, or call HBank::Callback.verify_signature(secret, header, raw_body). Check the callback against your own order too.

Tests

ruby -Ilib test/hbank_test.rb     # starts ../testing/mock_server.py (needs Python 3)