# Add e-signatures and clickwrap with Kotlin

> Build a signup clickwrap in Kotlin with Ktor. The Ktor client and kotlinx.serialization call the Esign Comply REST API, and a signed cookie holds the state.

Source: https://esigncomply.com/docs/quickstart/kotlin

Last updated November 26, 2026

To add e-signatures and clickwrap with Kotlin, call the REST API from a Ktor server with its client and the secret key: there is no package. One file creates the session, keeps the pinned versions in a cookie Ktor signs, and confirms the record. The browser SDK attaches to your 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 Kotlin with Ktor. Kotlin's documentation names Ktor and Spring first among the frameworks for a server app, and Ktor is the one JetBrains builds for Kotlin. For an app on Spring Boot, in Kotlin or Java, use the [Spring Boot quickstart](https://esigncomply.com/docs/quickstart/spring-boot.md). For a service with no framework, the [Java quickstart](https://esigncomply.com/docs/quickstart/java.md) uses the JDK alone.

Paste this prompt into Cursor, Claude Code or another AI coding tool to have it build the same integration:

```text copy="Copy prompt" open="cursor"
Add Esign Comply clickwrap to my Kotlin 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/kotlin.md (the steps and the tested code for Kotlin)
- https://esigncomply.com/setup.md (the order of API calls)
- https://esigncomply.com/auth.md (how to handle the keys)

Kotlin facts
- There is no Esign Comply package for Kotlin or the JVM. Do not install or invent one. The server calls the REST API at https://esigncomply.com/v1 with the Ktor client, 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. Ktor does not read .env files. Take it from the environment in application.yaml ($ESIGNCOMPLY_API_KEY, no default) so that a missing key stops the server at start. Never print the key.
- Ktor client: use the engine the project already has. The CIO engine speaks HTTP/1.1 only. The Java engine asks a plain-http server to upgrade to HTTP/2 unless protocolVersion is HTTP_1_1. Install HttpTimeout. The client does not throw on 4xx and 5xx unless expectSuccess is set: read status and the error envelope.
- HttpRequestRetry with no settings retries 5xx answers and exceptions three times. Configure it to retry a 429 only, twice, with retryOnExceptionIf returning false, and compute the delay from Retry-After yourself, 1 to 5 seconds: respectRetryAfterHeader has no upper limit.
- kotlinx.serialization: build Json with ignoreUnknownKeys = true, name the API's snake_case fields with @SerialName, and give every field you read a default. Declare livemode as Boolean? with the default null: a Boolean with the default false reads a missing field as false. A Map<String, Any> has no serializer: use data classes or buildJsonObject.
- Never block a thread in a route: wait with delay, not Thread.sleep.
- Keep the signer ID and the pinned version IDs in a Sessions cookie with SessionTransportTransformerMessageAuthentication. The visitor can read a signed cookie: put nothing secret in it.
- Install StatusPages with a handler for Throwable: without it Ktor answers 500 with the exception's message as the body.
- A string template escapes nothing. Print the document HTML as it is, and escape everything else you print.
- 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. Server: POST /api/ceremony calls POST /v1/sessions with an Idempotency-Key, saves the signer ID and the pinned version IDs in the signed session cookie, and returns only clientToken, apiUrl and documents.
4. Server: GET /legal/terms and /legal/privacy 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. Server: POST /api/signup/confirm calls GET /v1/records/{id} and requires: status is "recorded", "timestamped" or "anchored"; livemode is as expected; the signer ID and version IDs equal the ones in the session cookie. 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:8080/signup --callback http://localhost:8080/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](https://esigncomply.com/signup) 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](https://esigncomply.com/docs/api/agent.md).
- Nothing else from Esign Comply. Test mode works on `localhost` with no card and no domain, and the Free plan includes it in full.
- A JDK and Gradle. This page was run with Gradle 9.9.2 on Java 25, with Kotlin 2.4.21 and Ktor 3.6.2.
- `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

There is no artifact for the API. The server SDK exists for Node.js only, so a Kotlin server calls the REST API directly, and Ktor brings the client for that. To follow along in a new project:

