Skip to content

Tutorials

Java and Spring Boot Tutorial: Send, Embed and Track a Contract

Build a Spring Boot app that sends a contract, embeds the signing ceremony, verifies webhooks on the raw body and downloads the signed PDF.

This tutorial builds a complete Spring Boot app with SignatureAPI: your server creates an envelope, the user signs inside your page, a verified webhook reports the result, and your server downloads the signed PDF. The API client uses the JDK’s java.net.http.HttpClient, so you can move it to any Java app.

The app has one page and four server routes:

  • GET /: a form and the ceremony iframe.
  • POST /api/contracts: creates the envelope and returns the ceremony URL.
  • GET /api/contracts/{id}: reads the envelope status on the server.
  • GET /api/contracts/{id}/signed.pdf: streams the signed PDF.
  • POST /webhooks/signatureapi: receives events and verifies each one.

Before you start

  • Java 21. The Maven wrapper downloads Maven.
  • A test API key (key_test_...) from the Dashboard. Test envelopes are free, send no emails and are not legally binding. See Test mode.
  • To receive webhooks on your machine, a public tunnel to your local port and a webhook endpoint for it in Dashboard > Settings > Webhooks. Copy the endpoint’s signing secret. See Set Up Webhooks.

1. Create the envelope on your server

The API key stays on your server. buildContract builds the envelope with three recipient options for embedding:

  • delivery_type: "none": SignatureAPI doesn’t email the signed PDF, because your app shows the result.
  • custom authentication: your app already signed the user in, so the ceremony URL comes back in the response instead of an email.
  • embeddable_in: the origin allowed to show the ceremony in an iframe.
SignatureApi.java
public static Map<String, Object> buildContract(String name, String email, String userId, String appOrigin) {
  return Map.of(
      "title", "Service Agreement",
      "metadata", Map.of("app_user_id", userId),
      "documents", List.of(Map.of(
          "url", "https://pub-9cb75390636c4a8a83a6f76da33d7f45.r2.dev/docs-samples/service-agreement.pdf",
          "format", "pdf",
          "places", List.of(Map.of("key", "client_signature", "type", "signature", "recipient_key", "client")),
          "fixed_positions", List.of(Map.of("place_key", "client_signature", "page", 1, "top", 172, "left", 210)))),
      "recipients", List.of(Map.of(
          "key", "client",
          "type", "signer",
          "name", name,
          "email", email,
          "delivery_type", "none",
          "ceremony", Map.of(
              "authentication", List.of(Map.of(
                  "type", "custom", "provider", "Acme Corp Portal", "data", Map.of("user_id", userId))),
              "embeddable_in", List.of(appOrigin)))));
}

The envelope starts in processing, and the ceremony opens only once it is in_progress. createSigningSession reads the envelope once a second until then and returns the ceremony URL from that read. Every read returns a new URL for the same ceremony.

SignatureApi.java
public SigningSession createSigningSession(String name, String email, String userId) throws InterruptedException {
  JsonNode envelope = call("POST", "/v1/envelopes", buildContract(name, email, userId, settings.appOrigin()));
  for (int attempt = 0; envelope.path("status").asText().equals("processing") && attempt < 30; attempt++) {
    Thread.sleep(1000);
    envelope = call("GET", "/v1/envelopes/" + envelope.path("id").asText(), null);
  }
  if (!envelope.path("status").asText().equals("in_progress")) {
    throw new ApiException("Envelope is " + envelope.path("status").asText() + ", not ready for signing");
  }
  return new SigningSession(
      envelope.path("id").asText(), envelope.path("recipients").path(0).path("ceremony").path("url").asText());
}

2. Embed the ceremony

The page adds embedded=true and event_delivery=message to the ceremony URL and loads it in an iframe. It accepts ceremony events only from https://sign.signatureapi.com and from its own iframe.

static/index.html
const CEREMONY_ORIGIN = 'https://sign.signatureapi.com';
const iframe = document.getElementById('signatureapi-ceremony');
const status = document.getElementById('status');
let envelopeId = null;

document.getElementById('start').addEventListener('submit', async (event) => {
  event.preventDefault();
  const form = new FormData(event.target);
  const response = await fetch('/api/contracts', {
    method: 'POST',
    headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify({ name: form.get('name'), email: form.get('email') }),
  });
  const body = await response.json();
  if (!response.ok) { status.textContent = body.error; return; }
  envelopeId = body.envelopeId;
  // Both query parameters are required for an embedded ceremony.
  const src = new URL(body.ceremonyUrl);
  src.searchParams.set('embedded', 'true');
  src.searchParams.set('event_delivery', 'message');
  iframe.src = src.toString();
  iframe.classList.remove('hidden');
});

