WhatsApp official API in Rails: Net::HTTP and webhook

Integrate the official WhatsApp API into Rails via CRPRO Hub: Net::HTTP with timeouts, skip_forgery_protection, raw_post, secure_compare and Active Job.

In Ruby on Rails, the CRPRO Hub integration uses what already ships with Ruby and the framework: Net::HTTP to call the API, a controller to receive the webhook and Active Job to move heavy work out of the request. No gem is needed. The Rails-specific points are request forgery protection, the raw body in request.raw_post and constant-time comparison with ActiveSupport::SecurityUtils.

How to send a message with Net::HTTP

Short answer: a service module that builds a Net::HTTP::Post with the Authorization, Content-Type and Idempotency-Key headers, sets timeouts and checks that the status is 202. The Hub answers 202 with status accepted.

  • Create the API key in the dashboard with the messages:send scope and read it from ENV, or from Rails credentials (authentication). It is shown only once.
  • Net::HTTP.start accepts options such as use_ssl, open_timeout and read_timeout. Ruby's documentation says open_timeout and read_timeout start at 60 seconds; set smaller values, so a slow Hub does not hold the Puma process.
  • With use_ssl truthy and a nil port, the default port becomes 443 and certificate verification is enabled.
  • The Idempotency-Key must be stable per logical message. The same key with the same body returns the original response; with a different body, the Hub answers 409 IDEMPOTENCY_KEY_REUSED.
# app/services/crpro_hub.rb require "net/http" require "json" module CrproHub BASE = "https://crprohub.com/api/v1".freeze def self.enviar_texto(canal:, para:, texto:, chave:) uri = URI("#{BASE}/channels/#{canal}/messages") requisicao = Net::HTTP::Post.new( uri, "Authorization" => "Bearer #{ENV.fetch('CRPRO_API_KEY')}", "Content-Type" => "application/json", "Idempotency-Key" => chave ) requisicao.body = { to: para, type: "text", text: { body: texto } }.to_json resposta = Net::HTTP.start(uri.host, uri.port, use_ssl: true, open_timeout: 5, read_timeout: 10) do |http| http.request(requisicao) end raise "CRPRO Hub #{resposta.code}: #{resposta.body}" unless resposta.code == "202" JSON.parse(resposta.body).dig("data", "message_id") # 202: aceita, nao entregue end end

The Hub limits are 60 messages per minute per channel and 120 requests per minute per organization and credential. Call the service from a job, not from inside the user's request: the 202 only says the message was accepted and queued, and the final state arrives through the message.status webhook. The body fields are explained in the quickstart.

How to receive the webhook with skip_forgery_protection

Short answer: create a POST route and a controller with skip_forgery_protection, read the body with request.raw_post, check the HMAC and answer head :ok. Without the exemption, forgery protection stays on and Rails treats the Hub call, which sends no CSRF token, as suspect: it raises or resets the session, depending on configuration (:exception or :null_session).

The Rails API documentation describes skip_forgery_protection as the method that turns off request forgery protection for a controller, equivalent to skip_before_action :verify_authenticity_token. request.raw_post reads the body as it came, useful for web services that work with raw requests, and reads the stream only once, storing the result. That is what the signature needs: the Hub signs timestamp.delivery_id.body with HMAC SHA-256 and sends the result in X-Hub-Signature-256, as sha256=HEX.

# config/routes.rb post "webhooks/crprohub", to: "webhooks/crprohub#create"curl -X POST https://crprohub.com/api/v1/webhooks \ -H "Authorization: Bearer hub_pk_EXEMPLO_NAO_REAL" \ -H "Content-Type: application/json" \ -d '{"name":"Recebimento","url":"https://your-app.com/webhooks/crprohub","event_types":["message.received"]}'# app/controllers/webhooks/crprohub_controller.rb require "openssl" module Webhooks class CrproHubController < ApplicationController skip_forgery_protection # o Hub nao envia token CSRF; a assinatura autentica def create corpo = request.raw_post # bytes exatos do corpo return head :unauthorized unless assinatura_valida?(corpo) evento = JSON.parse(corpo) # O id do corpo se repete na retentativa e no replay. primeira_vez = Rails.cache.write("crprohub:evento:#{evento['id']}", true, unless_exist: true, expires_in: 1.day) ProcessarEventoCrproJob.perform_later(evento) if primeira_vez head :ok # 2xx rapido end private def assinatura_valida?(corpo) h = request.headers assinado = "#{h['X-Hub-Timestamp']}.#{h['X-Hub-Delivery-Id']}.#{corpo}" esperado = OpenSSL::HMAC.hexdigest("SHA256", ENV.fetch("CRPRO_WEBHOOK_SECRET"), assinado) recebido = h["X-Hub-Signature-256"].to_s.delete_prefix("sha256=") ActiveSupport::SecurityUtils.secure_compare(esperado, recebido) end end end{ "id": "6f1f0f6a-3b2c-4d1e-9a8b-0c1d2e3f4a5b", "event": "message.received", "channel_id": "9f6a9c1e-2f3d-4a5b-8c7d-1e2f3a4b5c6d", "occurred_at": "2026-08-21T12:00:00.000Z", "data": { "message_id": "wamid.EXEMPLO123", "from": "5521999999999", "type": "text", "text": "Oi, ainda tem em estoque?" } }
The Rails documentation distinguishes two methods: fixed_length_secure_compare raises if the sizes differ, and secure_compare returns false without raising. Since the value comes from outside, the example uses secure_compare.