```bash
mkdir esigncomply-quickstart && cd esigncomply-quickstart
mkdir -p src/main/kotlin src/main/resources
```

```kotlin file="settings.gradle.kts"
rootProject.name = "esigncomply-quickstart"
```

```kotlin file="build.gradle.kts"
plugins {
    kotlin("jvm") version "2.4.21"
    kotlin("plugin.serialization") version "2.4.21"
    id("io.ktor.plugin") version "3.6.2"
}

group = "com.example"
version = "1.0.0"

application {
    mainClass = "com.example.ApplicationKt"
}

repositories {
    mavenCentral()
}

dependencies {
    // The Ktor plugin brings the Ktor BOM, so the Ktor artifacts carry no version here.
    implementation("io.ktor:ktor-server-core")
    implementation("io.ktor:ktor-server-netty")
    implementation("io.ktor:ktor-server-config-yaml")
    implementation("io.ktor:ktor-server-sessions")
    implementation("io.ktor:ktor-server-content-negotiation")
    implementation("io.ktor:ktor-server-status-pages")
    implementation("io.ktor:ktor-serialization-kotlinx-json")
    implementation("io.ktor:ktor-client-cio")
    implementation("io.ktor:ktor-client-content-negotiation")
    implementation("ch.qos.logback:logback-classic:1.5.38")
}
```

Ktor is a set of artifacts, one for each thing it does. This build takes the server core, the Netty engine, the YAML configuration file, sessions, status pages and content negotiation with the kotlinx.serialization converter, and for the calls to the API the client with its CIO engine. Logback prints the log, with this configuration:

```xml file="src/main/resources/logback.xml"
<configuration>
    <appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
        <encoder>
            <pattern>%d{HH:mm:ss.SSS} %-5level %logger{24} - %msg%n</pattern>
        </encoder>
    </appender>
    <root level="INFO">
        <appender-ref ref="STDOUT"/>
    </root>
</configuration>
```

The Ktor documentation creates a project with its generator, which adds a Gradle wrapper. This page was run with a Gradle installation and the `gradle` command. In a project with a wrapper, type `./gradlew` where this page says `gradle`.

## Step 2. Set the key

Put the key in `.env` in the project folder. Ktor does not read this file: you load it into the shell that starts the app.

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

Step 4 keeps the pinned versions in a session cookie that Ktor signs. Add the key it signs with to the same file, as 64 hexadecimal characters:

```bash
printf 'SESSION_SIGN_KEY=%s\n' "$(head -c 32 /dev/urandom | od -An -tx1 | tr -d ' \n')" >> .env
```

The app takes every value from the environment through its configuration file:

```yaml file="src/main/resources/application.yaml"
ktor:
  application:
    modules:
      - com.example.ApplicationKt.module
  deployment:
    port: "$PORT:8080"

# Every value comes from the environment. A variable with no default must be set, or the server does not start.
esigncomply:
  apiUrl: "$ESIGNCOMPLY_API_URL:https://esigncomply.com/v1"
  apiKey: $ESIGNCOMPLY_API_KEY
  profileId: $ESIGNCOMPLY_PROFILE_ID
  termsId: $ESIGNCOMPLY_TERMS_ID
  privacyId: $ESIGNCOMPLY_PRIVACY_ID
  live: "$ESIGNCOMPLY_LIVE:false"
session:
  signKey: $SESSION_SIGN_KEY
```

A name with a colon has a default. A name without one must be set: in the test with `.env` not loaded, the server ended at start with `ApplicationConfigurationException: Required environment variable "ESIGNCOMPLY_API_KEY" not found and no default value is present`. A sign key that is not hexadecimal ended it with a `NumberFormatException`.

Load the file into your shell for the commands in steps 2, 3 and 7, then check that the key works:

```bash
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}'
```

