To handle Paystack webhooks in Rails, add skip_forgery_protection to your webhook action, read request.body.read for the raw bytes, compute an HMAC SHA-512 hash with your secret key, compare it to the X-Paystack-Signature header, and process the event. Return head :ok.
# app/controllers/webhooks_controller.rb
class WebhooksController < ApplicationController
skip_forgery_protection only: :paystack
def paystack
signature = request.headers['X-Paystack-Signature']
return head :bad_request unless signature.present?
body = request.body.read
secret = ENV['PAYSTACK_SECRET_KEY']
computed_hash = OpenSSL::HMAC.hexdigest('sha512', secret, body)
unless ActiveSupport::SecurityUtils.secure_compare(computed_hash, signature)
return head :bad_request
end
event = JSON.parse(body)
ProcessPaystackWebhookJob.perform_later(event)
head :ok
end
end
# app/jobs/process_paystack_webhook_job.rb
class ProcessPaystackWebhookJob < ApplicationJob
queue_as :default
def perform(event)
event_type = event['event']
data = event['data'] || {}
case event_type
when 'charge.success'
PaystackService.new.verify_and_fulfill(data['reference']) if data['reference']
when 'subscription.create'
handle_subscription_create(data)
when 'invoice.payment_failed'
handle_invoice_failed(data)
end
end
private
def handle_subscription_create(data)
# Create or update subscription record
end
def handle_invoice_failed(data)
# Update subscription status to past_due
end
end
Get weekly developer tips
Join 25,000+ developers. Practical guides, job tips, and new content — straight to your inbox.
No spam. Unsubscribe anytime.
# config/routes.rb
post '/webhooks/paystack', to: 'webhooks#paystack'
# test/controllers/webhooks_controller_test.rb
test 'valid webhook returns 200' do
payload = { event: 'charge.success', data: { reference: 'test_123' } }.to_json
signature = OpenSSL::HMAC.hexdigest('sha512', ENV['PAYSTACK_SECRET_KEY'], payload)
post webhooks_paystack_url,
params: payload,
headers: { 'Content-Type' => 'application/json', 'X-Paystack-Signature' => signature }
assert_response :ok
end
KES 2,999
The definitive guide to building payment systems with Paystack — from your first transaction to production-grade payment infrastructure across Africa. 9 modules, 47 lessons. Free preview available.
Start Paystack Course