Active Job, duplicates and a fast response

Short answer: the controller validates, marks the event id and enqueues a job. The Hub expects a 2xx within 10 seconds, repeats a delivery up to nine times over about four days and pauses the endpoint after 20 consecutive failures.

Rails.cache.write with unless_exist writes the key only if it does not exist, and the return value tells you whether it was the first time. That depends on the cache store: the in-memory store is per process, so with several processes a repeat can slip through. Use a shared store, or a table with a unique index on the event id. There is also the opposite risk: if the job fails after marking the id, the Hub's retry will be discarded; in that case mark the id as done at the end of the job. In the job, use the body's message_id as the basis of the send's Idempotency-Key.

Controller responseWhenEffect on the Hub
401Invalid or missing signatureCounts as a failure
200New or repeated eventDelivery complete
500Body is not JSON, or an exceptionRetry

If the endpoint is paused, reactivate with PATCH /api/v1/webhooks/{id} and {"status":"active"}. Events during the pause generate no delivery; recover with GET /api/v1/channels/{id}/messages and direction=inbound. See also the webhooks page.

API errors that show up in Rails and what to do

Short answer: handle them by range. Validation 4xx, like 400 and 422, are not fixed by repeating; 429 and 5xx deserve a retry with the same key; 401 and 403 call for a review of the key and scope.

  • 401: missing, invalid or revoked key. Generate another and update the environment.
  • 403: the key lacks the required scope, such as messages:send. The scope-by-role list is in authentication.
  • 409 IDEMPOTENCY_KEY_REUSED: the same key came back with a different body. Generate the text once and keep it.
  • 429: rate limit. Wait and repeat with the same Idempotency-Key.
  • Meta errors, such as outside the service window: see the docs home.

In an Active Job, let the exception rise in the cases that deserve a retry, so the queue repeats with a wait, and discard the job in validation cases, logging the reason. Since the Idempotency-Key is the same on every attempt, repeating does not duplicate the message.

How to test the controller

Short answer: an integration test that signs a body with the same formula as the controller and sends it with post, passing the X-Hub-* headers. Two cases are enough: a correct signature returns 200, a swapped one returns 401.

# test/controllers/webhooks/crprohub_controller_test.rb require "test_helper" class CrproHubControllerTest < ActionDispatch::IntegrationTest def assinar(corpo) ts, entrega = Time.now.to_i.to_s, "d-1" sig = OpenSSL::HMAC.hexdigest("SHA256", ENV.fetch("CRPRO_WEBHOOK_SECRET"), "#{ts}.#{entrega}.#{corpo}") { "X-Hub-Timestamp" => ts, "X-Hub-Delivery-Id" => entrega, "X-Hub-Signature-256" => "sha256=#{sig}" } end test "assinatura certa responde 200" do corpo = { id: "e1", event: "webhook.test" }.to_json post "/webhooks/crprohub", params: corpo, headers: assinar(corpo).merge("Content-Type" => "application/json") assert_response :ok end test "assinatura trocada responde 401" do corpo = { id: "e2" }.to_json headers = assinar(corpo).merge("X-Hub-Signature-256" => "sha256=" + "0" * 64, "Content-Type" => "application/json") post "/webhooks/crprohub", params: corpo, headers: headers assert_response :unauthorized end end

Set CRPRO_WEBHOOK_SECRET in the test environment. For a real delivery, the POST /api/v1/webhooks/{id}/test endpoint sends an event to your domain, up to 10 times per hour per endpoint. The webhooks page lists the headers and the receiving rules.

Frequently asked questions

Do I need a gem to talk to the Hub in Rails?

No. Net::HTTP, which ships with Ruby, and a controller are enough. The article depends on no Hub gem.

Why does Rails reject the webhook with a CSRF token error?

Because request forgery protection is active in the controller and checks the token. Use skip_forgery_protection in that controller and authenticate through the HMAC signature.

Why use request.raw_post and not params?

Because the signature covers the exact body bytes. params is already parsed, and re-serializing it can change the result.

Can I use fixed_length_secure_compare?

Only if both values have the same length, because it raises otherwise. For a value coming from outside, secure_compare is safer to use.

Fontes

Documentação oficial da Meta, conferida em 31 de outubro de 2026.