Docs
Checking Raims account
Integrations

Ruby SDK

Install the official Ruby SDK from RubyGems and connect your backend to the public API.

The official Ruby SDK connects server applications to the Raims public API. It provides resource services, typed responses, cursor pagination, and webhook verification. Keep the API key in your backend, outside code distributed to customers and routine logs.

The SDK reference lists each resource's methods and parameters.

Install the SDK

Use Ruby 3.3 or later. The raims gem is on RubyGems. Choose how your application manages gems:

gem install raims

Keep the application’s Gemfile.lock when using Bundler. Both paths load the SDK with require 'raims'.

Configure the client

  1. Prepare the credential

    Obtain a credential through API keys and store it in RAIMS_API_KEY or your application's secret store. The key determines company, environment, and permissions. Sandbox and Production use https://api.raims.com.

    For this first read, use a Sandbox key with View customers permission. The request only reads one page; it does not create customers or request emails.

  2. Save the read example

    With Bundler, run bundle exec ruby read_customers.rb to use the versions in Gemfile.lock.

    read_customers.rb
    Ruby
    require 'raims'
    
    raims = Raims::RaimsClient.new(ENV.fetch('RAIMS_API_KEY'))
    begin
      customers = raims.customers.list({page_size: 10})
      puts "HTTP status: #{customers.last_response.status_code}; items: #{customers.list.length}"
    rescue Raims::ApiError => error
      warn "HTTP status: #{error.http_status}; code: #{error.code}; Request-Id: #{error.request_id}"
      exit 1
    rescue Raims::ConnectionError
      warn 'Read failed before a conclusive response. Check the connection.'
      exit 1
    ensure
      raims.close
    end
  3. Run and check the result

    From the project directory, with RAIMS_API_KEY available to the process, run:

    Shell
    ruby read_customers.rb

    A successful read prints HTTP status: 200 and the number of items in this page. items: 0 is a valid empty result for the key’s company and environment. It is not an authentication failure.

What to check

The SDK reads the list and page envelope below. In an empty page, has_next: false means there is no next page. A nonempty page also returns customer records; the program prints only their count.

HTTP 200 response example excerptGET /v1/customers

No customers found

JSON
{
  "list": [],
  "page": {
    "page_size": 10,
    "has_next": false,
    "has_previous": false,
    "next_after": null,
    "previous_before": null
  }
}

Reuse the client and close it when finished. RaimsClient.open with a block also guarantees closure. The following snippets assume an open raims instance. Timeouts use seconds; read retries are disabled by default.

Create a customer and a charge

This is a backend snippet, after loading the order from your application’s storage. Keep the customer key separate from the charge key. Save the entire request payload, including the amount and title, before sending; read it again on retries instead of generating new values.

Input from the saved orderSource and purpose
customer_tax_idCustomer tax ID already authorized and saved by your application.
customer_keyIdempotency key for creating this customer; saved before the first request.
charge_keyA different idempotency key for this charge; saved with the order.
due_date_unixChosen due date, saved in UTC Unix seconds.
Ruby
customer = raims.customers.create(
  {tax_id: customer_tax_id},
  {idempotency_key: customer_key}
)

charge = raims.charges.create(
  {customer_id: customer.id, amount_cents: 15000,
   due_date: due_date_unix, title: 'Pedido 1234'},
  {idempotency_key: charge_key}
)

charge_id = charge.id
pending = charge.last_response.status_code == 202

If the CPF or CNPJ already exists in the same company and environment, the customer record is updated and keeps its ID.

Persist the returned customer ID and charge ID on the order before returning success to your caller. The charge ID is the value used to resume the read below; the SDK variables are not durable storage.

ResultWhat to do next
HTTP 201The charge was created. Save its ID; creation does not confirm payment. This snippet does not request email or payment issuance.
HTTP 202 in a creation that requests payment issuanceSave the same returned ID and keep the order pending. Retrieve that charge; do not create another one to resolve the pending result.
Error or missing responseHandle the structured error. If execution is uncertain, keep the intent and reconcile before retrying with the original key and payload.

The canonical creation example below shows only the ID and status fields:

HTTP 201 response example excerptPOST /v1/charges

Charge without a link or email request

JSON
{
  "id": "ch_1Q2W3E4R5T6Y7U8I9O0P",
  "status": 0
}

15000 represents BRL 150.00. Inputs use hashes with JSON field names; omitted fields remain absent and nil sends JSON null where allowed. For example, raims.customers.update(customer.id, {external_reference: nil}) clears that reference; omission preserves its value. Responses expose readers such as customer.id; use key? to distinguish absence from null.

Pagination and pending results

The following backend snippet counts at most 100 customers across pages, without logging their records. Keep the configured client open during iteration.

Ruby
page = raims.customers.list({page_size: 50})
visited = 0
page.auto_paging_each do |customer|
  visited += 1
  break if visited == 100
