A crypto payment API in Ruby: Net::HTTP, Rack and Rails
easyway has no Ruby gem, and a Ruby app doesn't need one. Creating an invoice is one HTTPS request, which Net::HTTP sends, and checking a webhook is one HMAC, which OpenSSL::HMAC computes. Both come with Ruby. This post shows a small client, a signature check, and how to plug the check into a bare Rack app or a Rails controller. We ran the client and the Rack endpoint on Ruby 3.3, and the error path against the live API.
The pieces
| File | Job | Needs |
|---|---|---|
easyway.rb | POST /v1/invoices and return the invoice, whose payment_url you redirect the customer to. | json, net/http (standard library) |
webhook.rb | Check the X-Webhook-Signature header of a delivery. | openssl (standard library) |
config.ru or a controller | Receive invoice.paid, check it, mark the order paid. | Rack, which Rails, Sinatra and Hanami already use |
Between the two calls, the customer pays on the hosted checkout: they pick a coin and network, see the amount and a QR code, and the page follows the payment by itself. Create the API key in Dashboard → Developers. An sk_test_… key only touches sandbox data, so you can try everything below before real money moves.
1. Create the invoice with Net::HTTP
# easyway.rb: one method, no gems. Ruby 3.0+.
require "json"
require "net/http"
require "uri"
module Easyway
API = ENV.fetch("EASYWAY_API", "https://api.easyway.cash")
CLASSES = %w[bad_request unauthorized forbidden not_found conflict].freeze
class Error < StandardError
attr_reader :status, :code
def initialize(status, code)
super("easyway #{status}: #{code}")
@status, @code = status, code
end
end
# amount_cents is an Integer: 14900 -> "149.00". Never pass a Float.
def self.create_invoice(order_id, amount_cents)
uri = URI("#{API}/v1/invoices")
req = Net::HTTP::Post.new(uri)
req["Authorization"] = "Bearer #{ENV.fetch("EASYWAY_API_KEY")}"
req["Idempotency-Key"] = "shop-order-#{order_id}" # 8-128 chars; a retry returns the same invoice
req["Content-Type"] = "application/json"
req.body = JSON.generate(
amount: format("%d.%02d", amount_cents / 100, amount_cents % 100),
currency: "USD",
order_id: order_id.to_s,
description: "Order ##{order_id}",
success_url: "https://shop.example.com/thanks?order=#{URI.encode_www_form_component(order_id)}",
cancel_url: "https://shop.example.com/cart"
)
res = Net::HTTP.start(uri.host, uri.port, use_ssl: uri.scheme == "https",
open_timeout: 5, read_timeout: 15, write_timeout: 15) { |http| http.request(req) }
return JSON.parse(res.body) if res.is_a?(Net::HTTPSuccess) # id, status "pending", payment_url, ...
err = JSON.parse(res.body) rescue {}
err = {} unless err.is_a?(Hash)
code = CLASSES.include?(err["error"]) ? err["message"] : err["error"]
raise Error.new(res.code.to_i, code || "unknown_error")
end
end| Detail | Why |
|---|---|
| Integer cents | The API takes decimal strings such as "149.00". Keep money as integer cents and format it at the edge; a Float like 0.1 + 0.2 is 0.30000000000000004. This also avoids bigdecimal, which is no longer a default gem from Ruby 3.4. |
| Idempotency-Key | Built from the order id, so a retry after a timeout returns the same invoice instead of a second one. It must be 8–128 characters of letters, digits and _ - : . A bare "order-7" is only 7 characters and gets 400 invalid_idempotency_key; the shop- prefix keeps short ids valid. |
| Timeouts | Net::HTTP waits 60 seconds by default. Set open_timeout and read_timeout so a stalled connection can't hold a web worker. |
Net::HTTPSuccess | Net::HTTP does not raise on 4xx or 5xx; check the class. The helper reads the specific code: most errors put a class in error and the code in message, e.g. {"error": "unauthorized", "message": "invalid_api_key"} (see errors in the docs). |
require_relative "easyway"
invoice = Easyway.create_invoice("2048", 14900) # order id and total in cents from your database
# save invoice["id"] with the order, then redirect the customer (303) to:
redirect_to invoice["payment_url"], allow_other_host: true, status: :see_other # RailsAgainst a local stand-in of the API the helper returned the payment_url, and the request body carried "149.00". With a made-up key, the live API answered easyway 401: invalid_api_key. If the call raises Net::OpenTimeout, Net::ReadTimeout or a connection error, call it again with the same order id; the Idempotency-Key makes that safe. To bill in a coin instead of USD, set currency to an asset id such as "USDT_TRC20" (see pricing in USD or in the coin); to show only some coins, add allowed_assets (see limiting the checkout).
2. Verify the webhook with OpenSSL::HMAC
Each delivery carries X-Webhook-Signature: t=…,v1=…, where v1 is the lower-case hex HMAC-SHA256 of t + "." + raw body under the endpoint's signing secret.
# webhook.rb: verify an easyway delivery. Only openssl from the standard library.
require "openssl"
module EasywayWebhook
TOLERANCE = 300 # seconds
def self.valid?(header, raw_body, secret, now: Time.now.to_i)
parts = header.to_s.split(",").filter_map { |p| p.split("=", 2) if p.include?("=") }.to_h
t, v1 = parts["t"].to_s, parts["v1"].to_s
return false unless t.match?(/\A\d{1,12}\z/) # \A and \z, never ^ and $
return false if (now - t.to_i).abs > TOLERANCE # missing, malformed or more than 5 minutes off
expected = OpenSSL::HMAC.hexdigest("SHA256", secret, "#{t}.#{raw_body}")
OpenSSL.secure_compare(expected, v1) # constant time, any length
end
endAs a bare Rack app, which any Ruby web server can run:
# config.ru: a bare Rack endpoint (rackup -p 8000). Dashboard -> Developers -> Webhooks points here.
require "json"
require_relative "webhook"
SECRET = ENV.fetch("EASYWAY_WEBHOOK_SECRET")
run lambda { |env|
req = Rack::Request.new(env)
raw = req.body.read(1_000_000).to_s # the RAW body is what was signed
unless req.post? && EasywayWebhook.valid?(req.get_header("HTTP_X_WEBHOOK_SIGNATURE"), raw, SECRET)
next [400, {}, []]
end
event = JSON.parse(raw)
# Store event["id"] and skip repeats: deliveries are retried until you answer 2xx.
if event["type"] == "invoice.paid"
inv = event["data"]["invoice"]
puts "order #{inv["order_id"]} paid: #{inv["net_amount"]} #{inv["pay_asset"]}"
# mark_order_paid(inv["order_id"], inv["id"], inv["net_amount"], inv["pay_asset"])
end
[200, {}, []]
}We sent signed deliveries to this app under rackup. The genuine one got 200. A changed body, a timestamp 400 seconds old, another secret, a missing or malformed header, a non-ASCII or short v1, and a GET all got 400. In Rails, the same check sits in a controller:
# app/controllers/easyway_webhooks_controller.rb (route: post "/webhooks/easyway")
class EasywayWebhooksController < ActionController::API
def create
raw = request.raw_post
ok = EasywayWebhook.valid?(request.headers["X-Webhook-Signature"], raw,
Rails.application.credentials.easyway_webhook_secret)
return head :bad_request unless ok
event = JSON.parse(raw)
PaidOrderJob.perform_later(event) if event["type"] == "invoice.paid" # e-mails etc. off the request
head :ok
end
end| Ruby pitfall | Fix |
|---|---|
^ and $ in a regex | In Ruby they match at line breaks, so /^\d+$/ accepts "1795…\nabc". Use \A and \z; with them our check returned false for that value. |
== on the signature | A plain comparison stops at the first different byte. OpenSSL.secure_compare takes the same time and accepts strings of any length. |
params in Rails | Rails parses the JSON into params, and re-serialised JSON is not byte-identical. Sign-check request.raw_post, then parse it. |
| CSRF | A controller that inherits from ActionController::Base rejects the POST without a token. Use ActionController::API as above, or skip the forgery check for this action only. |
| Duplicates and speed | Deliveries are retried until you answer 2xx within 10 seconds. Store the event id, skip repeats, and send e-mails or licence keys from a job. |
We did not run the controller inside a Rails app; it calls the same valid? method we tested. The webhook retries post explains duplicates and ordering, and the signature guide shows how to sign a test request with openssl.
Test it end to end
Set EASYWAY_API_KEY to a test key and EASYWAY_WEBHOOK_SECRET to the endpoint's secret, run rackup -p 8000 behind a tunnel, and add the tunnel URL in Dashboard → Developers → Webhooks. Create an invoice, open its payment_url and press Simulate payment: the real crediting code runs and a real invoice.paid delivery reaches your app. The sandbox guide covers underpaid and expired cases too.
Branch on e.code, never on the message text; the errors post sorts every code into retry or fix. The fee is a flat 0.5% of each confirmed payment, see pricing. The same integration in other languages: Python, PHP, Node.js, Go, Java and Rust; every endpoint is in the API docs.