Skip to content

Latest commit

 

History

History

python-django

Folders and files

README.md

Python and Django e-signature tutorial: send, embed and track a contract with webhooks

A complete Django app that sends a contract for signature, lets the user sign it inside your page (embedded ceremony), and tracks the result with verified webhooks.

The problem

Most e-signature integrations need three things working together: a server call that creates the envelope, a signing experience that keeps users in your product, and a reliable way to learn when signing is done. Getting any one wrong leaks your API key, breaks the iframe, or trusts forged webhook calls.

What you build

A small Django project (views.py, about 110 lines; the API client uses only the standard library):

Route Purpose
GET / A page with a form and the ceremony iframe
POST /api/contracts Creates the envelope on the server and returns the ceremony URL
GET /api/contracts/{id} Confirms the envelope status on the server
GET /api/contracts/{id}/signed.pdf Streams the signed PDF (the deliverable) through your server
POST /webhooks/signatureapi Receives events, verifies the signature on the raw body, dedupes retries

Prerequisites

  • Python 3.10 or newer.
  • A SignatureAPI test API key (key_test_...). Sign up for free.
  • For webhooks on your machine: a webhook endpoint in the dashboard pointing at a public tunnel, or npx signatureapi listen from the SignatureAPI CLI, which forwards test events and saves the signing secret.

Step by step

1. Create the envelope on your server

The browser never sees your API key. POST /api/contracts calls create_signing_session(), which builds the envelope with build_contract() and sets three recipient options for embedding:

"recipients": [{
    "key": "client", "type": "signer", "name": name, "email": email,
    "delivery_type": "none",  # your app shows the result; no emails
    "ceremony": {
        "authentication": [{"type": "custom", "provider": "Acme Corp Portal", "data": {"user_id": user_id}}],
        "embeddable_in": [app_origin],  # the origin allowed to frame the ceremony
    },
}],

custom authentication records that your app already signed the user in, so the ceremony URL comes back in the response at recipients[0].ceremony.url.

The envelope starts in processing, and the ceremony opens only once it is in_progress. create_signing_session() reads the envelope once a second until then and returns the ceremony URL from that read.

2. Embed the ceremony

templates/index.html adds the two required query parameters and loads the URL in an iframe:

src.searchParams.set('embedded', 'true');
src.searchParams.set('event_delivery', 'message');

It accepts message events only when event.origin is https://sign.signatureapi.com and event.source is the iframe. A ceremony.completed message is a UI signal, so the page then asks your server for the real status.

3. Verify webhooks on the raw body

SignatureAPI signs each delivery with the Standard Webhooks scheme. verify_webhook() computes an HMAC-SHA256 over webhook-id.webhook-timestamp.body with your signing secret, compares in constant time, and rejects timestamps older than 5 minutes. The view runs it on request.body, the exact bytes received: parsing and re-serializing the JSON first changes the bytes and breaks the signature. The sender cannot present a CSRF token, so the view is marked @csrf_exempt. The signature is the authentication.

4. Make the handler idempotent

Deliveries retry for up to 48 hours and can arrive out of order. The handler remembers each webhook-id and answers duplicates with 200 without processing them again. In production, store the ids in your database with a unique index.

5. Download the signed PDF

When the envelope completes, SignatureAPI generates the deliverable: the signed PDF with its audit log. download_signed_pdf() 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 app requests a fresh one on each download instead of storing it, and sends no API key to it. Until the deliverable is generated, the route answers 409 and the page can try again a few seconds later.

Run it

python3 -m venv .venv && . .venv/bin/activate
pip install -r requirements.txt
export SIGNATUREAPI_KEY=key_test_YOUR_KEY
export SIGNATUREAPI_WEBHOOK_SECRET=whsec_...   # from the webhook endpoint in the dashboard
export APP_ORIGIN=http://localhost:8000
python manage.py runserver

Open http://localhost:8000, keep the sample name and email, and select Start signing.

Expected output

Starting development server at http://127.0.0.1:8000/
"POST /api/contracts HTTP/1.1" 201
webhook recipient.completed for envelope eb4cf433-a8af-4161-b37b-7ef57d423e56
webhook envelope.completed for envelope eb4cf433-a8af-4161-b37b-7ef57d423e56

After signing, the page shows Thanks! Envelope status: completed.

Run the tests

python manage.py test -v 2

The tests run the shared webhook test vector through the verifier, then drive the app with Django's test client (CSRF checks on) against a local mock API and check the envelope payload, the 422 path, webhook acceptance, tamper rejection, duplicate handling and the PDF download. With SIGNATUREAPI_KEY set, live tests create a real embedded-ceremony envelope in test mode and download the signed PDF of an automatic-signer envelope.

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.
  • No message events arrive: add event_delivery=message to the URL, and check that your origin filter uses https://sign.signatureapi.com.
  • Every webhook returns 400 Invalid webhook signature: wrong secret (each endpoint has its own), or a proxy changed the body before verification.
  • Webhook timestamp outside the tolerance window: your server clock is off. Sync it with NTP.
  • ceremonyUrl is null: the recipient is not using custom authentication. With email_link, SignatureAPI emails the link instead.

Learn more