# Add e-signatures and clickwrap to Ruby

> Add e-signatures and clickwrap to plain Ruby with Net::HTTP: POST /v1/sessions, GET /v1/records, a cookie signed with OpenSSL and Puma. No gem for the API.

Source: https://esigncomply.com/ruby

Stack · Ruby

To add e-signatures and clickwrap to Ruby, call the REST API with `Net::HTTP`: there is no gem, because the server SDK exists for Node.js only. One Rack app with no framework creates the session with the secret key, keeps the pinned versions in a cookie signed with OpenSSL, and confirms the record. Esign Comply seals each acceptance.

Follow the quickstart and each signature is a valid electronic signature under the U.S. ESIGN Act, state UETA laws and New York's ESRA, and each clickwrap is built the way courts require: clear notice of the terms, an unmistakable act of assent, and a sealed record of both.

[Get an API key](https://esigncomply.com/signup) · [Read the docs](https://esigncomply.com/docs/quickstart/ruby)

No gem for the API: Net::HTTP is enough. Puma is the one gem, as the web server

[Ruby quickstart](https://esigncomply.com/docs/quickstart/ruby)

Free plan: 10 live signatures a month and a full test mode. No card required.

Last updated November 26, 2026

Run in Ruby before publishing

**The API call**

app.rb (excerpt)

```ruby
# One call to the Esign Comply API. Returns [status, parsed JSON]. JSON.parse gives string keys: record["status"].
def esc(method, path, body: nil, idempotency_key: nil)
  uri = URI("#{API}#{path}")
  request = (method == :post ? Net::HTTP::Post : Net::HTTP::Get).new(uri)
  request["Authorization"] = "Bearer #{API_KEY}"
  request["Idempotency-Key"] = idempotency_key if idempotency_key
  if body
    request["Content-Type"] = "application/json"
    request.body = JSON.generate(body)
  end
  # use_ssl turns certificate verification on. The timeouts are 60 seconds each unless set, and max_retries is 1:
  # Net::HTTP would send a GET a second time by itself after a timeout.
  options = { use_ssl: uri.scheme == "https", open_timeout: 5, read_timeout: 10, max_retries: 0 }
  response = nil
  3.times do |attempt|
    # Net::HTTP does not raise on 4xx and 5xx: the status is here, and the error envelope is the body.
    response = Net::HTTP.start(uri.host, uri.port, **options) { |http| http.request(request) }
    # Over the rate limit: wait for Retry-After (1 to 5 seconds) and try again, twice at most. Nothing else is retried.
    break unless response.code == "429" && attempt < 2
    sleep response["Retry-After"].to_f.clamp(1, 5)
  end
  [response.code.to_i, JSON.parse(response.body)]
end
```

**Create the session**

app.rb (excerpt)

```ruby
# Step 4: create the session with the secret key. The browser gets the client token only.
def ceremony(env)
  # The page that runs the ceremony: the origin the browser reports, or the scheme and host of the request.
  origin = env["HTTP_ORIGIN"] || "#{env['rack.url_scheme']}://#{env['HTTP_HOST']}"
  status, created = esc(:post, "/sessions",
    idempotency_key: "signup-#{SIGNER[:external_id]}-#{SecureRandom.uuid}",
    body: {
      profile: PROFILE,
      signer: SIGNER,
      documents: [
        { document: DOCUMENTS["terms"], version: "current" },
        { document: DOCUMENTS["privacy"], version: "current" }
      ],
      context: { url: "#{origin}/signup", locale: "en-US", purpose: "account_signup" }
    })
  return reply(502, error: created.dig("error", "code") || "unknown") unless status == 201

  pinned = { signer_id: SIGNER[:external_id], version_ids: created["documents"].map { |d| d["version_id"] }.sort }
  reply(200, { clientToken: created["client_token"], apiUrl: created["api_url"], documents: created["documents"] },
    "set-cookie" => pinned_cookie(pinned))
end
```

**Confirm**

app.rb (excerpt)

```ruby
# Step 6: confirm the record with the secret key before the account exists.
def confirm(env)
  body = JSON.parse(env["rack.input"].read) rescue nil # an empty or malformed body is refused below
  record_id = body.is_a?(Hash) && body["recordId"].is_a?(String) ? body["recordId"] : "missing"
  expected = pinned(env)
  status, record = esc(:get, "/records/#{ERB::Util.url_encode(record_id)}")

  confirmed = status == 200 &&
              SEALED.include?(record["status"]) &&
              record["livemode"] == LIVE &&
              !expected["signer_id"].nil? && record.dig("signer", "external_id") == expected["signer_id"] &&
              record["documents"].map { |d| d["version_id"] }.sort == expected["version_ids"]

  warn(confirmed ? "confirmed #{record['id']} (#{record['status']})" : "refused")
  return reply(409, confirmed: false) unless confirmed

  # Only now create the account, and store record["id"] and record["receipt"] with it.
  reply(200, confirmed: true, recordId: record["id"])
end
```

**Signed cookie**

app.rb (excerpt)

```ruby
# Server-owned state: a cookie this file signs with HMAC-SHA256. The visitor can read it and cannot change it.
def sign(payload)
  OpenSSL::HMAC.hexdigest("SHA256", COOKIE_SECRET, payload)
end

def pinned_cookie(pinned)
  payload = [JSON.generate(pinned)].pack("m0") # Base64 without the base64 gem
  "esc_signup=#{payload}.#{sign(payload)}; Path=/; HttpOnly; SameSite=Lax#{'; Secure' if LIVE}"
end

def pinned(env)
  cookie = env["HTTP_COOKIE"].to_s[/(?:\A|;\s*)esc_signup=([^;]*)/, 1].to_s
  payload, _, signature = cookie.rpartition(".")
  # Compared in constant time. A cookie that fails is the same as no cookie.
  return {} unless OpenSSL.secure_compare(sign(payload), signature)
  JSON.parse(payload.unpack1("m0"))
end
```

Integrate with Ruby

## How do you integrate Esign Comply with Ruby?

In plain Ruby the integration is one `app.rb`: an object that answers `call(env)`, which Puma runs from `config.ru` with no framework and no `rack` gem. `Net::HTTP`, `JSON` and `OpenSSL` come with Ruby. The pinned versions travel in a cookie the app signs with HMAC-SHA256, so nothing sits in memory and a restart loses nothing.

The Ruby 3.0.0 release notes say of webrick and three other libraries: The following libraries are no longer bundled gems or standard libraries. Install the corresponding gems to use these features.

Source: [Ruby 3.0.0 release notes](https://www.ruby-lang.org/en/news/2020/12/25/ruby-3-0-0-released/), read on November 26, 2026.

[Ruby quickstart](https://esigncomply.com/docs/quickstart/ruby) · [All stacks](https://esigncomply.com/stacks)

Where each part lives in Ruby

- **The API call** · `app.rb`
- **Create the session** · `app.rb`
- **Confirm** · `app.rb`
- **Signed cookie** · `app.rb`

Run on 2026-11-26 with Ruby 3.4.13 (the official Ruby container image) and the net-http 0.6.0, json 2.9.1 and openssl 3.3.3 it ships, with no framework and no rack gem, under Puma 8.1.3 with nio4r 2.7.5 from config.ru, in development and with RACK_ENV=production, with the browser SDK script build and the conformance check from esigncomply 1.0.4, against the API in test mode.

Copy-paste prompt

## What prompt adds Esign Comply clickwrap to a Ruby app?

Paste this into Cursor, Claude Code or the AI coding tool that is open on your project. It names the packages that exist, where the secret key goes in Ruby, what to build and what never to do, and it ends with the rules block for your project.

The rules block lives at [/rules.md](https://esigncomply.com/rules.md). Added to your project's instruction file, it makes every later session build signing and acceptance flows the same way. The [prompt generator](https://esigncomply.com/product/prompt-generator) writes the long version, with your own document and profile IDs.

[Pages for each AI tool](https://esigncomply.com/build)

Prompt: Esign Comply clickwrap in Ruby

```ruby
Add Esign Comply clickwrap to my Ruby app: a signup form where the user accepts the Terms of Service and the Privacy Notice with a checkbox and a button.

Read these first and follow them exactly. If something conflicts with existing code, or you are unsure how to implement a step, stop and ask. Do not invent API methods, packages or legal wording.
- https://esigncomply.com/docs/quickstart/ruby.md (the steps and the tested code for Ruby)
- https://esigncomply.com/setup.md (the order of API calls)
- https://esigncomply.com/auth.md (how to handle the keys)

Ruby facts
- There is no Esign Comply gem. Do not install or invent one. The server calls the REST API at https://esigncomply.com/v1 with Net::HTTP, Authorization: Bearer and the secret key.
- The browser SDK is a script tag: https://esigncomply.com/sdk/v1/esigncomply.js. It defines the global EsignComply.
- The secret key is in the environment variable ESIGNCOMPLY_API_KEY. Ruby does not read .env files on its own. Never print the key.
- Ruby has shipped no web server since 3.0. Use the server the project already has. The quickstart is one object that answers call(env), run by Puma from config.ru, with no framework and no rack gem.
- Net::HTTP: pass use_ssl for an https address (it turns certificate verification on, never set VERIFY_NONE), set open_timeout and read_timeout (each is 60 seconds otherwise), and set max_retries to 0 (otherwise it sends a GET a second time after a timeout). It does not raise on 4xx and 5xx: read the status and the error envelope.
- JSON.parse returns string keys: record["status"], never record[:status].
- Keep the signer ID and the pinned version IDs in a cookie signed with OpenSSL::HMAC, and compare the signature with OpenSSL.secure_compare. The visitor can read a signed cookie: put nothing secret in it. Do not require "base64" unless the Gemfile lists it: pack("m0") does the same.
- String interpolation escapes nothing. Print the document HTML as it is, and escape everything else you print with ERB::Util.html_escape.
- The page is on screen before the script has a session: render the checkbox disabled and enable it when observeAssent has resolved.

Build
1. Verify the key: GET /v1/usage with ESIGNCOMPLY_API_KEY. Stop if it fails.
2. Register the Terms of Service and the Privacy Notice as documents and publish one version of each from the documents in this project. If the project has none, register short sample documents and say so in your report. Never write or change the wording of the real documents. Create a profile: jurisdictions ["US-FED"], method "checkbox", assurance_level "L1".
3. Server: POST /api/ceremony calls POST /v1/sessions with an Idempotency-Key, saves the signer ID and the pinned version IDs in the signed cookie, and returns only clientToken, apiUrl and documents.
4. Server: GET /legal/terms and /legal/privacy render the html from GET /v1/documents/{id}/versions/{version_id}/content inside <article data-esc-document>, unmodified.
5. Browser: EsignComply.attach({ clientToken, apiUrl }), presentDocument for each link, observeAssent({ region, checkbox, submit }), then complete() from the user's real click.
6. Server: POST /api/signup/confirm calls GET /v1/records/{id} and requires: status is "recorded", "timestamped" or "anchored"; livemode is as expected; the signer ID and version IDs equal the ones in the signed cookie. Only then create the account.

Never
- Never pre-check the box, auto-submit, or call .click() on the user's behalf.
- Never use "By continuing" or "By clicking below" wording. The notice names the button by its label and each document by its registered name.
- Never put the secret key, or any call that uses it, in code that reaches the browser.
- Never show "signed" or "accepted" before the server has confirmed the record.
- Never fall back to an acceptance with no record when a session is refused.

Check before you report success
- Run: npx esigncomply check --url http://localhost:9292/signup --callback http://localhost:9292/api/signup/confirm
  Fix every finding marked "block". List every finding marked "warn".
- Report the files you created or changed, anything you did not implement and why, and the conformance summary.

Then add the rules block to this project's instruction file: https://esigncomply.com/rules.md
```

3 things to watch

## What goes wrong when you add e-signatures in Ruby?

These are specific to Ruby. Each one was seen while the quickstart's code was run, or is in Ruby's own documentation.

- **Net::HTTP sends a GET a second time after a timeout**

  Ruby's documentation gives `max_retries` an initial value of 1 and each timeout an initial value of 60 seconds. In the test on Ruby 3.4.13, against a server that never answered, a `GET` with `read_timeout` at 2 seconds failed after 4.01 seconds and had been received twice. With `max_retries: 0` it failed after 2.0 seconds and was received once. The quickstart sets both timeouts and `max_retries: 0`.

  Source: [Ruby documentation, Net::HTTP](https://docs.ruby-lang.org/en/3.4/Net/HTTP.html), read on November 26, 2026.

- **A cookie you sign yourself can be read by the visitor**

  The quickstart signs its cookie with `OpenSSL::HMAC` and does not encrypt it. In the test the `esc_signup` cookie, decoded from Base64, showed the signer ID and both version IDs. A changed signature, a signature cut short and a changed payload were each answered `409`. Ruby's documentation says `OpenSSL.fixed_length_secure_compare` raises `ArgumentError` when the lengths differ, and it did for the cut one, so the code calls `OpenSSL.secure_compare`.

  Source: [Ruby documentation, OpenSSL](https://docs.ruby-lang.org/en/3.4/OpenSSL.html), read on November 26, 2026.

- **Puma prints the backtrace of an exception into the response in development**

  A plain Rack app has no framework to catch an exception. In the test on Puma 8.1.3 an app that raised was answered `500` with `Puma caught this error: boom in the app (RuntimeError)` and the backtrace in the body. With `RACK_ENV=production` the body was empty. The quickstart ends its app with a `rescue` that answers `500` as JSON and logs the error.

## Where are the Ruby quickstart and the API reference?

Start with the quickstart: it carries every file this page excerpts, in the order you write them.

- Quickstart

  **[Ruby quickstart](https://esigncomply.com/docs/quickstart/ruby)**

  Step by step, from install to your first sealed test record, with every file and the output of each step.

- Reference

  **[API reference](https://esigncomply.com/docs/api)**

  Every endpoint, field and error code. Sessions, records and documents are the three this page uses.

- Guide

  **[Server confirmation](https://esigncomply.com/docs/guides/server-confirmation)**

  The one place access is granted: what to compare, and the webhook that backs the check up.

Verifiable

## What does Esign Comply record for a signature in Ruby?

The same record on every stack and platform. Your Ruby code creates the session and confirms the record, and the browser SDK reports what happened on the page. Esign Comply seals the result where your code cannot change it. The record itself is described on [Evidence and verification](https://esigncomply.com/product/evidence).

- **Observed and asserted fields**

  Every field is tagged. Observed is what the browser SDK and the API saw: the box unchecked at load, the tick from a trusted user event, the notice text, the terms version by hash, the server time. Asserted is what your app said, such as the user's email.

- **A signed receipt**

  `complete()` returns a receipt signed with ES256, using keys you do not hold. Your server stores it next to the user, and `GET /v1/records/{id}/receipt` returns it again.

- **An external timestamp**

  An outside authority timestamps the hash of every live record (RFC 3161), so the time on the record does not rest on your clock or on ours.

- **An offline verifier**

  Each record has an evidence report (PDF) and an evidence package (ZIP). Anyone you send the package to checks the acceptance with the open-source `esigncomply-verify`, without an account.

[How sealing and verification work](https://esigncomply.com/product/evidence) · [Observed and asserted, in the docs](https://esigncomply.com/docs/concepts/observed-and-asserted) · [The offline verifier](https://esigncomply.com/docs/sdk/verify)

Record

`rec_Z4m8`

simple · L1

Recorded

Written durably, receipt signed with ES256

Timestamped

External RFC 3161 token over the record hash

Anchored

Public anchor pending

Checkbox changed by a trusted user event · observed

Terms of Service, version dv_3kT9 · observed

Server time 2026-11-21T15:03:20.291Z · observed

Signer email dana@example.org · asserted

record_hash sha256:5be7… · example record

## Questions about e-signatures in Ruby

### Is there an Esign Comply SDK for Ruby?

No. There is no gem, because the server SDK exists for Node.js only. A Ruby server calls the REST API directly with the secret key, and the quickstart does it with `Net::HTTP` in one method. The Gemfile lists Puma, the web server, and nothing for the API.

### Where do I create the session in Ruby?

In the method `ceremony`, which the app calls for `POST /api/ceremony`, with a `POST` to `/v1/sessions` that carries the secret key and an `Idempotency-Key`. It puts the pinned versions in the signed cookie and returns only the client token, the API URL and the documents.

### Which web server runs plain Ruby now that WEBrick is gone?

Puma, in the quickstart. Ruby's 3.0.0 release notes list `webrick` among the libraries that are no longer bundled, and WEBrick's README says it is not intended for production use or for traffic from untrusted sources. In the test Puma 8.1.3 ran `config.ru` with no framework and no `rack` gem installed.

### Why does require "base64" fail under Bundler?

Because base64 stopped being a default gem in Ruby 3.4. In the test on Ruby 3.4.13, with a Gemfile that lists only Puma, the line ended with `LoadError: cannot load such file -- base64`. The quickstart encodes its cookie with `pack("m0")` from Ruby's core, so the Gemfile stays at one gem.

### When should I use Sinatra or Rails instead of plain Ruby?

When your app already runs on one of them, or needs what they bring: routing, templates and a session. Their pages show the same two API calls inside the framework. Plain Ruby fits a Rack app with no framework or a small service, where four routes do not justify one.

### Other stacks

- [Sinatra](https://esigncomply.com/sinatra)
- [Rails](https://esigncomply.com/rails)
- [Python](https://esigncomply.com/python)

### Platforms used with Ruby

- [Railway](https://esigncomply.com/railway)
- [Render](https://esigncomply.com/render)
- [Fly.io](https://esigncomply.com/fly-io)

[All stacks](https://esigncomply.com/stacks) · [All platforms](https://esigncomply.com/platforms) · [Clickwrap API](https://esigncomply.com/clickwrap) · [E-signature API](https://esigncomply.com/sign)

## Call the API from the Ruby you already run. Leave the record to us.

[Get an API key](https://esigncomply.com/signup) · [Read the docs](https://esigncomply.com/docs/quickstart/ruby)

Free plan: 10 live signatures a month and a full test mode. No card required.

Ruby is a trademark of its owner. Esign Comply is not affiliated with it. What this page says about Ruby is from Ruby's documentation or from a test run, as marked, on November 26, 2026. `/ruby.md` is this page as Markdown.

---

Every page on esigncomply.com has a Markdown version at the same URL plus `.md` (the home page is `https://esigncomply.com/index.md`). https://esigncomply.com/llms.txt lists them.

---

Esign Comply is the e-signature API and clickwrap API for developers who build their own signing flow in their own UI: it supplies the ceremony rules as a generated prompt for AI coding tools, records events in direct browser ceremonies, and seals independent, verifiable evidence.