window.addEventListener('message', async (event) => {
  // Accept messages only from the ceremony iframe.
  if (event.origin !== CEREMONY_ORIGIN || event.source !== iframe.contentWindow) return;
  if (event.data.type === 'ceremony.completed') {
    iframe.classList.add('hidden');
    // The browser event is a UI signal. Confirm on your server before you act on it.
    const response = await fetch(`/api/contracts/${envelopeId}`);
    const body = await response.json();
    status.textContent = `Thanks! Envelope status: ${body.status}`;
    // The signed PDF is ready a few seconds after completion. Your server streams it (step 5).
    const download = document.getElementById('download');
    download.href = `/api/contracts/${envelopeId}/signed.pdf`;
    download.classList.remove('hidden');
  } else if (event.data.type === 'ceremony.canceled') {
    status.textContent = 'Signing canceled. You can start again any time.';
  } else if (event.data.type === 'ceremony.failed') {
    status.textContent = `Signing failed: ${event.data.error_message}`;
  }
});

A ceremony.completed message is a signal for your UI, not proof of signing: the page asks your server for the envelope status before it shows the result. To send the signer to the ceremony page instead of embedding it, open the URL without embedded=true and set a redirect URL for the way back.

3. Verify webhooks on the raw body

SignatureAPI signs every delivery with the Standard Webhooks scheme. WebhookVerifier.verify computes an HMAC-SHA256 over webhook-id.webhook-timestamp.body with your signing secret, compares it in constant time with each v1 entry of webhook-signature, and rejects timestamps more than 5 minutes off. It runs on the exact bytes received: parsing and re-serializing the JSON changes them and breaks the signature.

WebhookVerifier.java
public static void verify(
    String secret,
    Map<String, String> headers,
    byte[] rawBody,
    long nowSeconds,
    long toleranceSeconds)
    throws VerificationException {
  Map<String, String> lower = new TreeMap<>(String.CASE_INSENSITIVE_ORDER);
  lower.putAll(headers);
  String id = lower.get("webhook-id");
  String timestamp = lower.get("webhook-timestamp");
  String signatureHeader = lower.get("webhook-signature");
  if (isEmpty(id) || isEmpty(timestamp) || isEmpty(signatureHeader)) {
    throw new VerificationException(
        "Missing webhook-id, webhook-timestamp or webhook-signature header");
  }
  if (!timestamp.matches("\\d{1,18}")) {
    throw new VerificationException("Invalid webhook-timestamp");
  }
  if (Math.abs(nowSeconds - Long.parseLong(timestamp)) > toleranceSeconds) {
    throw new VerificationException("Timestamp outside the tolerance window");
  }

  byte[] expected;
  try {
    byte[] key = Base64.getDecoder().decode(secret.replaceFirst("^whsec_", ""));
    Mac mac = Mac.getInstance("HmacSHA256");
    mac.init(new SecretKeySpec(key, "HmacSHA256"));
    mac.update((id + "." + timestamp + ".").getBytes(StandardCharsets.UTF_8));
    expected = mac.doFinal(rawBody);
  } catch (Exception e) {
    throw new VerificationException("Cannot compute signature: " + e.getMessage());
  }

  // The header holds space-separated "v1,<base64>" entries. Any match is enough.
  for (String entry : signatureHeader.split(" ")) {
    String[] parts = entry.split(",", 2);
    if (parts.length != 2 || !parts[0].equals("v1")) {
      continue;
    }
    try {
      byte[] candidate = Base64.getDecoder().decode(parts[1]);
      if (MessageDigest.isEqual(candidate, expected)) {
        return;
      }
    } catch (IllegalArgumentException ignored) {
      // Not base64: try the next entry.
    }
  }
  throw new VerificationException("No matching signature");
}

The handler receives the body as @RequestBody byte[], verifies it, and skips any webhook-id it has already processed. Deliveries are retried for up to 48 hours and can repeat, so in production store the ids with a unique index. See Webhooks.

