Skip to content
DocsMenu

Add e-signatures and clickwrap with Django

View as Markdown

Open this page inChatGPTClaudeCursor

To add e-signatures and clickwrap with Django, call the REST API from your views with the secret key: there is no Python package. One view creates the session and keeps the pinned versions in the Django session, another confirms the record, and the browser SDK attaches to your own 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.

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 Django 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/django.md (the steps and the tested code for Django)
- https://esigncomply.com/setup.md (the order of API calls)
- https://esigncomply.com/auth.md (how to handle the keys)

Django facts
- There is no Esign Comply package for Python. Do not install or invent one. The views call the REST API at https://esigncomply.com/v1 with Authorization: Bearer and the secret key.
- The browser SDK is a script tag: https://esigncomply.com/sdk/v1/esigncomply.js. It defines the global EsignComply.
- The secret key is in the environment variable ESIGNCOMPLY_API_KEY. Django does not read .env files on its own. Never print the key.
- Every POST from the page carries Django's CSRF token in the X-CSRFToken header. A page that is not a template needs @ensure_csrf_cookie on its view to get the csrftoken cookie.
- Keep the pinned version IDs in request.session. The default session lives in the database, so run python manage.py migrate first.
- 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. View for POST /api/ceremony: call POST /v1/sessions with an Idempotency-Key, save the pinned version IDs in request.session, and return only clientToken, apiUrl and documents.
4. View 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. View 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 server-owned state. 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:8000/signup --callback http://localhost:8000/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. The full application, with a model for the acceptance, the webhook and the signup form, is in Clickwrap in Django.

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 with POST /v1/agent/api-keys: see the agent account API.
  • Nothing else from Esign Comply. Test mode works on localhost with no card and no domain, and the Free plan includes it in full.
  • Python 3.9 or later. This page was run on Python 3.9.25 with Django 4.2.30.
  • curl and jq for steps 2 and 3, and Node.js 20.19 or later for the conformance check in step 7.

Step 1. Install

Install Django and requests. There is no Esign Comply package to add: the server SDK exists for Node.js only, so the views call the REST API with requests. Then create the project and its database, which holds the sessions.

mkdir esigncomply-quickstart && cd esigncomply-quickstart
python3 -m venv .venv && . .venv/bin/activate
pip install django requests
django-admin startproject mysite .
python manage.py migrate

Step 2. Set the key

Put the key in .env in the project folder. Django does not read this file: you load it into the shell that runs the server, and the views read the variables from os.environ.

# .env (never commit this file)
ESIGNCOMPLY_API_KEY=esc_test_us_...

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 function: an HTTPS call with the secret key that returns the status and the parsed JSON.

# mysite/esign.py
import os
import time

import requests

# There is no Python package: these are plain HTTPS calls with the secret key.
API = os.environ.get("ESIGNCOMPLY_API_URL", "https://esigncomply.com/v1")


def call(method, path, json=None, idempotency_key=None):
    """One call to the Esign Comply API. Returns (status, parsed JSON)."""
    headers = {"Authorization": f"Bearer {os.environ['ESIGNCOMPLY_API_KEY']}"}
    if idempotency_key:
        headers["Idempotency-Key"] = idempotency_key
    for attempt in range(3):
        response = requests.request(method, API + path, headers=headers, json=json, timeout=10)
        # Over the rate limit: wait for Retry-After (5 seconds at most) and try again, twice at most. Nothing else is retried.
        if response.status_code != 429 or attempt == 2:
            break
        time.sleep(min(float(response.headers.get("Retry-After") or 1), 5))
    return response.status_code, response.json()

When the API answers 429, call waits for the seconds in Retry-After, 5 at most, and calls again, up to twice. The wait holds the thread that serves that request and no other: under runserver, page requests sent while two confirmations waited were answered in under 0.01 seconds. A server with synchronous workers has one worker fewer for those seconds.

Four views carry the integration: the signup page, the document pages, the session and the confirmation. The ceremony view 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 request.session, which Django stores on the server.

# mysite/views.py
import json
import os
import uuid
from pathlib import Path
from urllib.parse import quote

from django.http import HttpResponse, JsonResponse
from django.views.decorators.csrf import ensure_csrf_cookie
from django.views.decorators.http import require_GET, require_POST

from . import esign

