How to Receive Mailgun Webhooks in Ruby on Rails

Skip CSRF + read request.raw_post for HMAC-friendly handlers

Rails remains the canonical Ruby web framework for SaaS. Its built-in CSRF protection is great for forms but actively blocks webhook handlers — you have to disable it on the webhook route AND read request.raw_post to get the unparsed bytes that HMAC verification needs. This guide walks through the Ruby on Rails setup for Mailgun webhooks end to end: capturing the raw body, verifying the signature, handling retries idempotently, and iterating locally without redeploying. Cross-reference the Mailgun Webhooks overview for the event catalog and sample payload.

Mailgun Official Webhook Docs

1. Set Up the Ruby on Rails Endpoint

The endpoint needs to do three things, in this order: read the raw body, verify the signature against those exact bytes, and only then parse the JSON for your business logic.

# config/routes.rb
Rails.application.routes.draw do
  post '/webhooks/:service', to: 'webhooks#receive', as: :webhook
end

# app/controllers/webhooks_controller.rb
class WebhooksController < ApplicationController
  # CSRF tokens don't apply to programmatic webhook deliveries.
  skip_before_action :verify_authenticity_token

  def receive
    raw_body = request.raw_post  # raw bytes — NOT parsed by Rails
    signature = request.headers['X-Signature-Header']

    # 1. Verify HMAC over raw_body
    # 2. Parse JSON only after verification passes
    # 3. Process the event idempotently (use the event id as your key)

    event = JSON.parse(raw_body)
    Rails.logger.info "Verified webhook: #{event['type'] || event}"

    head :ok
  end
end
Raw body, every time
Don't reach for params or strong-parameters on a webhook route — Rails parses JSON automatically and the byte-level body is gone. Always start with request.raw_post (or request.body.read with rewind), verify the signature, and only then JSON.parse. ActionController::Parameters and request.body are different worlds — the verifier needs the latter.

2. Verify the Mailgun Signature

Signing details
Algorithm
HMAC-SHA256
Header
(in body — not a header)
Encoding
hex

Mailgun puts `signature.timestamp`, `signature.token`, and `signature.signature` in the **request body** (not headers). The signed string is `{timestamp}{token}` concatenated, signed with your Webhook Signing Key (different from your API key), output as lowercase hex.

Ruby verification

class WebhooksController < ApplicationController
  skip_before_action :verify_authenticity_token, only: [:mailgun]

  def mailgun
    sig = params[:signature] || {}
    timestamp = sig['timestamp'].to_s
    token = sig['token'].to_s
    signature = sig['signature'].to_s
    if timestamp.empty? || token.empty? || signature.empty?
      return head :unauthorized
    end

    expected = OpenSSL::HMAC.hexdigest(
      'sha256',
      ENV['MAILGUN_WEBHOOK_SIGNING_KEY'],
      timestamp + token,
    )
    unless ActiveSupport::SecurityUtils.secure_compare(signature, expected)
      return head :forbidden
    end
    render json: {
      ok: true,
      event: params.dig('event-data', 'event'),
    }
  end
end

Wire this verification call into the Ruby on Rails handler from section 1. The pattern is identical across Ruby on Rails versions: read raw body, verify, parse JSON, dispatch.

Watch out: Mailgun is unusual — the signature lives in the JSON request body, not in headers. Use the dedicated Webhook Signing Key (Settings → API Security), not your Mailgun API Key. The signed-string formula is just `timestamp + token` — the body content itself is not part of the signature, only the (timestamp, token) anti-replay pair.

See Mailgun's official signing docs for the canonical reference, or the cross-service signature verification guide for the same pattern in Ruby and other languages.

3. Make the Handler Idempotent

Mailgun can — and will — send the same event twice. Network blips, your server returning a 5xx mid-processing, deploy windows: any of these triggers a retry, and your handler will see the same event id again. Build for that on day one rather than chasing duplicate-charge bugs in production.

The simplest pattern is a unique constraint on the event id in your database. The handler does the work inside a transaction, and the insert into the events table is the last step — if a retry arrives, the unique-constraint violation tells you the event already committed and you can return 200 without re-running the side effects.

Pattern in any framework:

  1. Read raw body, verify signature.
  2. Begin transaction.
  3. Apply business logic (charge, fulfil, notify, etc.).
  4. Insert event id into processed_events with a unique constraint.
  5. Commit. Return 200.
  6. On unique-constraint violation, return 200 — the event was already processed by a prior delivery.

4. Test Locally Without Deploying

The fastest iteration loop for any webhook handler is: capture a real Mailgun event with HookRay, then replay that captured request against your local Ruby on Rails server until the verification + business logic both pass. No need to retrigger the event in Mailgun, no need to redeploy.

  1. Get a free webhook URL at hookray.com — no signup.
  2. Paste the URL into your Mailgundashboard's webhook settings.
  3. Trigger a test event. HookRay shows the headers, raw body, and parsed payload in real time.
  4. Use HookRay's replay feature to send the captured request against http://localhost:3000/api/webhooks/mailgun (or wherever your Ruby on Rails app is listening) — iterate on your code without re-poking the Mailgun dashboard.

Deploying the Ruby on Rails Handler

Rails apps run well on long-running containers (Render, Fly.io, Heroku, Kamal-deployed VPS). Avoid hosting Rails as serverless functions for webhook endpoints — boot time is unforgiving and Rails warm-up easily blows past the 5-15 second window most webhook senders give you before retrying.

Need a host that boots quickly enough to absorb webhook bursts? DigitalOcean droplets stay warm, support raw-body proxies cleanly, and avoid the cold-start traps of some serverless runtimes.

Capture a real Mailgun webhook in 30 seconds

Free webhook URL, real-time payload inspection, one-click replay. No signup required.

Start Testing — Free