Add e-signatures and clickwrap with Phoenix
To add e-signatures and clickwrap with Phoenix, call the REST API from a controller with Req and the secret key: there is no package. One action creates the session and keeps the pinned versions in the Phoenix session, another confirms the record, and the browser SDK attaches to your HEEx checkbox. Esign Comply seals each acceptance as an independent record.
Follow the steps and each signature your app records is a valid electronic signature under the ESIGN Act, state UETA laws and New York's ESRA, and your clickwrap is built the way courts require: clear notice of the terms, an unmistakable act of assent, and a sealed record of both.
This page is Phoenix, with a controller and HEEx templates. For an Elixir service without Phoenix, use the Elixir quickstart: the same calls in a Plug router.
Paste this prompt into Cursor, Claude Code or another AI coding tool to have it build the same integration:
Add 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.md
The rest of this page is the same integration by hand, in eight steps.
Before you start
- A test API key. Create an account with your email, no card, then choose Create test key in the dashboard. The key is shown once and starts with
esc_test_. An AI agent with an agent token creates it withPOST /v1/agent/api-keys: see the agent account API. - Nothing else from Esign Comply. Test mode works on
localhostwith no card and no domain, and the Free plan includes it in full. - Elixir with Erlang/OTP, and the Phoenix project generator. This page was run on Phoenix 1.8.17 with Elixir 1.20.5 and Erlang/OTP 29.
curlandjqfor steps 2 and 3, and Node.js 20.19 or later for the conformance check in step 7.
Step 1. Install
There is no Hex package for the API. The server SDK exists for Node.js only, so a Phoenix app calls the REST API directly, and this page does it with Req. To follow along in a new app:
mix archive.install hex phx_new
mix phx.new esigncomply_quickstart --app quickstart --no-ecto --no-mailer --no-dashboard --no-gettext --no-assets
cd esigncomply_quickstart
The flags leave out the database, the mailer, the dashboard, the translations and the asset pipeline. What remains is what serves an HTML page: the endpoint, the router, HEEx and the session. With --no-assets there is no esbuild and no Tailwind, and this page needs neither: the SDK is a script tag, and the page's own script is inline. The default asset pipeline was not run.
Add Req to the deps list in mix.exs, then fetch the dependencies:
{:req, "~> 0.7.5"}
mix deps.get
Jason and Bandit are in the generated app already.
Step 2. Set the key
Put the key in .env in the app's folder. Phoenix does not read this file: you load it into the shell that starts the app.
# .env (never commit this file)
ESIGNCOMPLY_API_KEY=esc_test_us_...
The app reads the variables in config/runtime.exs. The block that starts with config :quickstart, :esigncomply is the only addition to the file the generator wrote:
import Config
# config/runtime.exs is executed for all environments, including
# during releases. It is executed after compilation and before the
# system starts, so it is typically used to load production configuration
# and secrets from environment variables or elsewhere. Do not define
# any compile-time configuration in here, as it won't be applied.
# The block below contains prod specific runtime configuration.
# ## Using releases
#
# If you use `mix release`, you need to explicitly enable the server
# by passing the PHX_SERVER=true when you start it:
#
# PHX_SERVER=true bin/quickstart start
#
# Alternatively, you can use `mix phx.gen.release` to generate a `bin/server`
# script that automatically sets the env var above.
if System.get_env("PHX_SERVER") do
config :quickstart, QuickstartWeb.Endpoint, server: true
end
config :quickstart, QuickstartWeb.Endpoint,
http: [port: String.to_integer(System.get_env("PORT", "4000"))]
# The Esign Comply settings, for every environment. They are read here, when the app starts, and never in
# config/config.exs: that file is evaluated when the code is compiled, so a release would carry the build machine's key.
config :quickstart, :esigncomply,
api_url: System.get_env("ESIGNCOMPLY_API_URL", "https://esigncomply.com/v1"),
api_key: System.fetch_env!("ESIGNCOMPLY_API_KEY"),
profile_id: System.fetch_env!("ESIGNCOMPLY_PROFILE_ID"),
documents: %{
"terms" => System.fetch_env!("ESIGNCOMPLY_TERMS_ID"),
"privacy" => System.fetch_env!("ESIGNCOMPLY_PRIVACY_ID")
},
# Set ESIGNCOMPLY_LIVE in production only.
live: System.get_env("ESIGNCOMPLY_LIVE") == "true"
if config_env() == :dev do
# Reload browser tabs when matching files change.
config :quickstart, QuickstartWeb.Endpoint,
live_reload: [
web_console_logger: true,
patterns: [
# Static assets, except user uploads
~r"priv/static/(?!uploads/).*\.(js|css|png|jpeg|jpg|gif|svg)$"E,
# Router, Controllers, LiveViews and LiveComponents
~r"lib/quickstart_web/router\.ex$"E,
~r"lib/quickstart_web/(controllers|live|components)/.*\.(ex|heex)$"E
]
]
end
if config_env() == :prod do
# The secret key base is used to sign/encrypt cookies and other secrets.
# A default value is used in config/dev.exs and config/test.exs but you
# want to use a different value for prod and you most likely don't want
# to check this value into version control, so we use an environment
# variable instead.
secret_key_base =
System.get_env("SECRET_KEY_BASE") ||
raise """
environment variable SECRET_KEY_BASE is missing.
You can generate one by calling: mix phx.gen.secret
"""
host = System.get_env("PHX_HOST") || "example.com"
config :quickstart, :dns_cluster_query, System.get_env("DNS_CLUSTER_QUERY")
config :quickstart, QuickstartWeb.Endpoint,
url: [host: host, port: 443, scheme: "https"],
http: [
# Enable IPv6 and bind on all interfaces.
# Set it to {0, 0, 0, 0, 0, 0, 0, 1} for local network only access.
# See the documentation on https://bandit.hexdocs.pm/Bandit.html#t:options/0
# for details about using IPv6 vs IPv4 and loopback vs public addresses.
ip: {0, 0, 0, 0, 0, 0, 0, 0}
],
secret_key_base: secret_key_base
# ## SSL Support
#
# To get SSL working, you will need to add the `https` key
# to your endpoint configuration:
#
# config :quickstart, QuickstartWeb.Endpoint,
# https: [
# ...,
# port: 443,
# cipher_suite: :strong,
# keyfile: System.get_env("SOME_APP_SSL_KEY_PATH"),
# certfile: System.get_env("SOME_APP_SSL_CERT_PATH")
# ]
#
# The `cipher_suite` is set to `:strong` to support only the
# latest and more secure SSL ciphers. This means old browsers
# and clients may not be supported. You can set it to
# `:compatible` for wider support.
#
# `:keyfile` and `:certfile` expect an absolute path to the key
# and cert in disk or a relative path inside priv, for example
# "priv/ssl/server.key". For all supported SSL configuration
# options, see https://plug.hexdocs.pm/Plug.SSL.html#configure/1
#
# We also recommend setting `force_ssl` in your config/prod.exs,
# ensuring no data is ever sent via http, always redirecting to https:
#
# config :quickstart, QuickstartWeb.Endpoint,
# force_ssl: [hsts: true]
#
# Check `Plug.SSL` for all available options in `force_ssl`.
end
Read the key here and not in config/config.exs. Mix's documentation says config/config.exs is evaluated when you compile your code or assemble the release, so a key read there stays in the release. This file runs when the app starts. In the test, the release was built with none of the variables set, and started without them it ended with System.EnvError: could not fetch environment variable "ESIGNCOMPLY_API_KEY" because it is not set.
Load the file into your shell for the commands in steps 2, 3 and 7, then check that the key works:
set -a; . ./.env; set +a
curl -s ${ESIGNCOMPLY_API_URL:-https://esigncomply.com/v1}/usage \
-H "Authorization: Bearer $ESIGNCOMPLY_API_KEY" | jq '{plan_name, test_events}'
{
"plan_name": "Free",
"test_events": {
"used_this_month": 0,
"quota_per_month": 500
}
}
A 401 means the key is wrong or revoked: see invalid_api_key. The rules for handling keys are in /auth.md.
Step 3. Register a document version
Every record pins the exact version of each document by hash, so the documents are registered first. This block registers a Terms of Service and a Privacy Notice with one version each, and creates a profile: the Federal pack, a checkbox with a button, level L1. It is the same for every stack and needs curl and jq.
ESC=${ESIGNCOMPLY_API_URL:-https://esigncomply.com/v1}
KEY="Authorization: Bearer $ESIGNCOMPLY_API_KEY"
JSON="Content-Type: application/json"
# Two sample documents, one version each.
TERMS=$(curl -s $ESC/documents -H "$KEY" -H "$JSON" \
-d '{"name":"Terms of Service","type":"terms"}' | jq -r .id); sleep 1
curl -s $ESC/documents/$TERMS/versions -H "$KEY" -H "$JSON" \
-d '{"version_label":"1","language":"en","content":{"format":"markdown","text":"# Terms of Service\n\nThese are sample terms for a test."},"material_change":true}' \
| jq -r .id; sleep 1
PRIVACY=$(curl -s $ESC/documents -H "$KEY" -H "$JSON" \
-d '{"name":"Privacy Notice","type":"privacy_notice"}' | jq -r .id); sleep 1
curl -s $ESC/documents/$PRIVACY/versions -H "$KEY" -H "$JSON" \
-d '{"version_label":"1","language":"en","content":{"format":"markdown","text":"# Privacy Notice\n\nThis is a sample privacy notice for a test."}}' \
| jq -r .id; sleep 1
# A profile: Federal pack, checkbox plus button, L1.
PROFILE=$(curl -s $ESC/profiles -H "$KEY" -H "$JSON" \
-d '{"name":"Signup","jurisdictions":["US-FED"],"method":"checkbox","assurance_level":"L1"}' | jq -r .id)
printf 'ESIGNCOMPLY_PROFILE_ID=%s\nESIGNCOMPLY_TERMS_ID=%s\nESIGNCOMPLY_PRIVACY_ID=%s\n' "$PROFILE" "$TERMS" "$PRIVACY"
It prints the two version IDs, then three lines with your own IDs:
dv_YiWs9cmWoVSGp7ALPeZS
dv_bAYeA7QigKUH0iLhPpV7
ESIGNCOMPLY_PROFILE_ID=prof_SPVEgBT8a8Ror3mJ8M99
ESIGNCOMPLY_TERMS_ID=doc_bDgYFndAoC8tkeYibAVy
ESIGNCOMPLY_PRIVACY_ID=doc_mb2hnWKS0Qa7SKtucDW9
Add the three lines to .env, then load the file into your shell again. The pauses keep the script under the Free plan's 2 requests per second. Keep the names Terms of Service and Privacy Notice: the notice on your page names each document by its registered name, and rule CR-02 checks that it does. With your own documents, publish the text you already have and change the notice to match. See Documents and Profiles.
Step 4. Create a session on the server
The whole client is one module with one function: an HTTPS call with the secret key that returns the status and the decoded JSON, sent again only when the API answers 429.
# 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
One controller carries the integration: the signup page, the document pages, the session and the confirmation. The ceremony action creates the session and returns three values to the browser: the client token, the API URL and the pinned documents. The version IDs it pinned go into the Phoenix session.
# lib/quickstart_web/controllers/signup_controller.ex
defmodule QuickstartWeb.SignupController do
use QuickstartWeb, :controller
require Logger
alias Quickstart.EsignComply
@sealed ~w(recorded timestamped anchored)
# The signer. In your app this is the signed-in user, or the account you are about to create.
@signer %{
external_id: "user_7c1d",
email: "dana@example.org",
name: "Dana Whitfield",
class: "consumer",
country: "US",
region: "US-CA"
}
# The signup page. The template is the whole page, so the root layout is left out.
def show(conn, _params) do
conn |> put_root_layout(false) |> render(:show)
end
# The document pages: each one renders a registered version, unmodified.
def legal(conn, %{"slug" => slug} = params) do
document = config(:documents)[slug]
v = params["v"]
version = if is_binary(v) and v =~ ~r/\A\w+\z/, do: v, else: "current"
case document && EsignComply.request(:get, "/documents/#{document}/versions/#{version}/content") do
{200, %{"version_id" => version_id, "html" => html}} ->
conn |> put_root_layout(false) |> render(:legal, version_id: version_id, html: html)
_ ->
conn |> put_status(404) |> json(%{error: "not_found"})
end
end
# 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
# 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
defp config(key), do: Application.fetch_env!(:quickstart, :esigncomply)[key]
end
The signer is a fixed test person here. In your app it is the signed-in user or the account you are about to create.
Route the four actions. The pipeline :browser_json and the routes that name SignupController are the additions to the generated lib/quickstart_web/router.ex:
defmodule QuickstartWeb.Router do
use QuickstartWeb, :router
pipeline :browser do
plug :accepts, ["html"]
plug :fetch_session
plug :fetch_live_flash
plug :put_root_layout, html: {QuickstartWeb.Layouts, :root}
plug :protect_from_forgery
plug :put_secure_browser_headers
end
pipeline :api do
plug :accepts, ["json"]
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
# Other scopes may use custom stacks.
# scope "/api", QuickstartWeb do
# pipe_through :api
# end
end
Eight things here are specific to Phoenix, and each one was seen in the test run.
Neither generated pipeline fits the two JSON routes. Behind :api, the session action was reached with no CSRF token at all, and then raised ArgumentError: session not fetched, call fetch_session/2. Behind :browser, the request the page sends was answered 200, and the same request with Accept: application/json was answered 406: that pipeline accepts html. So the routes get a pipeline of their own, :browser_json: JSON, the session and the CSRF check.
protect_from_forgery answers 403 to a POST without the token, and to one without the session cookie. The template puts get_csrf_token() into a meta tag and the script sends it back in the x-csrf-token header on both requests. In development the 403 is a page that names Plug.CSRFProtection.InvalidCSRFTokenError. From the release it is the word Forbidden.
context.url comes from the endpoint, not from the request. url(~p"/signup") builds it from the endpoint's :url settings: in development it was http://localhost:4000/signup, whatever the Origin, Host or X-Forwarded-Host header said. In the release it is https:// and PHX_HOST. With PHX_HOST not set, the release asked for a session on https://example.com/signup, the API refused it with domain_mismatch, and the action answered 502.
The session is a cookie that Phoenix signs and does not encrypt. The generated endpoint says so in a comment, and names encryption_salt as the setting that changes it. The browser got a cookie named _quickstart_key, 283 characters long, HttpOnly and SameSite=Lax. Decoded from Base64, its middle part showed the signer ID and the two version IDs, beside the state of the CSRF token. The visitor can read them and cannot change them. A cookie with a changed signature, with no signature, or with another signer ID in the payload was answered 403: Phoenix drops such a session, so the CSRF check fails before the action runs. The cookie of a page load that created no session was answered 409.
Plug.Parsers in the endpoint decodes the JSON body before the router runs. A body that is not JSON never reaches the action: the answer was 400. An empty body, and a body whose recordId is a number, reached the action and were refused with 409.
What an action raises ends that request and nothing else. With the API address on a closed port, the release answered 500 with {"errors":{"detail":"Internal Server Error"}}, the log had [error] ** (Req.TransportError) connection refused, and the next request was answered 200. In development the same request got Phoenix's debug page with the stack trace, because the generated config/dev.exs sets debug_errors: true.
The retry is Req's own, with a function in place of its default. With its defaults Req retries a GET three times on 429, 5xx and connection errors, waits as long as Retry-After says, and sends a POST once: the Elixir quickstart has the measurements. The function here retries a 429 only, for both calls. Against a stand-in that always answers 429, the three calls were 1, 2 and 5 seconds apart for no header, 2 and 30, with the same Idempotency-Key each time. The wait holds the process of that one request: in the burst test, page requests were answered in about 0.001 seconds while two confirmations waited to retry.
The default security headers leave the page's scripts alone. 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 inline module script both ran: the conformance check in step 7 passed with those headers on every answer.
Step 5. Attach the ceremony in the browser
The browser SDK renders nothing. It observes the checkbox, the notice, the links and the button you built, and reports each step from the signer's browser straight to Esign Comply. The templates belong to a small module, lib/quickstart_web/controllers/signup_html.ex:
# lib/quickstart_web/controllers/signup_html.ex
defmodule QuickstartWeb.SignupHTML do
use QuickstartWeb, :html
# show.html.heex and legal.html.heex
embed_templates "signup_html/*"
end
Save the page as lib/quickstart_web/controllers/signup_html/show.html.heex. The controller renders it without the root layout, so the file is the whole page:
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<meta name="csrf-token" content={get_csrf_token()} />
<title>Create account</title>
<style>
body { font: 16px/1.5 system-ui, sans-serif; max-width: 480px; margin: 48px auto; padding: 0 20px; }
a { color: #0b57d0; text-decoration: underline; }
button { font: inherit; padding: 10px 16px; }
</style>
</head>
<body>
<h1>Create account</h1>
<form id="signup">
<div id="assent">
<!-- The page is on screen before the script has a session, so the box stays disabled until the SDK watches it. -->
<label><input id="agree" type="checkbox" disabled /> I agree to the Terms of Service and Privacy Notice</label>
<p>
By checking the box and clicking Create account, you agree to the
<a id="tos-link" href="/legal/terms">Terms of Service</a> and acknowledge the
<a id="privacy-link" href="/legal/privacy">Privacy Notice</a>.
</p>
<button id="create-account" type="submit" disabled>Create account</button>
</div>
<p id="message" role="alert"></p>
</form>
<script src="https://esigncomply.com/sdk/v1/esigncomply.js"></script>
<script type="module">
const agree = document.querySelector("#agree");
const submit = document.querySelector("#create-account");
const message = document.querySelector("#message");
// Phoenix refuses a POST without the CSRF token: 403.
const csrf = document.querySelector('meta[name="csrf-token"]').content;
// Your server creates the session and returns only the client token and the pinned documents.
const response = await fetch("/api/ceremony", { method: "POST", headers: { "x-csrf-token": csrf } });
const { clientToken, apiUrl, documents } = await response.json();
const ceremony = await EsignComply.attach({ clientToken, apiUrl });
ceremony.on("change", ({ remainingSteps }) => {
submit.disabled = remainingSteps.some((step) => step !== "signature.applied");
});
// Point each link at the exact version this session pinned, then report it.
const links = [document.querySelector("#tos-link"), document.querySelector("#privacy-link")];
for (const [i, link] of links.entries()) {
link.search = "?v=" + documents[i].version_id;
await ceremony.presentDocument({ versionId: documents[i].version_id, mode: "hyperlink", link });
}
await ceremony.observeAssent({
region: document.querySelector("#assent"), // notice, links, checkbox, button
checkbox: agree,
submit,
});
agree.disabled = false; // the SDK watches the box from here on. Only the user ticks it.
document.querySelector("#signup").addEventListener("submit", async (event) => {
event.preventDefault();
try {
const result = await ceremony.complete(); // the signing act, from the signer's own click
// The result came to the browser. Your server confirms the record before anything is granted.
const confirmed = await fetch("/api/signup/confirm", {
method: "POST",
headers: { "Content-Type": "application/json", "x-csrf-token": csrf },
body: JSON.stringify({ recordId: result.recordId }),
});
message.textContent = confirmed.ok
? `Account created. Record ${result.recordId}`
: "We could not confirm whether your acceptance was recorded. Please wait while we check.";
} catch (error) {
message.textContent = error.message;
}
});
</script>
</body>
</html>
HEEx compiled the inline script as it is: the curly braces of the JavaScript were left alone. In development, HEEx added a data-phx-loc attribute to every element of the page, the checkbox and the button included, and the conformance check passed with them. The release added none.
The document page is lib/quickstart_web/controllers/signup_html/legal.html.heex:
<!doctype html>
<meta charset="utf-8" />
<%!-- raw/1 prints the registered HTML as it is. Without it HEEx escapes the tags. The attribute value is escaped. --%>
<article data-esc-document={@version_id}>{raw(@html)}</article>
HEEx escapes what it prints, and raw/1 is how the registered HTML arrives as it is. In a test with {@html} in place of {raw(@html)}, the page showed the tags as text and the SDK reported a finding for CR-08 at Block level: the page behind the link did not match the registered version.
Start the server from the shell that loaded .env:
mix phx.server
[info] Access QuickstartWeb.Endpoint at http://localhost:4000
Open http://localhost:4000/signup. The button stays disabled until the box is ticked. Tick it, click Create account, and the page shows:
Account created. Record rec_yioNEeE82jRirYttfhyb
The checkbox starts unchecked and disabled. The page is on screen before the script has a session, and the script enables the box once the SDK observes it: a box ticked before that fails CR-01. In a test with the session request held back, a click on the box did nothing. One page load sent one POST /api/ceremony.
Step 6. Confirm the record on the server
The result of complete() was delivered to the browser, so your server does not trust it. The confirm action reads the record with the secret key and grants access only when four things hold: the status is recorded, timestamped or anchored; livemode is what this deployment expects; the signer is the one in the session; and the document versions are exactly the ones this server pinned there. This step is never optional.
The server log has one line for each confirmation:
[info] confirmed rec_yioNEeE82jRirYttfhyb (recorded)
A POST without the CSRF token never reaches the action: Phoenix answers 403. With the token and the cookie of the page, a record ID that was made up is refused with status 409:
TOKEN=$(curl -s -c jar.txt http://localhost:4000/signup | grep -o 'name="csrf-token" content="[^"]*"' | sed 's/.*content="//; s/"$//')
curl -s -b jar.txt -X POST http://localhost:4000/api/signup/confirm \
-H "x-csrf-token: $TOKEN" -H "Content-Type: application/json" -d '{"recordId":"rec_made_up"}'
{"confirmed":false}
See Server confirmation for the webhook that backs this action up when the browser closes early.
Step 7. Check the result
Open the dashboard and choose Records. The test record is there with what was observed, what was asserted, and its evidence report, watermarked TEST.
Then run the conformance check against the page. It opens the page in headless Chromium at three window sizes, signs as a visitor would, and tries four things that must be refused. One of them posts a made-up record ID to your confirm route. The checker is a Node.js command line tool, so it needs Node.js 20.19 or later, in a folder of its own:
mkdir -p esc-check && cd esc-check
npm init -y && npm install esigncomply playwright
npx playwright install chromium
npx esigncomply check --url http://localhost:4000/signup --callback http://localhost:4000/api/signup/confirm
The report for this page's code, shortened:
Violations that must be refused
REFUSED Submit with the checkbox untouched No record was made.
REFUSED Completion from another origin The API answered 403 domain_mismatch.
REFUSED Programmatic click No record was made.
REFUSED Forged success posted to your callback http://localhost:4000/api/signup/confirm answered 403.
Ceremonies
390x844 record rec_rpCQPhqwiWX6pnHUN6y4 session ses_JPr1ZWSgpnXRgwGZeXEo, 5 events
768x1024 record rec_i2xg9w6iorECaRBkvufT session ses_JeDmX6d0AvQtDV74SKMh, 5 events
1440x900 record rec_yuf0JQjgDVxm4R0wwhpn session ses_fA3CQ318RbG0EP8mBE0N, 5 events
Summary: 0 block, 0 warn, 27 pass.
The forged callback is answered 403 here, not 409: it carries no CSRF token, so Phoenix refuses it before the action runs. The app logged a confirmed line for each of the three records.
Fix every finding marked block and read every finding marked warn. Each one names the rule the screen missed, the measurement and the fix. In test mode a finding never stops a record from being sealed, so read the report. The rules are on Conformance rules, and every flag of the command is on the CLI page.
Step 8. Go live
Going live takes three steps on the Esign Comply side. There is no plan to choose and no checkout: the Free plan records 10 live signatures a month.
- Register your production domain and verify it. See Register a domain.
- Add your organization's legal name, country and address under Go live in the dashboard.
- Create a live key. It is shown once and starts with
esc_live_.
Test and live share nothing, so create the documents and the profile again with the live key, or copy them to live from the dashboard, and use the live IDs in production.
Then switch the app over:
- Build a release with
MIX_ENV=prod mix releaseand start it withPHX_SERVER=true _build/prod/rel/quickstart/bin/quickstart start. In the test the release was 74 MB with the Erlang runtime inside, ran as one process of about 190 MB, and recorded the signature shown in step 5. - Set
PHX_SERVER=true. Without it the release started, loggedConfiguration :server was not enabled for QuickstartWeb.Endpoint, http/https services won't start, and nothing listened. - Set
SECRET_KEY_BASEto the output ofmix phx.gen.secret, the same on every instance. Without it the release ended at start withenvironment variable SECRET_KEY_BASE is missing. A session signed with another secret was answered403. - Set
PHX_HOSTto your registered domain. It is the host incontext.url, and the host thatcheck_origincompares. - The generated
config/prod.exsturnsforce_sslon, withlocalhostand127.0.0.1left out. In the test a plain http request for another host was answered301tohttps://and the endpoint's host. The same request withX-Forwarded-Proto: httpswas answered200, withstrict-transport-securityand a session cookie markedsecure. Your proxy has to send that header. check_originis about sockets. A WebSocket handshake on/live/websocketwithOrigin: https://evil.examplewas answered403. APOSTto/api/ceremonywith the sameOrigin, the token and the cookie was answered200: the two JSON routes rely on the CSRF token, not oncheck_origin.- Set the live key as
ESIGNCOMPLY_API_KEYand setESIGNCOMPLY_LIVE=truein production only. In the test with that variable set, the confirm action refused a test record with409. - Store the record ID and the receipt beside the user.
In live mode context.url must be inside your registered domain, and browser calls are accepted only from it. By default a live signature with a finding at Block level is recorded and you are told at once which rule failed. Turn on blocking, on the dashboard's Conformance page, and it is refused before it is sealed. Run the check from step 7 until no finding is at Block level before you switch keys.
Troubleshooting
403on every POST from the page. The request carries no CSRF token, or no session cookie. In development the answer namesPlug.CSRFProtection.InvalidCSRFTokenError. Send the token from thecsrf-tokenmeta tag in thex-csrf-tokenheader, as the page does. The Esign Comply API is not involved: the request never left Phoenix.- The release starts and nothing answers.
PHX_SERVERis not set, and the log saysConfiguration :server was not enabled. Start it withPHX_SERVER=true. domain_mismatchfrom/api/ceremony.context.urlis built from the endpoint's:urlsettings. In a release that ishttps://andPHX_HOST, andexample.comwhen the variable is not set. Test keys work onlocalhostand127.0.0.1at any port. Add other hosts under Domains in the dashboard. Seedomain_mismatch.429when theconfirmaction reads the record. The retry function waits for the seconds inRetry-After, 1 at least and 5 at most, and Req sends the request again, up to twice. Nothing else is retried. In the test, four confirmations sent at once from the session that signed all answered200, two of them a second later than the others. The API's log showed why: two reads got429and passed on the next attempt. Seerate_limit_exceeded.
Questions about the Phoenix quickstart
Is there an Esign Comply package for Phoenix?
No. The server SDK exists for Node.js only. A Phoenix app calls the REST API directly, and this quickstart does it with Req in one function. Req is the only dependency the page adds to the generated app.
Which pipeline do the two JSON routes belong in?
One of their own. They need the session and the CSRF check, which the generated :api pipeline does not have: behind it the session action raised an error because the session was not fetched. The :browser pipeline accepts html and answered 406 to a request that asked for JSON.
Where does context.url come from in Phoenix?
From the endpoint's :url settings, through url(~p"/signup"). In development that was http://localhost:4000/signup whatever the request's headers said. In a release it is https:// and PHX_HOST. With that variable not set, the API refused the session with domain_mismatch.
Why does the legal template call raw?
Because HEEx escapes what it prints. Without raw/1 the registered document reached the browser with every tag visible as text, and the SDK reported a finding for CR-08 at Block level. The registered HTML was sanitized by Esign Comply when the version was published, and the page has to show it unmodified.
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 this page keeps the form in a controller template and claims nothing about LiveView.
Does the Phoenix quickstart need a domain or a card?
No. Test mode works on localhost with a test key, no card and no domain. You register and verify a domain only when you go live, and the Free plan then records 10 live signatures a month.
Next steps
- E-signatures and clickwrap for Phoenix: what the integration gives you on this stack, with the things to watch for.
- Add e-signatures and clickwrap with Elixir: the same calls in a Plug router with no Phoenix.
- Server confirmation: the checks in step 6 and the
record.completedwebhook. - Sessions API and Records API: every field of the two calls this app makes.
- All quickstarts.
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.
Last updated · API version 2026-11-21