Skip to content

Tutorials

Ruby on Rails Tutorial with Active Job Webhooks

Build a Rails app that sends a contract, embeds the signing ceremony, verifies webhooks and processes them with Active Job, then downloads the PDF.

This tutorial builds a complete Ruby on Rails 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 webhook controller only verifies and acknowledges each delivery; an Active Job processes the event in the background. The API client uses Net::HTTP, with no extra gems.

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

  • Ruby 3.3 and Bundler.
  • 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. build_contract 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.
app/lib/signature_api.rb
def build_contract(name, email, user_id)
  {
    title: "Service Agreement",
    metadata: { app_user_id: user_id },
    documents: [{
      url: "https://pub-9cb75390636c4a8a83a6f76da33d7f45.r2.dev/docs-samples/service-agreement.pdf",
      format: "pdf",
      places: [{ key: "client_signature", type: "signature", recipient_key: "client" }],
      fixed_positions: [{ place_key: "client_signature", page: 1, top: 172, left: 210 }]
    }],
    recipients: [{
      key: "client",
      type: "signer",
      name: name,
      email: email,
      delivery_type: "none",
      ceremony: {
        authentication: [{ type: "custom", provider: "Acme Corp Portal", data: { user_id: user_id } }],
        embeddable_in: [@app_origin]
      }
    }]
  }
end

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. Every read returns a new URL for the same ceremony.

app/lib/signature_api.rb
def create_signing_session(name, email, user_id)
  envelope = api("POST", "/v1/envelopes", build_contract(name, email, user_id))
  30.times do
    break unless envelope["status"] == "processing"

    sleep @poll_interval
    envelope = api("GET", "/v1/envelopes/#{envelope["id"]}")
  end
  raise ApiError, "Envelope is #{envelope["status"]}, not ready for signing" unless envelope["status"] == "in_progress"

  { envelopeId: envelope["id"], ceremonyUrl: envelope["recipients"][0]["ceremony"]["url"] }
end

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.

app/views/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. SignatureApi.verify_webhook 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.

app/lib/signature_api.rb
def self.verify_webhook(secret, headers, raw_body, now: Time.now.to_i, tolerance_seconds: 300)
  lower = headers.to_h { |name, value| [name.to_s.downcase, value] }
  id = lower["webhook-id"]
  timestamp = lower["webhook-timestamp"]
  signature_header = lower["webhook-signature"]
  if [id, timestamp, signature_header].any? { |v| v.nil? || v.empty? }
    raise WebhookVerificationError, "Missing webhook-id, webhook-timestamp or webhook-signature header"
  end
  raise WebhookVerificationError, "Invalid webhook-timestamp" unless timestamp.match?(/\A\d+\z/)
  if (now - timestamp.to_i).abs > tolerance_seconds
    raise WebhookVerificationError, "Timestamp outside the tolerance window"
  end

  key = Base64.strict_decode64(secret.delete_prefix("whsec_"))
  expected = OpenSSL::HMAC.digest("SHA256", key, "#{id}.#{timestamp}.#{raw_body}")

  # The header holds space-separated "v1,<base64>" entries. Any match is enough.
  signature_header.split(" ").each do |entry|
    version, signature = entry.split(",", 2)
    next unless version == "v1" && signature

    candidate = begin
      Base64.strict_decode64(signature)
    rescue ArgumentError
      next
    end
    if candidate.bytesize == expected.bytesize && OpenSSL.fixed_length_secure_compare(candidate, expected)
      return true
    end
  end
  raise WebhookVerificationError, "No matching signature"
end

The handler reads the raw body with request.raw_post, 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.

app/controllers/webhooks_controller.rb
def create
  raw_body = request.raw_post
  headers = %w[webhook-id webhook-timestamp webhook-signature].to_h { |name| [name, request.headers[name]] }

  begin
    SignatureApi.verify_webhook(Rails.configuration.x.signatureapi[:webhook_secret], headers, raw_body)
  rescue SignatureApi::WebhookVerificationError => e
    return render json: { error: e.message }, status: :bad_request
  end

  # Retries repeat the same webhook-id: acknowledge them without processing again.
  return render json: { duplicate: true } unless ContractStore.first_delivery?(headers["webhook-id"])

  event = JSON.parse(raw_body)
  # Respond fast: the job records the event in the background.
  SignatureapiEventJob.perform_later(event.dig("data", "envelope_id"), event["type"])
  render json: { received: true }
end

The controller answers right away and hands the event to SignatureapiEventJob, so a slow step never delays the response. Put the work your app does on each event here, such as updating the contract record or downloading the PDF on deliverable.generated:

app/jobs/signatureapi_event_job.rb
class SignatureapiEventJob < ApplicationJob
  queue_as :default

  def perform(envelope_id, event_type)
    ContractStore.record_event(envelope_id, event_type)
    Rails.logger.info("webhook #{event_type} for envelope #{envelope_id}")
  end
end

In production, run Active Job on a persistent queue backend so queued events survive a restart.

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. 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 function asks for a fresh one on each download instead of storing it.

app/lib/signature_api.rb
def download_signed_pdf(envelope_id)
  envelope = api("GET", "/v1/envelopes/#{envelope_id}")
  if envelope["status"] != "completed" || envelope["deliverable"].blank?
    raise NotReadyError, "Envelope is #{envelope["status"]}. The signed PDF exists once it is completed."
  end

  deliverable = api("GET", "/v1/deliverables/#{envelope["deliverable"]["id"]}")
  if deliverable["status"] != "generated"
    raise NotReadyError, "Deliverable is #{deliverable["status"]}. Try again in a few seconds."
  end

  response = Net::HTTP.get_response(URI(deliverable["url"]))
  raise ApiError, "Downloading the PDF returned #{response.code}" unless response.is_a?(Net::HTTPSuccess)

  response.body
end

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
bundle install
export SIGNATUREAPI_KEY=YOUR_API_KEY            # your test key
export SIGNATUREAPI_WEBHOOK_SECRET=whsec_YOUR_SECRET
export APP_ORIGIN=http://localhost:3000
bin/rails server

Open http://localhost:3000, 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
bin/rails 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