# Clickwrap agreement in Rails

> Clickwrap agreement in Rails with working code: a Net::HTTP client, the signup view, server confirmation, the migration and a signed webhook. No gem needed.

Source: https://esigncomply.com/guides/rails-clickwrap

Stack guide · Rails

Eight files put a terms and privacy checkbox on your Rails signup, call the Esign Comply API with `Net::HTTP`, and create the user only after the acceptance is confirmed as a sealed record.

[Get started](https://esigncomply.com/signup) · [Read the quickstart](https://esigncomply.com/docs/quickstart)

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

8 files · copy and run

## The working code: a signup clickwrap in Rails

Plain Rails: a service object, four small controllers, one ERB view and a migration. There is no gem to add and nothing to configure beyond five environment variables.

**API client**

`app/services/esign_comply.rb`

```ruby
# app/services/esign_comply.rb
require "net/http"

# The whole client. There is no gem to install: these are plain HTTPS calls with the secret key.
module EsignComply
  API = ENV.fetch("ESIGNCOMPLY_API_URL", "https://esigncomply.com/v1")
  SEALED = %w[recorded timestamped anchored].freeze

  class Error < StandardError; end

  # POST /v1/sessions. The response carries client_token, api_url and the pinned documents.
  def self.create_session(signer:, url:)
    call(:post, "/sessions", idempotency_key: "signup-#{signer[:external_id]}", body: {
      profile: ENV.fetch("ESIGNCOMPLY_PROFILE_ID"),
      signer: signer,
      documents: [
        { document: ENV.fetch("ESIGNCOMPLY_TERMS_ID"), version: "current" },
        { document: ENV.fetch("ESIGNCOMPLY_PRIVACY_ID"), version: "current" }
      ],
      context: { url: url, locale: "en-US", purpose: "account_signup" }
    })
  end

  # GET /v1/records/{id}
  def self.get_record(record_id)
    call(:get, "/records/#{ERB::Util.url_encode(record_id)}")
  end

  # GET /v1/documents/{id}/versions/{version_id}/content
  def self.get_document_content(document_id, version_id)
    call(:get, "/documents/#{document_id}/versions/#{ERB::Util.url_encode(version_id)}/content")
  end

  # Server confirmation: read the record with the secret key and compare it with
  # what this server saved when it created the session.
  def self.confirm_record(record_id, acceptance)
    record = get_record(record_id)
    confirmed = SEALED.include?(record["status"]) &&
                record["livemode"] == Rails.env.production? &&
                record.dig("signer", "external_id") == acceptance.signer_id &&
                record["documents"].map { |d| d["version_id"] }.sort == acceptance.document_version_ids.sort
    record if confirmed
  rescue Error
    nil # a made-up ID, a record from the other environment, or the API could not be reached
  end

  def self.call(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 #{ENV.fetch('ESIGNCOMPLY_API_KEY')}"
    request["Idempotency-Key"] = idempotency_key if idempotency_key
    if body
      request["Content-Type"] = "application/json"
      request.body = body.to_json
    end

    response = nil
    3.times do
      response = Net::HTTP.start(uri.host, uri.port, use_ssl: uri.scheme == "https", open_timeout: 5, read_timeout: 10) do |http|
        http.request(request)
      end
      break unless response.code == "429"
      sleep 1 # rate limited: the window is one second (the Free plan allows 2 requests per second)
    end
    raise Error, "#{response.code} #{response.body}" unless response.is_a?(Net::HTTPSuccess)
    JSON.parse(response.body)
  rescue SocketError, SystemCallError, Timeout::Error, OpenSSL::SSL::SSLError => e
    raise Error, e.message
  end
  private_class_method :call
end
```

**Session endpoint**

`app/controllers/signup_ceremonies_controller.rb`

```ruby
# app/controllers/signup_ceremonies_controller.rb
# POST /signup/ceremony creates the session and returns only the client token.
class SignupCeremoniesController < ApplicationController
  def create
    country = params.require(:country).upcase
    # Your identifier for this person. Keep using it for them in later sessions.
    signer = { external_id: SecureRandom.uuid, email: params.require(:email), class: "consumer", country: country }
    signer[:region] = "US-#{params[:state].upcase}" if country == "US" && params[:state].present?

    ceremony = EsignComply.create_session(signer: signer, url: signup_url)

    # Server-owned state: the signer and the versions this session pinned.
    Acceptance.create!(
      signer_id: signer[:external_id],
      session_id: ceremony["id"],
      document_version_ids: ceremony["documents"].map { |d| d["version_id"] }
    )
    session[:esign_session_id] = ceremony["id"]

    # Only these go to the browser. Never the key, never the whole session.
    render json: {
      clientToken: ceremony["client_token"],
      apiUrl: ceremony["api_url"],
      documents: ceremony["documents"]
    }
  rescue EsignComply::Error
    render json: { error: "ceremony_unavailable" }, status: :bad_gateway
  end
end
```

**Signup form**

`app/views/registrations/new.html.erb`

```erb
<%# app/views/registrations/new.html.erb %>
<style>
  #assent a { color: #2563eb; text-decoration: underline; }
</style>

<form id="signup" action="<%= signup_path %>" method="post" data-turbo="false">
  <%= hidden_field_tag :authenticity_token, form_authenticity_token %>
  <label>Email <input name="email" type="email" autocomplete="email" required data-signer></label>
  <label>Country <input name="country" value="US" maxlength="2" required data-signer></label>
  <label>State <input name="state" placeholder="CA" maxlength="2" data-signer></label>
  <label>Password <input name="password" type="password" autocomplete="new-password" minlength="12" required></label>

  <div id="assent">
    <input id="agree" type="checkbox" disabled>
    <label for="agree">
      By checking the box and clicking Create account, you agree to the
      <a id="tos-link" href="<%= legal_path("terms") %>" target="_blank" rel="noopener">Terms of Service</a>
      and acknowledge the
      <a id="privacy-link" href="<%= legal_path("privacy") %>" target="_blank" rel="noopener">Privacy Notice</a>.
    </label>
    <p><button id="create-account" type="submit" disabled>Create account</button></p>
    <p>Acme uses Esign Comply to record this event on its behalf. See Acme's Privacy Notice for purposes and roles.</p>
  </div>
  <p id="message" role="alert"></p>
</form>

<script src="https://esigncomply.com/sdk/v1/esigncomply.js"></script>
<script type="module">
  const form = document.querySelector("#signup");
  const fields = form.elements;
  const agree = document.querySelector("#agree");
  const submit = document.querySelector("#create-account");
  const message = document.querySelector("#message");
  const tosLink = document.querySelector("#tos-link");
  const privacyLink = document.querySelector("#privacy-link");
  const INCONCLUSIVE = "We could not confirm whether your acceptance was recorded. Please wait while we check.";
  let ceremony = null;
  let startedFor = null; // the signer details the current session was created with
  let run = 0;
  let timer;
  const details = () => JSON.stringify([fields.email.value, fields.country.value, fields.state.value]);

  // A session belongs to the signer details it was created with. Without one, the box stays disabled.
  function drop() {
    run += 1; // a start that is still in flight is ignored
    if (ceremony) ceremony.destroy();
    ceremony = null;
    startedFor = null;
    agree.checked = false; // a new session must find the box unchecked
    agree.disabled = submit.disabled = true;
    message.textContent = "";
  }

  async function start() {
    clearTimeout(timer);
    if (startedFor === details()) return; // a session for these details exists or is on its way
    drop();
    if (!fields.email.value || !fields.email.checkValidity()) return;
    startedFor = details();
    const current = run;

    try {
      // Your server creates the session with the secret key and returns only the client token.
      const response = await fetch("<%= signup_ceremony_path %>", {
        method: "POST",
        headers: { "Content-Type": "application/json", "X-CSRF-Token": fields.authenticity_token.value },
        body: JSON.stringify({ email: fields.email.value, country: fields.country.value, state: fields.state.value }),
      });
      if (!response.ok) throw new Error("We could not start the signup. Reload the page to try again.");
      const { clientToken, apiUrl, documents } = await response.json();
      if (current !== run) return; // a field changed while the request was in flight

      const attached = await EsignComply.attach({ clientToken, apiUrl });
      if (current !== run) return attached.destroy();
      ceremony = attached;
      ceremony.on("change", ({ remainingSteps }) => {
        submit.disabled = remainingSteps.some((step) => step !== "signature.applied");
      });
      ceremony.on("expired", () => {
        drop();
        start();
      });

      // Point each link at the exact version this session pinned, then report it.
      const [terms, privacy] = documents;
      tosLink.search = "?v=" + terms.version_id;
      privacyLink.search = "?v=" + privacy.version_id;
      await ceremony.presentDocument({ versionId: terms.version_id, mode: "hyperlink", link: tosLink });
      await ceremony.presentDocument({ versionId: privacy.version_id, mode: "hyperlink", link: privacyLink });

      // The region holds the notice, the links, the checkbox and the button.
      await ceremony.observeAssent({ region: document.querySelector("#assent"), checkbox: agree, submit });
      agree.disabled = false; // the box can be ticked only while the SDK is watching it
    } catch (error) {
      if (current === run) message.textContent = error.message;
    }
  }

  // When a signer field changes, drop the session at once. Start a new one when the
  // field is left, or when the typing stops.
  form.addEventListener("input", (event) => {
    if (!event.target.matches("[data-signer]")) return;
    drop();
    clearTimeout(timer);
    if (event.target !== fields.email) timer = setTimeout(start, 800); // an email is finished when its field is left
  });
  form.addEventListener("change", (event) => {
    if (event.target.matches("[data-signer]")) start();
  });
  start();

  form.addEventListener("submit", async (event) => {
    event.preventDefault();
    if (!ceremony) return;
    message.textContent = "";
    try {
      const result = await ceremony.complete(); // the signing act: { recordId, receipt, verifyUrl, status }
      const body = new FormData(form);
      body.set("record_id", result.recordId);
      // Your server confirms the record with the secret key before it creates the account.
      const finished = await fetch(form.action, { method: "POST", body, headers: { Accept: "application/json" } });
      if (!finished.ok) throw new Error("Not confirmed");
      location.assign("/");
    } catch (error) {
      // A refusal carries a message and a fix: keep the form. Anything else is inconclusive.
      const refused = error instanceof EsignComply.EsignComplyError && error.code !== "network_error" && error.status < 500;
      message.textContent = refused ? error.message : INCONCLUSIVE;
    }
  });
</script>
```

**Confirm and create**

`app/controllers/registrations_controller.rb`

```ruby
# app/controllers/registrations_controller.rb
class RegistrationsController < ApplicationController
  # GET /signup renders the form.
  def new; end

  # POST /signup confirms the record, then creates the account.
  def create
    acceptance = Acceptance.find_by(session_id: session[:esign_session_id], user_id: nil)
    record_id = params[:record_id].presence # from the browser: a claim to check
    record = EsignComply.confirm_record(record_id, acceptance) if acceptance && record_id
    # Not confirmed: no account. The browser shows the "could not confirm" message.
    return render json: { error: "not_confirmed" }, status: :conflict unless record

    user = User.create!(email: params.require(:email), password: params.require(:password))
    acceptance.update!(
      user_id: user.id,
      record_id: record["id"],
      receipt: record["receipt"],
      accepted_at: record["signed_at"]
    )
    reset_session
    session[:user_id] = user.id # or sign_in(user) with Devise
    render json: { ok: true }
  end
end
```

**Migration**

`db/migrate/20261122000000_create_acceptances.rb`

```ruby
# db/migrate/20261122000000_create_acceptances.rb
# The model is the plain class: app/models/acceptance.rb holds "class Acceptance < ApplicationRecord; end".
class CreateAcceptances < ActiveRecord::Migration[7.1]
  def change
    create_table :acceptances do |t|
      # Written when the session is created.
      t.string :signer_id, null: false           # signer.external_id sent to Esign Comply
      t.string :session_id, null: false          # ses_...
      t.json :document_version_ids, null: false  # ["dv_...", "dv_..."]: the versions the session pinned
      # Filled in once the record is confirmed.
      t.references :user, foreign_key: true      # null until the account exists
      t.string :record_id                        # rec_...
      t.text :receipt                            # signed receipt (JWS, ES256)
      t.datetime :accepted_at                    # the record's signed_at
      t.timestamps
    end
    add_index :acceptances, :session_id, unique: true
    add_index :acceptances, :record_id, unique: true
  end
end
```

**Document page**

`app/controllers/legal_controller.rb`

```ruby
# app/controllers/legal_controller.rb
# GET /legal/terms?v=dv_... serves one registered version, unmodified.
class LegalController < ApplicationController
  DOCUMENTS = { "terms" => "ESIGNCOMPLY_TERMS_ID", "privacy" => "ESIGNCOMPLY_PRIVACY_ID" }.freeze

  def show
    document_id = ENV.fetch(DOCUMENTS.fetch(params[:slug]))
    content = EsignComply.get_document_content(document_id, params[:v].presence || "current")
    # The registered HTML and nothing else inside the article: the SDK hashes its text.
    article = helpers.content_tag(:article, content["html"].html_safe, data: { esc_document: content["version_id"] })
    render html: article, layout: true
  rescue KeyError, EsignComply::Error
    head :not_found
  end
end
```

**Webhook**

`app/controllers/esign_webhooks_controller.rb`

```ruby
# app/controllers/esign_webhooks_controller.rb
# POST /webhooks/esigncomply
class EsignWebhooksController < ActionController::API
  def create
    payload = request.raw_post # the raw body: never parse and re-serialize before verifying
    return head :bad_request unless verified?(payload)

    event = JSON.parse(payload)
    # Deliveries are at-least-once. This only fills in a row that is still open, so a repeat changes nothing.
    if event["type"] == "record.completed"
      data = event["data"]
      acceptance = Acceptance.find_by(session_id: data["session_id"], record_id: nil)
      if acceptance &&
         event["livemode"] == Rails.env.production? &&
         data["signer_external_id"] == acceptance.signer_id &&
         data["documents"].map { |d| d["version_id"] }.sort == acceptance.document_version_ids.sort
        record = EsignComply.get_record(data["record_id"]) # the payload carries no receipt
        acceptance.update!(record_id: record["id"], receipt: record["receipt"], accepted_at: record["signed_at"])
      end
    end
    head :ok # also for event types this code does not know
  end

  private

  # Standard Webhooks: HMAC-SHA256 over "<webhook-id>.<webhook-timestamp>.<raw body>".
  def verified?(payload)
    id = request.headers["webhook-id"]
    timestamp = request.headers["webhook-timestamp"]
    signatures = request.headers["webhook-signature"]
    return false if id.blank? || timestamp.blank? || signatures.blank?
    return false if (Time.now.to_i - timestamp.to_i).abs > 300 # more than 5 minutes from now

    # The key is the base64-decoded part of the secret after "whsec_".
    key = Base64.decode64(ENV.fetch("ESIGNCOMPLY_WEBHOOK_SECRET").delete_prefix("whsec_"))
    expected = Base64.strict_encode64(OpenSSL::HMAC.digest("SHA256", key, "#{id}.#{timestamp}.#{payload}"))
    # The header can hold several space-separated "v1,<signature>" values while a secret is rotated.
    signatures.split(" ").any? do |part|
      version, value = part.split(",", 2)
      version == "v1" && value.present? && ActiveSupport::SecurityUtils.secure_compare(value, expected)
    end
  end
end
```

**Routes**

`config/routes.rb`

```ruby
# config/routes.rb
Rails.application.routes.draw do
  get  "signup", to: "registrations#new", as: :signup
  post "signup", to: "registrations#create"
  post "signup/ceremony", to: "signup_ceremonies#create", as: :signup_ceremony
  get  "legal/:slug", to: "legal#show", as: :legal
  post "webhooks/esigncomply", to: "esign_webhooks#create"
end
```

## What each file does

Eight files, four jobs: create the session on your server, collect the acceptance in your own view, confirm the record before `User.create!`, and keep the receipt next to the user.

### `esign_comply.rb`: the whole client, no gem

`app/services/esign_comply.rb`

There is no Esign Comply gem, and you do not need one. The server SDK is for Node, so Rails calls the REST API with `Net::HTTP`: `Authorization: Bearer` with your secret key on every request, and an `Idempotency-Key` on the `POST`. `create_session` is `POST /v1/sessions`, `get_record` is `GET /v1/records/{id}`, and `get_document_content` fetches one registered version of a document. Faraday works the same way if your app already uses it.

`confirm_record` is the check your signup depends on. It returns the record only when its status is `recorded`, `timestamped` or `anchored`, `livemode` equals `Rails.env.production?`, and the signer and the exact set of document versions equal what the `Acceptance` row holds. A `429` is retried after a second, because the Free plan allows 2 requests per second and one signup makes three calls close together.

### `SignupCeremoniesController`: create the session, return the client token

`app/controllers/signup_ceremonies_controller.rb`

The form posts the email, country and state here once the email is entered. The controller makes a signer ID, creates the session and saves an `Acceptance` row with the signer ID and the version IDs the session pinned. That row is the server-owned state the confirmation compares against later. The session ID goes into the Rails session.

The JSON response has three keys: the client token, the API URL and the pinned documents. The client token is short-lived and scoped to this one session, which is why it is safe in the browser and the secret key is not. Send the signer's country and state from your form, never from an IP address: the profile decides which rule packs apply.

### `new.html.erb`: your notice, your checkbox, your button

`app/views/registrations/new.html.erb`

Plain ERB and one script. The notice names the button and both documents, the links are underlined and coloured apart from the text around them, and the checkbox starts unchecked. It also starts disabled: the script enables it only after `observeAssent` is watching, so every tick is one the SDK saw happen.

The script loads the browser SDK from `https://esigncomply.com/sdk/v1/esigncomply.js`, asks your controller for a session and calls `EsignComply.attach` with the client token. `presentDocument` reports each link, `observeAssent` watches the container, and the `change` event opens the button when the signing act is the only step left. `complete()` runs from the real click, and the record ID is posted to `RegistrationsController#create` with the rest of the form. The form sets `data-turbo="false"`, so the script owns the submit.

### `RegistrationsController`: confirm first, then `User.create!`

`app/controllers/registrations_controller.rb`

The record ID in `params` came from the browser, so it is a claim. The action finds the open `Acceptance` row for this Rails session and asks `EsignComply.confirm_record` to check the claim against it. No row, no record or a mismatch returns `409`, the page tells the signer the acceptance could not be confirmed, and no account is created.

On a confirmed record the action creates the user and writes the user ID, the record ID, the signed receipt and the accepted time onto the row. `User.create!` assumes `has_secure_password`. With Devise, create the user the same way and call `sign_in(user)`.

### The migration: an `acceptances` table next to `users`

`db/migrate/20261122000000_create_acceptances.rb`

One row per ceremony. `signer_id`, `session_id` and `document_version_ids` are written when the session is created. `user_id`, `record_id`, `receipt` and `accepted_at` are filled in when the record is confirmed. The receipt is a compact signed token (ES256) that names the record hash: anyone you hand it to can check it against Esign Comply's published keys.

Keep the signer ID. It is your identifier for this person at Esign Comply, and a later session for the same user (an updated version of the terms, for example) sends the same value.

### `LegalController`: the registered version, unmodified

`app/controllers/legal_controller.rb`

`/legal/terms` and `/legal/privacy` render the version Esign Comply holds, fetched by the version ID in `?v=`. The HTML goes inside `<article data-esc-document>` with nothing else in it. When the form reports a link, the browser SDK reads this page, hashes the article's text and sends the hash, and the API compares it with the registered version (rule `CR-08`). You never paste legal text into a view, so the page and the record cannot drift apart.

### `EsignWebhooksController`: verify the signature, fill the open row

`app/controllers/esign_webhooks_controller.rb`

`record.completed` arrives once a record is sealed, including when the browser closed before your signup action ran. The controller reads `request.raw_post`, rejects a delivery whose timestamp is more than 5 minutes from now, and recomputes the signature: HMAC-SHA256 over `<webhook-id>.<webhook-timestamp>.<raw body>`, keyed with the base64-decoded part of the secret after `whsec_`. The comparison is constant-time.

It inherits from `ActionController::API`, so there is no CSRF check to skip: the signature is the authentication. Deliveries are at-least-once, and the handler only fills a row that is still open, so a repeat changes nothing.

### `routes.rb`: five routes

`config/routes.rb`

Two for the signup page, one for the session, one for the document pages and one for the webhook. `signup_url` is what the session declares as `context.url`. In live mode that URL has to be inside your registered domain.

Test mode

## Run it

From an empty account to a sealed test record on `localhost:3000`. No domain, no card and no gem.

1. **Create a free account and a test key**

   Sign up, then choose Create test key in the dashboard. The key starts with `esc_test_` and is shown once. The Free plan needs no card, and test keys work on `localhost` on any port with no domain.

2. **Register your two documents and a signup profile**

   In the dashboard, add a document named Terms of Service and one named Privacy Notice, publish a version of each, and create a profile with method `checkbox` and level `L1`. The names matter: the notice in the form names each document by its title, and rule `CR-02` looks for both. Copy the three IDs.

3. **Set the environment variables**

   Put them wherever your app reads its environment: the shell that starts the server, your process manager or a dotenv file that stays out of git.

   Terminal

   ```bash
   export ESIGNCOMPLY_API_KEY=esc_test_us_...       # the test key, shown once in the dashboard
   export ESIGNCOMPLY_PROFILE_ID=prof_signup_4f1a   # the signup profile: checkbox, L1
   export ESIGNCOMPLY_TERMS_ID=doc_8Hq2             # Terms of Service
   export ESIGNCOMPLY_PRIVACY_ID=doc_Pv71           # Privacy Notice
   export ESIGNCOMPLY_WEBHOOK_SECRET=whsec_...      # only for the webhook
   # An EU key (esc_test_eu_...) also needs:
   # export ESIGNCOMPLY_API_URL=https://api.eu.esigncomply.com/v1
   ```

4. **Migrate and start the server**

   The migration adds the `acceptances` table. The model is the plain class named in its first comment.

   `bin/rails db:migrate && bin/rails server`

5. **Sign up once**

   Open `http://localhost:3000/signup`. Enter an email and move to the next field: the checkbox unlocks when the session is attached. Tick it and click Create account.

6. **Open the test record**

   The dashboard lists one new test record under Records. It shows what Esign Comply observed from the browser (the page attached, both documents presented, the notice captured, the tick, the signing act), the conformance findings and the evidence report, watermarked TEST. Your `acceptances` row holds the same record ID and its signed receipt.

7. **Run the conformance check**

   The checker is a Node CLI, so it needs Node.js 20.19 or later on your machine, not in your app. The command reads `ESIGNCOMPLY_API_KEY` from your shell and takes test keys only. It opens your page in headless Chromium at 390 by 844, 768 by 1024 and 1440 by 900, tries to submit without the tick and with a scripted click, then signs up for real at each size, so expect three test users in your development database. Every finding names its rule, the measurement and the fix, and the exit code fails a CI build. A clean run ends with `0 block`.

   `npx esigncomply@latest check --url http://localhost:3000/signup`

[Create a free account](https://esigncomply.com/signup) · [What test mode does](https://esigncomply.com/docs/guides/test-mode) · [The conformance rules](https://esigncomply.com/docs/conformance)

Live mode

## Going live

The code does not change between test and live. The key, the three IDs and the domain do.

[See pricing](https://esigncomply.com/pricing) · [Register a domain](https://esigncomply.com/docs/guides/domains)

1. **Register your domain**

   Enter your production host in the dashboard under Domains. Registering `app.example.com` covers `example.com` and every subdomain, and every plan, Free included, covers that one domain.

2. **Verify it with one TXT record**

   Add a TXT record named `_esigncomply` with the value `esc-verify=<token>` that the dashboard shows. Esign Comply checks every minute for the first hour. Leave the record in place: it is checked again every day.

3. **Add your organization details**

   Enter your organization's legal name and country in the dashboard. The Free plan covers 10 live signature events a month with no checkout. Starter is $200 per year for 2,000 live signature events, and Unlimited is $1,200 per year. One event is one signer's completed signing act, so the terms and the privacy notice accepted together at signup count once.

4. **Switch to the live key**

   Create a live key (`esc_live_...`) and set it in your production environment only, for example in encrypted credentials or your host's secrets. Copy your documents and profile to live from the dashboard and set the live IDs beside it. `Rails.env.production?` already makes the confirmation expect a live record there, so a test record cannot open a production account.

In live mode `context.url` has to be inside your registered domain, browser calls are accepted only from it, and a finding at Block level stops the record from being sealed. Run the conformance check until nothing blocks before you switch keys.

Copy-paste prompt

## Have your AI tool do it instead

Paste this into Cursor, Claude Code or any coding agent that is open on your Rails app. It names the two things a tool gets wrong on this stack: there is no gem, and the browser SDK comes from a script tag.

The [prompt generator](https://esigncomply.com/product/prompt-generator) writes the long version: your own document and profile IDs, the rule packs for your regions and the stack you pick, in one prompt.

[Generate a prompt](https://esigncomply.com/product/prompt-generator)

Prompt: clickwrap in Rails

```
Add a signup clickwrap to this Rails app with Esign Comply. A new user accepts our Terms of Service and Privacy Notice before the account is created. We render every screen. Esign Comply observes it and keeps the independent record.

Read these first and follow them exactly:
- https://esigncomply.com/setup.md
- https://esigncomply.com/auth.md
- https://esigncomply.com/llms.txt
- https://esigncomply.com/guides/rails-clickwrap (working code for this stack: use it as the reference)

Stack
- There is no Esign Comply gem. Call the REST API with Net::HTTP: Authorization: Bearer with ENV["ESIGNCOMPLY_API_KEY"], and an Idempotency-Key on POST requests.
- Load the browser SDK with <script src="https://esigncomply.com/sdk/v1/esigncomply.js"></script>. It defines the global EsignComply.

Build
1. POST /signup/ceremony: create the session with POST /v1/sessions. Return only client_token, api_url and the pinned documents. Save the signer ID and the version IDs in an acceptances table.
2. The signup view: attach the SDK to our own unchecked checkbox and our Create account button. Present each document link, observe the assent container, and call complete() from the user's real click.
3. POST /signup: before User.create!, read GET /v1/records/{id} and require status recorded, timestamped or anchored, livemode equal to Rails.env.production?, and the saved signer ID and version IDs. Store the record ID and the receipt on the acceptance row.

Never
- Never invent API methods, packages or legal wording.
- Never pre-check the box, auto-submit or click for the user.
- Never put the secret key in client code, in a template or in the repository, and never print it.
- Never create the account before the server has confirmed the record.

If anything conflicts with existing code, stop and ask me. Finish with npx esigncomply@latest check --url http://localhost:3000/signup and fix every finding marked "block".
```

### Open the page for your AI tool

- [Cursor](https://esigncomply.com/build/cursor)
- [Claude Code](https://esigncomply.com/build/claude-code)
- [Codex](https://esigncomply.com/build/codex)
- [Windsurf](https://esigncomply.com/build/windsurf)
- [GitHub Copilot](https://esigncomply.com/build/github-copilot)
- [Devin](https://esigncomply.com/build/devin)
- [Lovable](https://esigncomply.com/build/lovable)
- [v0](https://esigncomply.com/build/v0)
- [Bolt](https://esigncomply.com/build/bolt)
- [Replit](https://esigncomply.com/build/replit)
- [ChatGPT](https://esigncomply.com/build/chatgpt)
- [Grok](https://esigncomply.com/build/grok)
- [Grokbot](https://esigncomply.com/build/grokbot)
- [Muse](https://esigncomply.com/build/muse)
- [All AI tools](https://esigncomply.com/build#tools)

## Questions about a clickwrap in Rails

### Is there an Esign Comply gem for Rails?

No, and the integration does not need one. The server SDK exists for Node. A Rails app calls the REST API with Net::HTTP or Faraday, and a signup clickwrap uses three calls: POST /v1/sessions, GET /v1/records/{id} and one GET for the registered document text. The 70-line service object on this page is the whole client.

### How do I add a clickwrap agreement to a Rails signup form?

Create a session from a controller with your secret key and return only the client token. In the view, load the browser SDK with a script tag and attach it to your own unchecked checkbox and submit button. When the signer clicks, the SDK returns a record ID. Confirm that record on your server with GET /v1/records/{id} before you create the user, and store the record ID and receipt in an acceptances table.

### Does the form work with Turbo and Devise?

The form sets data-turbo="false" and its script handles the submit itself, so Turbo leaves it alone. Devise changes one line: confirm the record first, create the user as you do today, then call sign_in(user) instead of setting session\[:user_id\].

### How do I verify an Esign Comply webhook in Rails?

Read request.raw_post before anything parses it. Compute an HMAC-SHA256 over the webhook-id, the webhook-timestamp and the raw body, joined with dots, using the base64-decoded part of the secret after whsec\_ as the key. Compare it with each v1 signature in the webhook-signature header using ActiveSupport::SecurityUtils.secure_compare, and reject timestamps more than 5 minutes from now.

[Read the webhook reference](https://esigncomply.com/docs/api/webhooks)

### Where is the acceptance stored, in my database or at Esign Comply?

Both, on purpose. Esign Comply keeps the sealed record: what the browser showed, the version hashes, the signing act, an outside timestamp and a place in a hash-chained ledger. Your acceptances table keeps the record ID, the document version IDs and the signed receipt next to the user, so you can show which terms each user accepted without an API call.

[How to store terms acceptance](https://esigncomply.com/learn/store-tos-acceptance)

### The same clickwrap in another stack

- [Next.js and Supabase](https://esigncomply.com/guides/nextjs-supabase-clickwrap)
- [Django](https://esigncomply.com/guides/django-clickwrap)
- [Laravel](https://esigncomply.com/guides/laravel-clickwrap)
- [React Native](https://esigncomply.com/guides/react-native-clickwrap)
- [All stack guides](https://esigncomply.com/guides)

[Build your own clickwrap](https://esigncomply.com/build/clickwrap) · [Use cases with live demos](https://esigncomply.com/use-cases) · [Clickwrap and browsewrap compared](https://esigncomply.com/learn/clickwrap-vs-browsewrap)

## Add the eight files to your Rails app. Leave the record to us.

[Get started](https://esigncomply.com/signup) · [Documentation](https://esigncomply.com/docs)

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

---

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.