```json
{
  "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`](https://esigncomply.com/docs/api/errors.md#invalid_api_key). The rules for handling keys are in [/auth.md](https://esigncomply.com/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`.

```bash
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:

```text
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](https://esigncomply.com/docs/conformance.md#cr-02) checks that it does. With your own documents, publish the text you already have and change the notice to match. See [Documents](https://esigncomply.com/docs/api/documents.md) and [Profiles](https://esigncomply.com/docs/api/profiles.md).

## Step 4. Create a session on the server

`Application.kt` is the whole server: the signup page, the two document pages, the route that creates the session, and the route that confirms the record. The class `EsignComply` is the entire client: one HTTPS call with the secret key that returns the response, sent again only when the API answers `429`.

```kotlin file="src/main/kotlin/Application.kt"
// src/main/kotlin/Application.kt
package com.example

import io.ktor.client.HttpClient
import io.ktor.client.call.body
import io.ktor.client.engine.cio.CIO
import io.ktor.client.plugins.HttpRequestRetry
import io.ktor.client.plugins.HttpTimeout
import io.ktor.client.plugins.contentnegotiation.ContentNegotiation as ClientContentNegotiation
import io.ktor.client.request.bearerAuth
import io.ktor.client.request.header
import io.ktor.client.request.request
import io.ktor.client.request.setBody
import io.ktor.client.statement.HttpResponse
import io.ktor.http.ContentType
import io.ktor.http.HttpHeaders
import io.ktor.http.HttpMethod
import io.ktor.http.HttpStatusCode
import io.ktor.http.contentType
import io.ktor.http.encodeURLPathPart
import io.ktor.serialization.kotlinx.json.json
import io.ktor.server.application.Application
import io.ktor.server.application.install
import io.ktor.server.application.log
import io.ktor.server.plugins.BadRequestException
import io.ktor.server.plugins.contentnegotiation.ContentNegotiation
import io.ktor.server.plugins.origin
import io.ktor.server.plugins.statuspages.StatusPages
import io.ktor.server.request.httpMethod
import io.ktor.server.request.path
import io.ktor.server.request.receiveText
import io.ktor.server.response.respond
import io.ktor.server.response.respondText
import io.ktor.server.routing.get
import io.ktor.server.routing.post
import io.ktor.server.routing.routing
import io.ktor.server.sessions.SessionTransportTransformerMessageAuthentication
import io.ktor.server.sessions.Sessions
import io.ktor.server.sessions.cookie
import io.ktor.server.sessions.get
import io.ktor.server.sessions.sessions
import io.ktor.server.sessions.set
import io.ktor.util.escapeHTML
import java.util.UUID
import kotlinx.serialization.SerialName
import kotlinx.serialization.Serializable
import kotlinx.serialization.SerializationException
import kotlinx.serialization.json.Json
import kotlinx.serialization.json.JsonObject
import kotlinx.serialization.json.addJsonObject
import kotlinx.serialization.json.buildJsonObject
import kotlinx.serialization.json.put
import kotlinx.serialization.json.putJsonArray
import kotlinx.serialization.json.putJsonObject

fun main(args: Array<String>): Unit = io.ktor.server.netty.EngineMain.main(args)

// kotlinx.serialization refuses a key that the class does not declare, and the API sends more fields than this app reads.
val JSON = Json { ignoreUnknownKeys = true }
val SEALED = setOf("recorded", "timestamped", "anchored")

// The signer. In your app this is the signed-in user, or the account you are about to create.
const val SIGNER_ID = "user_7c1d"
val SIGNER = buildJsonObject {
    put("external_id", SIGNER_ID)
    put("email", "dana@example.org")
    put("name", "Dana Whitfield")
    put("class", "consumer")
    put("country", "US")
    put("region", "US-CA")
}

// What this app reads from the API. The API's JSON is snake_case, so those fields carry @SerialName.
// Every field has a default: one the API did not send is null or empty, never false, and never stops the decoding.
@Serializable data class Doc(@SerialName("version_id") val versionId: String = "")
@Serializable data class ApiError(val code: String = "unknown")
@Serializable data class Session(@SerialName("client_token") val clientToken: String? = null, @SerialName("api_url") val apiUrl: String? = null, val documents: List<Doc> = emptyList(), val error: ApiError? = null)
@Serializable data class Content(@SerialName("version_id") val versionId: String = "", val html: String = "")
@Serializable data class Signer(@SerialName("external_id") val externalId: String? = null)
@Serializable data class SignedRecord(val id: String? = null, val status: String? = null, val livemode: Boolean? = null, val signer: Signer? = null, val documents: List<Doc> = emptyList())

// What the browser gets, and what the page posts back.
@Serializable data class Ceremony(val clientToken: String, val apiUrl: String, val documents: List<Doc>)
@Serializable data class Confirm(val recordId: String = "missing")

// Server-owned state: the Sessions plugin keeps it in a cookie that it signs.
@Serializable data class Pinned(val signerId: String, val versionIds: List<String>)

// There is no Kotlin package for the API: these are plain HTTPS calls with the secret key, made with the Ktor client.
class EsignComply(private val api: String, private val apiKey: String) {
    // CIO is Ktor's own coroutine engine. It speaks HTTP/1.1 only, so it never asks a server to upgrade to HTTP/2.
    private val http = HttpClient(CIO) {
        // Installed with no settings, HttpRequestRetry sends a request again up to three times after a 5xx answer or an exception.
        // Here it retries a 429 only, twice at most, and waits for Retry-After (1 to 5 seconds). Nothing else is retried.
        install(HttpRequestRetry) {
            retryIf(maxRetries = 2) { _, response -> response.status == HttpStatusCode.TooManyRequests }
            retryOnExceptionIf { _, _ -> false }
            delayMillis(respectRetryAfterHeader = false) {
                (response?.headers?.get(HttpHeaders.RetryAfter)?.toLongOrNull() ?: 1L).coerceIn(1L, 5L) * 1000
            }
        }
        install(HttpTimeout) {
            connectTimeoutMillis = 5_000
            requestTimeoutMillis = 10_000
        }
        install(ClientContentNegotiation) { json(JSON) }
    }

    /** One call to the Esign Comply API. The client does not throw on 4xx and 5xx: read status, and the error envelope is the body. */
    suspend fun request(method: HttpMethod, path: String, body: JsonObject? = null, idempotencyKey: String? = null): HttpResponse =
        http.request(api + path) {
            this.method = method
            bearerAuth(apiKey)
            if (idempotencyKey != null) header("Idempotency-Key", idempotencyKey)
            if (body != null) {
                contentType(ContentType.Application.Json)
                setBody(body)
            }
        }
}

fun Application.module() {
    // application.yaml fills these from the environment. A variable that is missing there stops the server at start.
    val config = environment.config
    val esc = EsignComply(config.property("esigncomply.apiUrl").getString(), config.property("esigncomply.apiKey").getString())
    val profile = config.property("esigncomply.profileId").getString()
    val documents = mapOf(
        "terms" to config.property("esigncomply.termsId").getString(),
        "privacy" to config.property("esigncomply.privacyId").getString(),
    )
    val live = config.property("esigncomply.live").getString() == "true" // set ESIGNCOMPLY_LIVE in production only
    // The page is a resource, so it travels inside the jar.
    val signupPage = checkNotNull(Application::class.java.getResource("/signup.html")) { "signup.html is not on the classpath" }.readText()

    install(ContentNegotiation) { json(JSON) }
    install(StatusPages) {
        // A request Ktor cannot read, such as a query string with a broken percent escape, keeps the 400 Ktor gives it.
        exception<BadRequestException> { call, _ -> call.respond(HttpStatusCode.BadRequest, mapOf("error" to "bad_request")) }
        // Without this, Ktor answers 500 with the exception's message as the body, and logs a failed API call at DEBUG only.
        exception<Throwable> { call, cause ->
            call.application.log.error("${call.request.httpMethod.value} ${call.request.path()}: $cause")
            call.respond(HttpStatusCode.InternalServerError, mapOf("error" to "internal_error"))
        }
    }
    install(Sessions) {
        cookie<Pinned>("esc_signup") {
            cookie.path = "/"
            cookie.httpOnly = true
            cookie.secure = live
            cookie.extensions["SameSite"] = "lax"
            // Signed, not encrypted: the visitor can read the cookie and cannot change it.
            transform(SessionTransportTransformerMessageAuthentication(config.property("session.signKey").getString().hexToByteArray()))
        }
    }

    routing {
        get("/signup") { call.respondText(signupPage, ContentType.Text.Html) }

        // The document pages: each one renders a registered version, unmodified.
        get("/legal/{slug}") {
            val document = documents[call.parameters["slug"]]
                ?: return@get call.respond(HttpStatusCode.NotFound, mapOf("error" to "not_found"))
            val version = call.request.queryParameters["v"]?.takeIf { it.matches(Regex("\\w+")) } ?: "current"
            val answer = esc.request(HttpMethod.Get, "/documents/$document/versions/$version/content")
            if (answer.status != HttpStatusCode.OK) return@get call.respond(HttpStatusCode.NotFound, mapOf("error" to "not_found"))
            val content = answer.body<Content>()
            // A string template escapes nothing. The version ID goes into an attribute, so it is escaped. The document HTML is printed as it is.
            call.respondText(
                """<!doctype html><meta charset="utf-8"><article data-esc-document="${content.versionId.escapeHTML()}">${content.html}</article>""",
                ContentType.Text.Html,
            )
        }

        // Step 4: create the session with the secret key. The browser gets the client token only.
        post("/api/ceremony") {
            // The page that runs the ceremony: the origin the browser reports, or the scheme and host of the request.
            val origin = call.request.headers[HttpHeaders.Origin]
                ?: "${call.request.origin.scheme}://${call.request.headers[HttpHeaders.Host]}"
            val created = esc.request(
                HttpMethod.Post, "/sessions",
                idempotencyKey = "signup-$SIGNER_ID-${UUID.randomUUID()}",
                body = buildJsonObject {
                    put("profile", profile)
                    put("signer", SIGNER)
                    putJsonArray("documents") {
                        addJsonObject { put("document", documents.getValue("terms")); put("version", "current") }
                        addJsonObject { put("document", documents.getValue("privacy")); put("version", "current") }
                    }
                    putJsonObject("context") {
                        put("url", "$origin/signup")
                        put("locale", "en-US")
                        put("purpose", "account_signup")
                    }
                },
            )
            val session = created.body<Session>()
            if (created.status != HttpStatusCode.Created || session.clientToken == null || session.apiUrl == null) {
                return@post call.respond(HttpStatusCode.BadGateway, mapOf("error" to (session.error?.code ?: "unknown")))
            }

            call.sessions.set(Pinned(SIGNER_ID, session.documents.map { it.versionId }.sorted()))
            call.respond(Ceremony(session.clientToken, session.apiUrl, session.documents))
        }

        // Step 6: confirm the record with the secret key before the account exists.
        post("/api/signup/confirm") {
            // An empty or malformed body is refused below like a made-up record ID.
            val recordId = try { JSON.decodeFromString<Confirm>(call.receiveText()).recordId } catch (malformed: SerializationException) { "missing" }
            val expected = call.sessions.get<Pinned>()
            val answer = esc.request(HttpMethod.Get, "/records/${recordId.encodeURLPathPart()}")
            val record = answer.body<SignedRecord>()

            val confirmed = answer.status == HttpStatusCode.OK &&
                record.status in SEALED &&
                record.livemode == live &&
                expected != null && record.signer?.externalId == expected.signerId &&
                record.documents.map { it.versionId }.sorted() == expected.versionIds

            log.info(if (confirmed) "confirmed ${record.id} (${record.status})" else "refused")
            if (!confirmed) return@post call.respond(HttpStatusCode.Conflict, mapOf("confirmed" to false))

            // Only now create the account, and store record.id and the receipt with it.
            call.respond(buildJsonObject { put("confirmed", true); put("recordId", record.id) })
        }
    }
}
```

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.

Eight things here are specific to Kotlin and Ktor, and each one was seen in the test run.

kotlinx.serialization refuses a key the class does not declare. With the default `Json`, a session answer read into a class that names one of its fields threw `JsonDecodingException: Encountered an unknown key 'id'`. `ignoreUnknownKeys = true` reads it. The API's fields are snake_case, and a property `clientToken` without `@SerialName("client_token")` stayed `null` with no error. `JsonNamingStrategy.SnakeCase` renames every field at once, but it is marked experimental in kotlinx.serialization 1.11.0, and in the test the same `Json` instance then wrote `client_token` and `api_url` into the answer for the browser, where the page reads `clientToken`. So each field is named.

Every field has a default. An error envelope read into a class whose fields have none threw `MissingFieldException: Fields [status, livemode] are required`. With `livemode: Boolean = false` the same envelope gave `false`, which is exactly what a test deployment expects. With `Boolean? = null` it gave `null`, and the check fails. A `Map<String, Any>` has no serializer: `mapOf("confirmed" to true, "recordId" to id)` threw `SerializationException: Serializer for class 'Any' is not found`, so the answers with mixed values are built with `buildJsonObject`.

The client engine is CIO, and it speaks HTTP/1.1 only. That matters over plain http. In the test, Ktor's Java engine with its defaults failed against the test API, which runs over plain http, with `IOException: HTTP/1.1 header parser received no bytes`: its request carried `Upgrade: h2c`, and the test API closes such a connection. With `protocolVersion = HTTP_1_1` the same engine was answered. CIO sent no such header. `HttpTimeout` gives each attempt 10 seconds. Without it CIO gave up on a server that never answers after 15 seconds. The client does not throw on a refusal: a made-up record ID came back as status `404`. Calls over https were not run.

The retry is Ktor's own plugin, `HttpRequestRetry`, with each of its defaults replaced. Installed with no settings, it sent a `GET` four times to a server that always answered `500`, and it sent a `POST` four times to a server that closed the connection. With only `retryIf` set, that `POST` was still sent three times. With the settings on this page each was sent once. The plugin reads `Retry-After` by itself, with no upper limit: with a header of 8 seconds it waited 8 seconds, twice. So the page computes the wait: the seconds in `Retry-After`, 1 at least and 5 at most. 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 is a coroutine `delay`, so it holds no thread. Sixteen requests at once to a route that calls `delay(3_000)` were all answered after 3.0 seconds, and a page request sent meanwhile took 0.004 seconds. With `Thread.sleep(3_000)` in the route they finished four at a time, after 3, 6, 9 and 12 seconds, on a machine with four cores, and the page request waited 11.5 seconds. In the burst test of this page, page requests were answered in under 0.01 seconds while two confirmations waited to retry.

The state is a cookie that the `Sessions` plugin signs. The browser got a cookie named `esc_signup`, 194 characters long, `HttpOnly`, `SameSite=lax`, with `Max-Age=604800`: seven days, Ktor's default. It is signed, not encrypted. Its value is URL-encoded JSON, a slash and the signature: decoded, it showed the signer ID and the two version IDs. The visitor can read them and cannot change them. With one character of the signature changed, with the signature cut to 10 characters, with no signature, and with another signer ID in the payload, the confirm route answered `409`. With `SESSION_SIGN_KEY` fixed, the same cookie confirmed a real record after a restart.

Ktor catches what a route throws, and the server keeps running. What it answers needs `StatusPages`. Without the plugin, and the API address on a closed port, the session route answered `500` with the exception's message as the body, `Connection refused (connect failed)`, and logged nothing at the `INFO` level. A call that timed out put the API address and a document ID into the body. With the handler on this page the answer was `{"error":"internal_error"}`, the log had `ERROR Application - POST /api/ceremony: java.net.ConnectException`, and the next request was answered `200`. A second handler answers `400` for a request Ktor cannot read, which the catch-all would turn into `500`: a query string with a broken percent escape, `?v=%zz`, was answered `400`.

`context.url` is built from the `Origin` header the browser sends with the `POST`, and from the scheme and the `Host` header of the request when there is none. All of it comes from the client. A request with `Origin: https://evil.example` was refused by the API with `domain_mismatch`, and the route answered `502`. So was a request with `Host: evil.example` and no `Origin`. Ktor does not read `X-Forwarded-Proto` on its own: with that header set to `https` and no `Origin`, the URL the route built still started with `http://`.

## 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 `src/main/resources/signup.html`. The app reads it from the classpath once, when it starts:

```html file="src/main/resources/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");

      // Your server creates the session and returns only the client token and the pinned documents.
      const response = await fetch("/api/ceremony", { method: "POST" });
      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" },
            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>
```

Start the app from the shell that loaded `.env`:

```bash
gradle run
```

```text
INFO  Application - Application started in 0.448 seconds.
INFO  Application - Responding at http://0.0.0.0:8080
```

That is every interface of the machine: in the test the page answered on the machine's own address too, not only on `localhost`. On Java 25 the start also printed four `WARNING` lines about a restricted method that Netty calls. Started with `java --enable-native-access=ALL-UNNAMED`, the jar from step 8 printed none.

Open [http://localhost:8080/signup](http://localhost:8080/signup). The button stays disabled until the box is ticked. Tick it, click **Create account**, and the page shows:

```text
Account created. Record rec_SCHw2yowbUJGJM8UvwX9
```

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](https://esigncomply.com/docs/conformance.md#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`.

Each link opens a document page on your own server that renders the registered version. The route builds that page with a string template, which escapes nothing. The document arrives as it is, which is what this page needs, and the version ID is escaped with `escapeHTML()` because it goes into an attribute. In a test with `escapeHTML()` around the document too, the page showed the tags as text and the SDK reported a finding for [CR-08](https://esigncomply.com/docs/conformance.md#cr-08) at Block level: the page behind the link did not match the registered version.

## 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 route for `POST /api/signup/confirm` 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 cookie; and the document versions are exactly the ones this server pinned there. This step is never optional.

The app logs one line for each confirmation:

```text
INFO  Application - confirmed rec_SCHw2yowbUJGJM8UvwX9 (recorded)
```

A record ID that was made up is refused with status `409`. So is a real record ID sent without the cookie, a body that is not JSON, an empty body, and a body whose `recordId` is a number:

```bash
curl -s -X POST http://localhost:8080/api/signup/confirm \
  -H "Content-Type: application/json" -d '{"recordId":"rec_made_up"}'
```

```json
{"confirmed":false}
```

See [Server confirmation](https://esigncomply.com/docs/guides/server-confirmation.md) for the webhook that backs this route 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:

```bash
mkdir -p esc-check && cd esc-check
npm init -y && npm install esigncomply playwright
npx playwright install chromium
npx esigncomply check --url http://localhost:8080/signup --callback http://localhost:8080/api/signup/confirm
```

The report for this page's code, shortened:

```text
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:8080/api/signup/confirm answered 409.

Ceremonies
  390x844    record rec_rVDGnNi9dRJg4J4Un2Wb  session ses_Tm0AVeqXU6pxCB4YCPRX, 5 events
  768x1024   record rec_eBMWfmDMtrXGGZB9aAUd  session ses_GUnLtPYxgpLaPJHKe4nu, 5 events
  1440x900   record rec_kjVwYLUNUGZnruVMeV0S  session ses_hcCFmZu71THkrnAoErYY, 5 events

Summary: 0 block, 0 warn, 27 pass.
```

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](https://esigncomply.com/docs/conformance.md), and every flag of the command is on the [CLI page](https://esigncomply.com/docs/sdk/cli.md).

## 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](https://esigncomply.com/docs/guides/domains.md).
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 server over:

- Build one file with `gradle buildFatJar` and start it with `java -jar build/libs/esigncomply-quickstart-all.jar`. In the test the jar was 34 MB and the conformance check in step 7 ran against it. It ran as one process of about 150 MB. `gradle run` kept three Java processes with about 620 MB between them: the app, and Gradle beside it.
- The page is a resource inside the jar. Started from another folder, the jar still answered `/signup` with `200`.
- Set the live key as `ESIGNCOMPLY_API_KEY` and set `ESIGNCOMPLY_LIVE=true` in production only. In the test with that variable set, the confirm route refused a test record with `409`, and the cookie was marked `Secure`. `cookie.secure` follows the variable and does not look at the request: serve the site over HTTPS.
- Set `PORT` when your host gives you one. The app listens on 8080 otherwise.
- Keep one `SESSION_SIGN_KEY` for every instance and every restart, and store the record ID and the receipt beside the user. In the test, a cookie signed with another key was refused with `409`.

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

- **`ApplicationConfigurationException: Required environment variable "ESIGNCOMPLY_API_KEY" not found` when the app starts.** The variables are not in the environment of the shell that starts the app. Run `set -a; . ./.env; set +a` in that shell first. With the variable set and empty, the app started and the session route answered `502` with [`missing_api_key`](https://esigncomply.com/docs/api/errors.md#missing_api_key).
- **`JsonDecodingException: Encountered an unknown key`.** The `Json` instance that reads the API's answer was built without `ignoreUnknownKeys = true`. The API sends more fields than the app's classes declare. Pass the same `JSON` instance to the client's `ContentNegotiation`, as `Application.kt` does.
- **`domain_mismatch` from `/api/ceremony`.** `context.url` is built from the `Origin` or `Host` header, and that host is not on the test allowlist. Test keys work on `localhost` and `127.0.0.1` at any port. Add other hosts under Domains in the dashboard. See [`domain_mismatch`](https://esigncomply.com/docs/api/errors.md#domain_mismatch).
- **`429` when the confirm route reads the record.** `HttpRequestRetry` waits for the seconds in `Retry-After`, 1 at least and 5 at most, and 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 answered `200`, two of them a second later than the others. The API's log showed why: two reads got `429` and passed on the next attempt. See [`rate_limit_exceeded`](https://esigncomply.com/docs/api/errors.md#rate_limit_exceeded). When the route answers `409` for a real record, the cause is a `SESSION_SIGN_KEY` that changed.

## Questions about the Kotlin quickstart

### Is there an Esign Comply library for Kotlin?

No. The server SDK exists for Node.js only. A Kotlin server calls the REST API directly, and this quickstart does it with the Ktor client in one small class. The build lists Ktor's own artifacts and Logback, and nothing for the API.

### Why Ktor and not Spring Boot?

Because Ktor is the framework JetBrains builds for Kotlin, and Spring Boot has a quickstart of its own. Kotlin's documentation names both first for server apps. Use the Spring Boot quickstart when your app already runs on Spring: it makes the same two calls with `RestClient` and keeps the pinned versions in the `HttpSession`.

### Which Ktor client engine does the code use?

CIO, Ktor's own coroutine engine. It speaks HTTP/1.1 only, so it never asks a plain-http server to upgrade to HTTP/2. In the test, the Java engine with its defaults did ask, and its call to the test API failed with an IOException until `protocolVersion` was set to `HTTP_1_1`.

### Can the visitor read the session cookie?

Yes, and that is safe. The cookie is signed, not encrypted: URL-decoded it showed the signer ID and the two version IDs, and nothing else is in it. The visitor cannot change it. In the test a cookie with a changed signature or a changed payload was refused with status 409.

### Does a request that waits to retry hold a thread?

No. The wait is a coroutine delay, which suspends the request and frees the thread. In the test, page requests sent while two confirmations waited to retry were answered in under 0.01 seconds. The same test with `Thread.sleep` in a route made a page request wait 11.5 seconds.

### Does the Kotlin 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 Kotlin](https://esigncomply.com/kotlin): what the integration gives you on this stack, with the things to watch for.
- [Add e-signatures and clickwrap with Spring Boot](https://esigncomply.com/docs/quickstart/spring-boot.md): the same calls with `RestClient`, Jackson and the `HttpSession`.
- [Add e-signatures and clickwrap with Java](https://esigncomply.com/docs/quickstart/java.md): the same calls with the JDK alone.
- [Server confirmation](https://esigncomply.com/docs/guides/server-confirmation.md): the checks in step 6 and the `record.completed` webhook.
- [Sessions API](https://esigncomply.com/docs/api/sessions.md) and [Records API](https://esigncomply.com/docs/api/records.md): every field of the two calls this app makes.
- [All quickstarts](https://esigncomply.com/docs/quickstart.md#quickstarts-by-stack-and-platform).