ContractController.java
// Step 3: SignatureAPI calls this endpoint. Verify the RAW body (byte[]), never re-serialized JSON.
@PostMapping("/webhooks/signatureapi")
public ResponseEntity<Map<String, Object>> webhook(@RequestBody byte[] rawBody, @RequestHeader Map<String, String> requestHeaders) {
  Map<String, String> headers = new TreeMap<>(String.CASE_INSENSITIVE_ORDER);
  headers.putAll(requestHeaders);
  try {
    WebhookVerifier.verify(api.settings().webhookSecret(), headers, rawBody, clock.instant().getEpochSecond(), 300);
  } catch (WebhookVerifier.VerificationException e) {
    return ResponseEntity.badRequest().body(Map.of("error", e.getMessage()));
  }
  if (!seenWebhookIds.add(headers.get("webhook-id"))) {
    return ResponseEntity.ok(Map.of("duplicate", true));
  }
  JsonNode event = json.readTree(new String(rawBody, StandardCharsets.UTF_8));
  String type = event.path("type").asText();
  String envelopeId = event.path("data").path("envelope_id").asText("");
  Contract contract = contracts.computeIfAbsent(envelopeId, k -> new Contract("unknown"));
  contract.events.add(type);
  if (type.equals("envelope.completed")) {
    contract.status = "completed";
  }
  log.info("webhook {} for envelope {}", type, envelopeId);
  return ResponseEntity.ok(Map.of("received", true));
}

4. Confirm the status

GET /api/contracts/{id} reads the envelope with GET /v1/envelopes/{id} and returns its status, together with the webhook events stored for it. The page calls it after the ceremony finishes.

5. Download the signed PDF

When the envelope completes, SignatureAPI generates the deliverable: the signed PDF with its audit log. downloadSignedPdf reads the envelope, gets its deliverable, and downloads the file from the deliverable’s url. That URL is pre-signed and expires after 1 hour, so the function asks for a fresh one on each download instead of storing it.

SignatureApi.java
public byte[] downloadSignedPdf(String envelopeId) {
  JsonNode envelope = call("GET", "/v1/envelopes/" + envelopeId, null);
  String status = envelope.path("status").asText();
  if (!status.equals("completed") || envelope.path("deliverable").isMissingNode() || envelope.path("deliverable").isNull()) {
    throw new NotReadyException("Envelope is " + status + ". The signed PDF exists once it is completed.");
  }
  JsonNode deliverable = call("GET", "/v1/deliverables/" + envelope.path("deliverable").path("id").asText(), null);
  if (!deliverable.path("status").asText().equals("generated")) {
    throw new NotReadyException("Deliverable is " + deliverable.path("status").asText() + ". Try again in a few seconds.");
  }
  HttpRequest file = HttpRequest.newBuilder(URI.create(deliverable.path("url").asText())).timeout(Duration.ofSeconds(60)).build();
  return send(file, HttpResponse.BodyHandlers.ofByteArray()).body();
}

Until the deliverable is generated, the route answers 409 and the page can try again a few seconds later. To store the PDF as soon as it exists, call the same function when your webhook handler receives deliverable.generated.

Run it

Terminal
export SIGNATUREAPI_KEY=YOUR_API_KEY            # your test key
export SIGNATUREAPI_WEBHOOK_SECRET=whsec_YOUR_SECRET
export APP_ORIGIN=http://localhost:8080
./mvnw spring-boot:run

Open http://localhost:8080, keep the sample name and email, and select Start signing. After you sign, the page shows Thanks! Envelope status: completed and a link to the signed PDF.

Test it

Terminal
./mvnw test

The tests check the webhook verifier against a fixed test vector, then run the app against a local mock API: the envelope payload, the 422 path, webhook acceptance, tampering and duplicates, and the PDF download. With SIGNATUREAPI_KEY set to a test key, two more tests run against the API: one creates an embedded envelope and waits for in_progress, the other completes an envelope with an automatic signer and downloads its signed PDF.

Troubleshooting

  • The iframe is blank or refuses to load. embeddable_in must match your page’s origin exactly (scheme, host and port), and the URL needs embedded=true.
  • The ceremony asks the signer to try again later. The envelope was still processing. Show the URL only after the envelope is in_progress, as step 1 does.
  • No message events arrive. Add event_delivery=message to the URL and check that the origin filter uses https://sign.signatureapi.com.
  • Every webhook fails verification. Each endpoint has its own signing secret, and a proxy or body parser may have changed the body before verification.
  • The download returns 409. The deliverable is still being generated. Wait for deliverable.generated or try again in a few seconds.

Next steps