---
title: "Go Tutorial: Send, Embed and Track a Contract"
description: "Build a Go app with net/http that sends a contract, embeds the signing ceremony, verifies webhooks and downloads the signed PDF, standard library only."
canonical: "https://signatureapi.com/docs/tutorials/go"
source: "https://signatureapi.com/docs/tutorials/go.md"
last_verified_api_version: "1.18.0"
last_modified: "2026-11-18T17:33:13Z"
---

# Go Tutorial: Send, Embed and Track a Contract

Build a Go app with net/http that sends a contract, embeds the signing ceremony, verifies webhooks and downloads the signed PDF, standard library only.

_Last verified against API version 1.18.0._

This tutorial builds a complete Go 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. It uses only the standard library (`net/http`, `crypto/hmac`, `encoding/json`) and Go 1.22 routing patterns.

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

- Go 1.23 or newer.
- A test API key (`key_test_...`) from the [Dashboard](https://dashboard.signatureapi.com). Test envelopes are free, send no emails and are not legally binding. See [Test mode](https://signatureapi.com/docs/api/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](https://dashboard.signatureapi.com/settings/webhooks). Copy the endpoint's signing secret. See [Set Up Webhooks](https://signatureapi.com/docs/api/guides/how-to/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](https://signatureapi.com/docs/api/resources/ceremonies/authentication/custom): 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.

```go signatureapi.go
func buildContract(name, email, userID, appOrigin string) map[string]any {
	return map[string]any{
		"title":    "Service Agreement",
		"metadata": map[string]any{"app_user_id": userID},
		"documents": []any{map[string]any{
			"url":             "https://pub-9cb75390636c4a8a83a6f76da33d7f45.r2.dev/docs-samples/service-agreement.pdf",
			"format":          "pdf",
			"places":          []any{map[string]any{"key": "client_signature", "type": "signature", "recipient_key": "client"}},
			"fixed_positions": []any{map[string]any{"place_key": "client_signature", "page": 1, "top": 172, "left": 210}},
		}},
		"recipients": []any{map[string]any{
			"key":           "client",
			"type":          "signer",
			"name":          name,
			"email":         email,
			"delivery_type": "none",
			"ceremony": map[string]any{
				"authentication": []any{map[string]any{"type": "custom", "provider": "Acme Corp Portal", "data": map[string]any{"user_id": userID}}},
				"embeddable_in":  []any{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](https://signatureapi.com/docs/api/resources/ceremonies/ceremony-url#url-validity).

```go signatureapi.go
func (c Config) createSigningSession(name, email, userID string) (envelopeID, ceremonyURL string, err error) {
	var envelope Envelope
	if err = c.api("POST", "/v1/envelopes", buildContract(name, email, userID, c.AppOrigin), &envelope); err != nil {
		return
	}
	for attempt := 0; envelope.Status == "processing" && attempt < 30; attempt++ {
		time.Sleep(time.Second)
		if err = c.api("GET", "/v1/envelopes/"+envelope.ID, nil, &envelope); err != nil {
			return
		}
	}
	if envelope.Status != "in_progress" || len(envelope.Recipients) == 0 {
		return "", "", &APIError{Detail: fmt.Sprintf("Envelope is %s, not ready for signing", envelope.Status)}
	}
	return envelope.ID, envelope.Recipients[0].Ceremony.URL, nil
}
```

## 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](https://signatureapi.com/docs/embedded/ceremony-events) only from `https://sign.signatureapi.com` and from its own iframe.

```javascript 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](https://signatureapi.com/docs/api/resources/ceremonies/redirect-url) for the way back.

## 3. Verify webhooks on the raw body

SignatureAPI signs every delivery with the [Standard Webhooks](https://github.com/standard-webhooks/standard-webhooks) scheme. `verifyWebhook` 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.

```go signatureapi.go
func verifyWebhook(secret string, header http.Header, rawBody []byte, now time.Time, tolerance time.Duration) error {
	id, timestamp, signatures := header.Get("webhook-id"), header.Get("webhook-timestamp"), header.Get("webhook-signature")
	if id == "" || timestamp == "" || signatures == "" {
		return fmt.Errorf("%w: missing webhook headers", errWebhook)
	}
	seconds, err := strconv.ParseInt(timestamp, 10, 64)
	if err != nil || seconds < 0 {
		return fmt.Errorf("%w: invalid timestamp", errWebhook)
	}
	age := now.Sub(time.Unix(seconds, 0))
	if age < -tolerance || age > tolerance {
		return fmt.Errorf("%w: timestamp outside the tolerance window", errWebhook)
	}
	key, err := base64.StdEncoding.DecodeString(strings.TrimPrefix(secret, "whsec_"))
	if err != nil {
		return fmt.Errorf("%w: secret is not valid base64", errWebhook)
	}
	mac := hmac.New(sha256.New, key)
	mac.Write([]byte(id + "." + timestamp + "."))
	mac.Write(rawBody)
	expected := mac.Sum(nil)
	for _, entry := range strings.Fields(signatures) {
		version, value, _ := strings.Cut(entry, ",")
		candidate, err := base64.StdEncoding.DecodeString(value)
		if version == "v1" && err == nil && hmac.Equal(candidate, expected) {
			return nil
		}
	}
	return fmt.Errorf("%w: invalid signature", errWebhook)
}
```

The handler reads the body with `io.ReadAll`, 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](https://signatureapi.com/docs/api/webhooks).

```go main.go
func (s *server) webhook(w http.ResponseWriter, r *http.Request) {
	raw, err := io.ReadAll(http.MaxBytesReader(w, r.Body, 1<<20))
	if err == nil {
		err = verifyWebhook(s.cfg.WebhookSecret, r.Header, raw, time.Now(), 300*time.Second)
	}
	if err != nil {
		writeJSON(w, http.StatusBadRequest, map[string]string{"error": err.Error()})
		return
	}
	var event struct {
		Type string `json:"type"`
		Data struct {
			EnvelopeID string `json:"envelope_id"`
		} `json:"data"`
	}
	if err := json.Unmarshal(raw, &event); err != nil {
		writeJSON(w, http.StatusBadRequest, map[string]string{"error": "body is not JSON"})
		return
	}
	webhookID := r.Header.Get("webhook-id")
	s.mu.Lock()
	defer s.mu.Unlock()
	if s.seenWebhookIDs[webhookID] {
		writeJSON(w, http.StatusOK, map[string]bool{"duplicate": true})
		return
	}
	s.seenWebhookIDs[webhookID] = true
	record := s.contracts[event.Data.EnvelopeID]
	if record == nil {
		record = &contract{Status: "unknown", Events: []string{}}
		s.contracts[event.Data.EnvelopeID] = record
	}
	record.Events = append(record.Events, event.Type)
	if event.Type == "envelope.completed" {
		record.Status = "completed"
	}
	log.Printf("webhook %s for envelope %s", event.Type, event.Data.EnvelopeID)
	writeJSON(w, http.StatusOK, map[string]bool{"received": true})
}
```

## 4. Confirm the status

`GET /api/contracts/{id}` reads the envelope with [`GET /v1/envelopes/{id}`](https://signatureapi.com/docs/api/resources/envelopes/get) 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](https://signatureapi.com/docs/api/resources/deliverables/object): 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.

```go signatureapi.go
func (c Config) downloadSignedPDF(envelopeID string) ([]byte, error) {
	var envelope Envelope
	if err := c.api("GET", "/v1/envelopes/"+envelopeID, nil, &envelope); err != nil {
		return nil, err
	}
	if envelope.Status != "completed" || envelope.Deliverable == nil {
		return nil, errNotReady(fmt.Sprintf("Envelope is %s. The signed PDF exists once it is completed.", envelope.Status))
	}
	var deliverable struct{ Status, URL string }
	if err := c.api("GET", "/v1/deliverables/"+envelope.Deliverable.ID, nil, &deliverable); err != nil {
		return nil, err
	}
	if deliverable.Status != "generated" {
		return nil, errNotReady(fmt.Sprintf("Deliverable is %s. Try again in a few seconds.", deliverable.Status))
	}
	resp, err := httpClient.Get(deliverable.URL) // no API key on this request
	if err != nil {
		return nil, err
	}
	defer resp.Body.Close()
	if resp.StatusCode != http.StatusOK {
		return nil, &APIError{Status: resp.StatusCode}
	}
	return io.ReadAll(resp.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

```shell
export SIGNATUREAPI_KEY=YOUR_API_KEY            # your test key
export SIGNATUREAPI_WEBHOOK_SECRET=whsec_YOUR_SECRET
export APP_ORIGIN=http://localhost:8080
go 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

```shell
go test -v ./...
```

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](https://signatureapi.com/docs/api/resources/recipients/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

- [Embedding in a Web Application](https://signatureapi.com/docs/embedded/web-app): the full request flow and every ceremony option.
- [Webhooks](https://signatureapi.com/docs/api/webhooks): events, retries and source IPs.
- [Go-live checklist](https://signatureapi.com/docs/api/guides/go-live-checklist): what to check before you switch to a live key.
