Add e-signatures and clickwrap to Phoenix
To add e-signatures and clickwrap to Phoenix, call the REST API from a controller with Req: there is no Hex package, because the server SDK exists for Node.js only. One action creates the session with the secret key and keeps the pinned versions in the Phoenix session, another confirms the record. Esign Comply seals each acceptance as an independent record.
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.
No Hex package for the API: add Req to the generated app, and nothing else
Phoenix quickstartFree plan: 10 live signatures a month and a full test mode. No card required.
Last updated
# Step 4: create the session with the secret key. The browser gets the client token only. def ceremony(conn, _params) do answer = EsignComply.request(:post, "/sessions", headers: [{"idempotency-key", "signup-#{@signer.external_id}-#{Base.url_encode64(:crypto.strong_rand_bytes(16), padding: false)}"}], json: %{ profile: config(:profile_id), signer: @signer, documents: [ %{document: config(:documents)["terms"], version: "current"}, %{document: config(:documents)["privacy"], version: "current"} ], # The page that runs the ceremony. url/1 builds it from the endpoint's :url settings, not from the request. context: %{url: url(~p"/signup"), locale: "en-US", purpose: "account_signup"} } ) case answer do {201, %{"client_token" => client_token, "api_url" => api_url, "documents" => documents}} -> # Server-owned state: the Phoenix session, a cookie that is signed and not encrypted. The visitor can read it and cannot change it. pinned = %{"signer_id" => @signer.external_id, "version_ids" => documents |> Enum.map(& &1["version_id"]) |> Enum.sort()} conn |> put_session(:pinned, pinned) |> json(%{clientToken: client_token, apiUrl: api_url, documents: documents}) {_status, %{"error" => %{"code" => code}}} -> conn |> put_status(502) |> json(%{error: code}) _ -> conn |> put_status(502) |> json(%{error: "unknown"}) end end
# lib/quickstart/esign_comply.ex defmodule Quickstart.EsignComply do @moduledoc "There is no Hex package for the API: these are plain HTTPS calls with the secret key, made with Req." @doc """ One call to the Esign Comply API. Returns `{status, body}`. Req decodes a JSON body with Jason, so the keys are strings: `record["status"]`, never `record.status`. """ def request(method, path, opts \\ []) do config = Application.fetch_env!(:quickstart, :esigncomply) # Req does not raise on 4xx and 5xx: the status is in the response, and the error envelope is the body. response = [ method: method, url: config[:api_url] <> path, auth: {:bearer, config[:api_key]}, receive_timeout: 10_000, # By default Req sends a GET again up to three times, on 408, 429 and 5xx answers and on connection errors. # Here it retries a 429 only, twice at most. Nothing else is retried. retry: &retry/2, max_retries: 2 ] |> Keyword.merge(opts) |> Req.request!() {response.status, response.body} end # Over the rate limit: wait for Retry-After, 1 second at least and 5 at most, then try again. defp retry(_request, %Req.Response{status: 429} = response) do seconds = case Integer.parse(List.first(Req.Response.get_header(response, "retry-after")) || "") do {seconds, ""} -> seconds _ -> 1 end {:delay, seconds |> max(1) |> min(5) |> Kernel.*(1000)} end defp retry(_request, _response_or_exception), do: false end
# Step 6: confirm the record with the secret key before the account exists. def confirm(conn, params) do # Plug.Parsers has decoded the JSON body into params. A body that is not JSON never gets here: Phoenix answers 400. record_id = if is_binary(params["recordId"]), do: params["recordId"], else: "missing" expected = get_session(conn, :pinned) || %{} {status, record} = EsignComply.request(:get, "/records/#{URI.encode(record_id, &URI.char_unreserved?/1)}") confirmed = status == 200 and is_map(record) and record["status"] in @sealed and record["livemode"] == config(:live) and is_binary(expected["signer_id"]) and record["signer"]["external_id"] == expected["signer_id"] and record["documents"] |> Enum.map(& &1["version_id"]) |> Enum.sort() == expected["version_ids"] Logger.info(if confirmed, do: "confirmed #{record["id"]} (#{record["status"]})", else: "refused") if confirmed do # Only now create the account, and store record["id"] and record["receipt"] with it. json(conn, %{confirmed: true, recordId: record["id"]}) else conn |> put_status(409) |> json(%{confirmed: false}) end end
# For the two JSON routes the signup page calls. They need what :browser has and :api has not: # the session, which holds the pinned versions, and the CSRF check. They answer in JSON. pipeline :browser_json do plug :accepts, ["json"] plug :fetch_session plug :protect_from_forgery plug :put_secure_browser_headers end scope "/", QuickstartWeb do pipe_through :browser get "/", PageController, :home get "/signup", SignupController, :show get "/legal/:slug", SignupController, :legal end scope "/api", QuickstartWeb do pipe_through :browser_json post "/ceremony", SignupController, :ceremony post "/signup/confirm", SignupController, :confirm end
How do you integrate Esign Comply with Phoenix?
In Phoenix the integration is one controller, two HEEx templates and a pipeline for the two JSON routes. The page sends the token from get_csrf_token() with each POST, the document template prints the registered HTML with raw/1, and url(~p"/signup") takes context.url from the endpoint's settings. config/runtime.exs reads the key when the app starts, under mix phx.server and in a release.
Phoenix's documentation says: Phoenix is a web development framework written in Elixir which implements the server-side Model View Controller (MVC) pattern.
Source: Phoenix documentation, Overview, read on .- Session actionlib/quickstart_web/controllers/signup_controller.ex
- The API calllib/quickstart/esign_comply.ex
- Confirm actionlib/quickstart_web/controllers/signup_controller.ex
- Pipeline and routeslib/quickstart_web/router.ex
Run on 2026-11-26 with Phoenix 1.8.17 (from mix phx.new with --no-ecto, --no-mailer, --no-dashboard, --no-gettext and --no-assets), Phoenix LiveView 1.2.15 for HEEx, Plug 1.20.4, Bandit 1.15.0, Req 0.7.5 and Jason 1.4.5 on Elixir 1.20.5 and Erlang/OTP 29 (the official Elixir container image), under mix phx.server in development and as a release built with MIX_ENV=prod mix release, with the browser SDK script build and the conformance check from esigncomply 1.0.4, against the API in test mode over plain http. Its calls to the API over https, a LiveView form and the default asset pipeline were not run.
What prompt adds Esign Comply clickwrap to a Phoenix 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 Phoenix, 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. Added to your project's instruction file, it makes every later session build signing and acceptance flows the same way. The prompt generator writes the long version, with your own document and profile IDs.
Pages for each AI toolAdd Esign Comply clickwrap to my Phoenix 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/phoenix.md (the steps and the tested code for Phoenix)
- https://esigncomply.com/setup.md (the order of API calls)
- https://esigncomply.com/auth.md (how to handle the keys)
Phoenix facts
- There is no Esign Comply package on Hex. Do not install or invent one. A small module calls the REST API at https://esigncomply.com/v1 with Req, a bearer token 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. Read it in config/runtime.exs with System.fetch_env!, never in config/config.exs: that file is evaluated when the code is compiled, and a release would carry the value of the build machine. Phoenix does not read .env files. Never print the key.
- The two JSON routes need the session and the CSRF check. The generated :api pipeline has neither, and :browser accepts html only. Give them a pipeline with accepts ["json"], fetch_session and protect_from_forgery.
- Every POST from the page carries the token from the csrf-token meta tag in the x-csrf-token header, or Phoenix answers 403.
- Build context.url with url(~p"/signup"). It comes from the endpoint's :url configuration, which is PHX_HOST in production, not from the request.
- Keep the pinned version IDs in the session with put_session. The Phoenix session cookie is signed, not encrypted, unless the endpoint sets an encryption_salt: the visitor can read it, so put nothing secret in it.
- HEEx escapes what it prints. Render the registered document HTML with raw/1, and nothing else.
- Req: by default it sends a GET again up to three times, on 408, 429 and 5xx answers and on connection errors, it waits as long as Retry-After says, and it does not retry a POST. Pass a retry function that returns {:delay, ms} for a 429 only, with the wait held between 1 and 5 seconds, and max_retries: 2. Req decodes JSON with Jason: the keys are strings.
- A release listens only with PHX_SERVER=true, and needs SECRET_KEY_BASE and PHX_HOST.
- 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. Action for POST /api/ceremony: call POST /v1/sessions with an Idempotency-Key, save the signer ID and the pinned version IDs in the session, and return only clientToken, apiUrl and documents.
4. Action for GET /legal/:slug: 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. Action for POST /api/signup/confirm: call GET /v1/records/{id} and require: status is "recorded", "timestamped" or "anchored"; livemode is as expected; the signer ID and version IDs equal the ones in the session. 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:4000/signup --callback http://localhost:4000/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.mdWhat goes wrong when you add e-signatures in Phoenix?
These are specific to Phoenix. Each one was seen while the quickstart's code was run, or is in Phoenix's own documentation.
- 01
Neither generated pipeline fits the two JSON routes
In the test on Phoenix 1.8.17, the session action behind
:apiwas reached with no CSRF token and raisedArgumentError: session not fetched, call fetch_session/2. Behind:browserit answered406to a request withAccept: application/json, because that pipeline accepts html. The quickstart gives the routes a pipeline withaccepts ["json"],fetch_sessionandprotect_from_forgery. - 02
check_origin guards sockets, not your POST routes
Phoenix's documentation describes
Source: Phoenix documentation, Phoenix.Endpoint, read on .:check_originas a check of theoriginheader by the socket transports, against the host in the endpoint's:url. In the test release, a WebSocket handshake withOrigin: https:/was answered/evil.example 403, and aPOSTto the session route with the same header, the CSRF token and the cookie was answered200. The JSON routes rely on the CSRF token. - 03
Without PHX_HOST the release asks for sessions on example.com
url(~p"/signup")buildscontext.urlfrom the endpoint's:urlsettings, and the generatedconfig/runtime.exssets the host fromPHX_HOSTwithexample.comas the default. In the test release with the variable not set, the API refused the session withdomain_mismatchand the action answered502. Request headers play no part:HostandX-Forwarded-Hostdid not change the URL.
Where are the Phoenix quickstart and the API reference?
Start with the quickstart: it carries every file this page excerpts, in the order you write them.
- QuickstartPhoenix quickstartStep by step, from install to your first sealed test record, with every file and the output of each step.Open
- ReferenceAPI referenceEvery endpoint, field and error code. Sessions, records and documents are the three this page uses.Open
- GuideServer confirmationThe one place access is granted: what to compare, and the webhook that backs the check up.Open
What does Esign Comply record for a signature in Phoenix?
The same record on every stack and platform. Your Phoenix 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.
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, andGET /v1returns it again./records /{id} /receipt 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.
Questions about e-signatures in Phoenix
Is there an Esign Comply SDK for Phoenix?
No. There is no Hex package, because the server SDK exists for Node.js only. A Phoenix app calls the REST API directly with the secret key, and the quickstart does it with Req in one function. Req is the only dependency it adds to the generated app.
Where do I create the session in Phoenix?
In a controller action behind POST /api, with a call to POST /v1 that carries the secret key and an Idempotency-Key. The action puts the pinned versions in the session and renders only the client token, the API URL and the documents as JSON.
Why is the signup page a controller page and not a LiveView?
Because that is what was tested. The browser SDK observes the checkbox, the links and the button it is given, and the page's script enables the checkbox itself. A LiveView form was not run, so the quickstart keeps the form in a controller template and claims nothing about LiveView.
Does HEEx escape the registered document HTML?
Yes, unless the template calls raw/1. In the test with {@html} in the document template, the page showed every tag as text and the SDK reported a finding for CR-08 at Block level. With {raw(@html)} the registered HTML arrives unmodified, which is what the page has to show.
Do a script tag and an inline script fit Phoenix's default security headers?
Yes. put_secure_browser_headers sent content-security-policy: base-uri 'self'; frame-ancestors 'self';, which names no script source. The SDK's script tag and the page's inline module script both ran, and the conformance check passed with those headers on every answer. HEEx left the curly braces of the inline script alone.
Add one controller to your Phoenix app. Leave the record to us.
Free plan: 10 live signatures a month and a full test mode. No card required.
Phoenix is a trademark of its owner. Esign Comply is not affiliated with it. What this page says about Phoenix is from Phoenix's documentation or from a test run, as marked, on . /phoenix.md is this page as Markdown.