end
puts "Items visited: #{visited}"

Items visited: 0 means the query found no customers. 100 means the chosen limit was reached; it does not prove there are no more records. A page error interrupts the count. Save progress only after processing a complete page if your job must resume later.

each visits only the received page; auto_paging_each fetches subsequent pages and preserves filters and options. next_page and previous_page return another page or nil. Do not combine after and before or interpret cursor contents.

HTTP 202 keeps the result pending. It does not confirm payment and the SDK does not start polling. When resuming the saved order, load charge_id from storage and retrieve that same charge once:

Ruby
current = raims.charges.retrieve(charge_id)
puts "HTTP status: #{current.last_response.status_code}; charge status: #{current.status}"

HTTP 200 here confirms that the read succeeded. Interpret the returned status and payment_information using the charge reference; a successful GET does not mean the charge was paid or that issuance completed. If issuance is still pending, keep the same ID. Repeated reads do not speed up processing or issue another payment; contact support if the condition persists.

Idempotency and errors

Ruby
begin
  page = raims.customers.list({page_size: 10})
  puts "HTTP status: #{page.last_response.status_code}; items: #{page.list.length}"
rescue Raims::ApiError => error
  warn "HTTP status: #{error.http_status}; code: #{error.code}; Request-Id: #{error.request_id}"
  error.details&.each do |detail|
    warn "field: #{detail['field']}; code: #{detail['code']}"
  end
rescue Raims::ConnectionError
  warn 'No conclusive response. Reconcile any uncertain write before retrying.'
end

Use error.code to decide how to handle an API error, alongside the HTTP status and error.request_id. error.api_message contains the API's diagnostic text; error.message and error.inspect use a generic representation of the failure. Do not use message text to control the integration.

error.details returns the API's details array, or nil when the field is absent or is not an array. Read the string keys detail['field'] and detail['code'] from each validation detail, as shown above. ArgumentError identifies invalid local arguments. Do not log credentials, complete bodies, or temporary access links.

The SDK does not generate idempotency keys or retry writes automatically. After a lost response, retrieve the resource and, when the endpoint permits retrying the request, reuse the original key and parameters. Configure max_network_retries on the client or request options for eligible GET/HEAD read retries only. The default is zero; Retry-After follows the SDK's bounded wait policy. See Idempotency.

For example, if the read above returns HTTP 403 with API_KEY_PERMISSION_DENIED, the key lacks access to list customers. Enable View customers on the appropriate key and retry the read. Repeating it with the same permissions will not resolve that error.

Check HTTP response codes for other failures.

For an uncertain write, recover the saved key and the entire original payload. If the charge ID was received, retrieve that ID first. Within the idempotency retention period, a compatible retry can return the preserved result, including a pending 202. A key with different parameters can be rejected; do not change the due date or create a new key to bypass the uncertainty. After retention expires, reconcile before another write.

Use Sandbox

Use a Sandbox key and a charge belonging to that environment:

Ruby
Raims::RaimsClient.open(ENV.fetch('RAIMS_SANDBOX_API_KEY')) do |sandbox|
  result = sandbox.simulations.charges.confirm_payment(sandbox_charge_id)
end

The SDK does not turn a Production key into Sandbox or offer an environment selector. See the conditions under Simulations. Email requests and webhook deliveries may reach external destinations even in Sandbox; use authorized destinations.

Receive webhooks

Preserve raw_body, the string containing the original bytes received by your server, and signing_headers, the hash containing webhook-id, webhook-timestamp, and webhook-signature. Preserve repeated occurrences so ambiguity can be rejected.

Ruby
begin
  event = Raims::Webhook.construct_event(
    raw_body, signing_headers, ENV.fetch('RAIMS_WEBHOOK_SECRET')
  )
  persist_event(event)
rescue Raims::SignatureVerificationError
  reject_delivery
end

persist_event and reject_delivery belong to your application. RAIMS_WEBHOOK_SECRET contains the webhook's secret_key, not the API key. Do not reserialize JSON before verification. Do not process an invalid event.

The default tolerance is 300 seconds; keep the server clock synchronized. A valid signature does not prevent redelivery: check type and environment, deduplicate the event id, and store the work durably before returning success. webhook-id identifies the delivery. See Receive events.

Update the SDK

For applications using Bundler, update the gem and its dependencies within the constraints declared in Gemfile:

Shell
bundle update raims

Review and keep the updated Gemfile.lock. For an installation managed directly through RubyGems, use:

Shell
gem update raims

If Gemfile used source downloaded from GitHub, replace its path: or git: declaration with gem 'raims', using https://rubygems.org as the source, and run bundle update raims. The require 'raims' statement stays the same.

Read the version history and test the flows used by your integration before updating the application. Installation does not enable automatic future updates.