LIVE = os.environ.get("ESIGNCOMPLY_LIVE") == "true"  # set it in production only
SEALED = {"recorded", "timestamped", "anchored"}
DOCUMENTS = {
    "terms": os.environ["ESIGNCOMPLY_TERMS_ID"],
    "privacy": os.environ["ESIGNCOMPLY_PRIVACY_ID"],
}

# The signer. In your app this is request.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",
}


@ensure_csrf_cookie  # sets the csrftoken cookie that the page sends back as X-CSRFToken
@require_GET
def signup(request):
    return HttpResponse((Path(__file__).parent / "signup.html").read_text())


# The document pages: each one renders a registered version, unmodified.
@require_GET
def legal(request, slug):
    document_id = DOCUMENTS.get(slug)
    if not document_id:
        return JsonResponse({"error": "not_found"}, status=404)
    version = quote(request.GET.get("v", "current"), safe="")
    status, content = esign.call("GET", f"/documents/{document_id}/versions/{version}/content")
    if status != 200:
        return JsonResponse({"error": "not_found"}, status=404)
    return HttpResponse(
        f'<!doctype html><meta charset="utf-8"><article data-esc-document="{content["version_id"]}">{content["html"]}</article>'
    )


# Step 4: create the session with the secret key. The browser gets the client token only.
@require_POST
def ceremony(request):
    origin = request.headers.get("Origin") or f"{request.scheme}://{request.get_host()}"
    status, session = esign.call(
        "POST",
        "/sessions",
        idempotency_key=f"signup-{SIGNER['external_id']}-{uuid.uuid4()}",
        json={
            "profile": os.environ["ESIGNCOMPLY_PROFILE_ID"],
            "signer": SIGNER,
            "documents": [
                {"document": DOCUMENTS["terms"], "version": "current"},
                {"document": DOCUMENTS["privacy"], "version": "current"},
            ],
            "context": {"url": f"{origin}/signup", "locale": "en-US", "purpose": "account_signup"},
        },
    )
    if status != 201:
        return JsonResponse({"error": session.get("error", {}).get("code")}, status=502)
    # The Django session is stored on the server: the browser holds only its ID.
    request.session["pinned_versions"] = sorted(d["version_id"] for d in session["documents"])
    return JsonResponse(
        {"clientToken": session["client_token"], "apiUrl": session["api_url"], "documents": session["documents"]}
    )


# Step 6: confirm the record with the secret key before the account exists.
@require_POST
def confirm(request):
    record_id = json.loads(request.body or b"{}").get("recordId")
    status, record = esign.call("GET", f"/records/{quote(str(record_id), safe='')}")
    confirmed = (
        status == 200
        and record["status"] in SEALED
        and record["livemode"] is LIVE
        and record["signer"]["external_id"] == SIGNER["external_id"]
        and sorted(d["version_id"] for d in record["documents"]) == request.session.get("pinned_versions")
    )
    print(f"confirmed {record['id']} ({record['status']})" if confirmed else "refused", flush=True)
    if not confirmed:
        return JsonResponse({"confirmed": False}, status=409)
    # Only now create the account, and store record["id"] and record["receipt"] with it.
    return JsonResponse({"confirmed": True, "recordId": record["id"]})

Route the four views. This replaces the mysite/urls.py that startproject wrote:

# mysite/urls.py
from django.urls import path

from . import views

urlpatterns = [
    path("signup", views.signup),
    path("legal/<slug:slug>", views.legal),
    path("api/ceremony", views.ceremony),
    path("api/signup/confirm", views.confirm),
]

The signer is a fixed test person here. In your app it is request.user or the account you are about to create.

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. Save the page as mysite/signup.html:

<!doctype html>
<html lang="en">
  <head>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1" />
    <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");
      // Django set the csrftoken cookie with this page. Every POST sends it back in a header.
      const csrf = document.cookie.match(/csrftoken=([^;]+)/)[1];

      // 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-CSRFToken": 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-CSRFToken": 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>

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.

The page is a plain file, not a template, so it has no {% csrf_token %} tag. The @ensure_csrf_cookie decorator on the signup view makes Django set the csrftoken cookie anyway, and the script sends its value back in the X-CSRFToken header on both POST requests.

Start the server from the shell that loaded .env, and open http://localhost:8000/signup:

python manage.py runserver

The button stays disabled until the box is ticked. Tick it, click Create account, and the page shows a line such as:

Account created. Record rec_uHqaGvr7mLysar8wace8

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 view 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 this server created the session for; and the document versions are exactly the ones in the session. This step is never optional.

The server prints one line for each confirmation:

confirmed rec_uHqaGvr7mLysar8wace8 (recorded)

A POST without the CSRF token never reaches the view: Django answers 403. With the token, a record ID that was made up is refused with status 409:

curl -s -c jar.txt -o /dev/null http://localhost:8000/signup
TOKEN=$(grep csrftoken jar.txt | awk '{print $7}')
curl -s -b jar.txt -X POST http://localhost:8000/api/signup/confirm \
  -H "X-CSRFToken: $TOKEN" -H "Content-Type: application/json" -d '{"recordId":"rec_made_up"}'
{"confirmed": false}

See Server confirmation for the webhook that backs this view 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:8000/signup --callback http://localhost:8000/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:8000/api/signup/confirm answered 403.

Ceremonies
  390x844    record rec_uHqaGvr7mLysar8wace8  session ses_UKshgYd3JXPdFNKapENo, 5 events
  768x1024   record rec_dLjP2LZtJNk3ooHmYf3A  session ses_ud9ycnvMrbpSbRAkhp04, 5 events
  1440x900   record rec_f1mSqutnNSTQgvUEHi2s  session ses_VKLxtFbMYYnc9ivwtdSB, 5 events

Summary: 0 block, 0 warn, 27 pass.

The forged callback is answered 403 here, not 409: it carries no CSRF token, so Django refuses it before the view runs.

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.

  1. Register your production domain and verify it. See Register a domain.
  2. Add your organization's legal name, country and address under Go live in the dashboard.
  3. 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 project over:

  • Set the live key as ESIGNCOMPLY_API_KEY and set ESIGNCOMPLY_LIVE=true in production only. From then on the confirm view refuses every test record there.
  • Serve the project with a production server. Django's own documentation says of runserver: do not use this server in a production setting.
  • Store the record ID and the receipt in a model beside the user. Clickwrap in Django has the model and the webhook.

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

  • 403 on every POST from the page. The request carries no CSRF token. The page reads the csrftoken cookie, which exists only when the signup view has @ensure_csrf_cookie. In the test run, the signup page set the cookie and a view without the decorator set none. The Esign Comply API is not involved: the request never left Django.
  • 500 from /api/ceremony with "no such table: django_session". The session lives in the database and the tables do not exist yet. Run python manage.py migrate. The session at Esign Comply was created, and it expires unused. A second cause of a refused confirmation is a record ID that does not exist, which the API answers with not_found.
  • KeyError: 'ESIGNCOMPLY_TERMS_ID' when the server starts. The variables are not in the environment of the shell that runs manage.py. Run set -a; . ./.env; set +a in that shell first. An API call with an empty or wrong key returns invalid_api_key.
  • 429 when the confirm view reads the record. call waits for the seconds in Retry-After, 5 at most, and calls again, up to twice. Nothing else is retried. In the test, four confirmations sent at once from the session that signed all answered 200, two of them a second later than the others. Four reads sent at once through call showed why: two got 429 with Retry-After: 1 and passed on the next attempt. See rate_limit_exceeded.

Questions about the Django quickstart

Is there an Esign Comply package for Django?

No. The server SDK exists for Node.js only. Django calls the REST API directly, and this quickstart does it with requests in one short function. There is no app to add to INSTALLED_APPS and no settings to change.

Where are the pinned versions kept in Django?

In request.session. Django's default session engine stores the data in the database and gives the browser a cookie with the session ID only, so the visitor cannot read or change what the server pinned. That is why the quickstart runs python manage.py migrate first.

Because the page is a plain file with no csrf_token template tag. In the test run a view without the decorator set no csrftoken cookie. The decorator forces the cookie, and the page's script sends it back as X-CSRFToken on each POST.

How is this different from the Django guide?

The quickstart is the shortest path to a sealed test record: four views, the session, and a fixed test signer. The guide is a whole signup app, with a model that stores the acceptance, the signer's own details, and the record.completed webhook.

Does the Django 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

Run on 2026-11-26 with Django 4.2.30 and requests 2.32.5 on Python 3.9.25, with the browser SDK script build and the conformance check from esigncomply 1.0.4, against the API in test mode.

Last updated · API version 2026-11-21