Skip to content
Stack guide · Rails

Clickwrap agreement in 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.

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.

app/services/esign_comply.rb
# 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

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.

01

esign_comply.rb: the whole client, no gem

app/services/esign_comply.rbView the file

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.

02

SignupCeremoniesController: create the session, return the client token

app/controllers/signup_ceremonies_controller.rbView the file

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.

03

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

app/views/registrations/new.html.erbView the file

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.

04

RegistrationsController: confirm first, then User.create!

app/controllers/registrations_controller.rbView the file

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).

05

The migration: an acceptances table next to users

db/migrate/20261122000000_create_acceptances.rbView the file

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.

06

LegalController: the registered version, unmodified

app/controllers/legal_controller.rbView the file

/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.

07

EsignWebhooksController: verify the signature, fill the open row

app/controllers/esign_webhooks_controller.rbView the file

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.

08

routes.rb: five routes

config/routes.rbView the file

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. 01

    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. 02

    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. 03

    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
    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. 04

    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. 05

    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. 06

    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. 07

    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
Live mode

Going live

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

  1. 01
    Register your domainEnter 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. 02
    Verify it with one TXT recordAdd 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. 03
    Add your organization detailsEnter 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. 04
    Switch to the live keyCreate 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 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
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".

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

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

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

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

Working with an AI tool? This page is also available as Markdown: /guides/rails-clickwrap.md