McTaba Labs logo
Software EngineeringThe WhiteboardProjectsEventsMasterclassesWebinarsLearn
Book Call

500+ developers already in the community

Get answers, find accountability partners, and stay ahead

Join Discord →
McTaba Labs logo

Educating 1 million students in tech by 2030.

Programs

  • HighSchool Graduates Launchpad
  • AI & Business Automation
  • Corporate Training
  • McTaba Story & Mission
  • Full-Stack Curriculum
  • Course Pricing & Plans
  • Frequently Asked Questions

Resources

  • Join Discord Community
  • Tech Events in Nairobi
  • Masterclasses
  • Free Resources
  • Learn
  • Campus
  • Africa Tech Talent Report
  • Partner With Us
  • Start a Project
  • Our Work

Contact Us

  • 124 Manyani East Road, Lavington, Nairobi
  • +254727795603
  • Book a Discovery Call

Office Hours:

Mon-Fri: 9am - 2pm EAT

Sat: 10am - 12pm EAT

© 2027 McTaba Labs - A product of Edtech Industries. All rights reserved.

Privacy PolicyTerms of ServiceRefund Policy
  1. Learn
  2. Paystack for African Developers
  3. Accept Payments with Paystack in Ruby on Rails
Bonaventure OgetoBy Bonaventure Ogeto|Updated July 20, 2026

Accept Payments with Paystack in Ruby on Rails

To accept Paystack payments in Rails, create a PaymentsController that uses Net::HTTP or the httparty gem to call the Paystack API. Initialize a transaction, redirect the customer to Paystack checkout, and verify the payment in a callback action.

In this article

  1. 1. Setup
  2. 2. Paystack Service
  3. 3. Payments Controller
  4. 4. Routes
  5. 5. Order Model
  6. 6. Production Checklist
  7. 7. Ship Payments Faster

Setup

Add your Paystack key to Rails credentials or .env:

# .env
PAYSTACK_SECRET_KEY=sk_test_xxxxxxxxxxxxxxxxxxxxx

Add the dotenv gem if using .env:

# Gemfile
gem 'dotenv-rails', groups: [:development, :test]

Paystack Service

# app/services/paystack_service.rb
require 'net/http'
require 'json'

class PaystackService
  BASE_URL = 'https://api.paystack.co'

  def initialize
    @secret_key = ENV['PAYSTACK_SECRET_KEY']
  end

  def initialize_transaction(email:, amount_kobo:, reference:, callback_url:)
    uri = URI(BASE_URL + '/transaction/initialize')
    http = Net::HTTP.new(uri.host, uri.port)
    http.use_ssl = true

    request = Net::HTTP::Post.new(uri)
    request['Authorization'] = 'Bearer ' + @secret_key
    request['Content-Type'] = 'application/json'
    request.body = {
      email: email,
      amount: amount_kobo,
      reference: reference,
      callback_url: callback_url
    }.to_json

    response = http.request(request)
    JSON.parse(response.body)
  end

  def verify_transaction(reference)
    uri = URI(BASE_URL + '/transaction/verify/' + reference)
    http = Net::HTTP.new(uri.host, uri.port)
    http.use_ssl = true

    request = Net::HTTP::Get.new(uri)
    request['Authorization'] = 'Bearer ' + @secret_key

    response = http.request(request)
    JSON.parse(response.body)
  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.

Payments Controller

# app/controllers/payments_controller.rb
class PaymentsController < ApplicationController
  def create
    email = params[:email]
    amount = params[:amount].to_f
    reference = "order_#{SecureRandom.hex(6)}"

    order = Order.create!(
      email: email,
      amount_kobo: (amount * 100).to_i,
      reference: reference
    )

    service = PaystackService.new
    result = service.initialize_transaction(
      email: email,
      amount_kobo: order.amount_kobo,
      reference: reference,
      callback_url: payment_callback_url
    )

    if result['status']
      redirect_to result['data']['authorization_url'], allow_other_host: true
    else
      flash[:error] = result['message'] || 'Failed'
      redirect_to checkout_path
    end
  end

  def callback
    reference = params[:reference] || params[:trxref]

    unless reference
      flash[:error] = 'Missing reference'
      return redirect_to root_path
    end

    service = PaystackService.new
    result = service.verify_transaction(reference)

    if result['status'] && result['data']['status'] == 'success'
      order = Order.find_by(reference: reference)

      if order && result['data']['amount'] == order.amount_kobo
        Order.where(reference: reference, paid: false).update_all(paid: true, paid_at: Time.current)
        render :success
      else
        render :failed
      end
    else
      render :failed
    end
  end
end

Routes

# config/routes.rb
Rails.application.routes.draw do
  post '/pay', to: 'payments#create'
  get '/payment/callback', to: 'payments#callback', as: :payment_callback
end

Order Model

rails generate model Order reference:string:uniq email:string amount_kobo:integer currency:string paid:boolean paid_at:datetime
rails db:migrate

Production Checklist

  1. Use Rails credentials. Store keys with rails credentials:edit instead of .env in production.
  2. Set up webhooks. See Handle Paystack Webhooks in Rails.
  3. HTTPS. Required for callback and webhook URLs.
  4. Validate amounts. Check against your database, not params.

Ship Payments Faster

This guide is part of the Paystack integration guides by language and framework series.

Sign up for the McTaba newsletter

Key Takeaways

  • ✓Use Net::HTTP (stdlib) or the httparty gem for Paystack API calls. No Paystack gem is required.
  • ✓Store your Paystack secret key in Rails credentials or environment variables.
  • ✓Amounts are in kobo (NGN), pesewas (GHS), or cents. Multiply by 100 before sending.
  • ✓Skip CSRF verification for webhook actions with skip_forgery_protection.
  • ✓Always verify transactions server-side after the redirect callback.
  • ✓Rails conventions (MVC, ActiveRecord) map cleanly to the Paystack payment flow.

Frequently Asked Questions

Do I need a Paystack Ruby gem?
No. Net::HTTP in the Ruby standard library handles all the API calls. You can also use the httparty or faraday gems for a cleaner API, but they are not required.
Can I use Rails API mode with Paystack?
Yes. In API mode, return JSON responses instead of rendering views. The Paystack API calls are identical.
How do I handle CSRF for webhooks?
Add skip_forgery_protection to your webhook controller action. Paystack requests do not include Rails CSRF tokens.

Learn Paystack Integration

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

Not ready? Create Free Account

Keep reading

Paystack Integration Guides by Language and Framework

A complete directory of Paystack integration guides organized by programming language and framework. Each guide covers accepting payments, verifying transactions, handling webhooks, and building subscriptions in your specific stack.

Read more

Accept Payments with Paystack in Svelte and SvelteKit

Accept Paystack payments in SvelteKit using server endpoints for backend logic and Svelte components for the frontend. This guide covers initializing transactions, inline popup checkout, redirect checkout, and verification in a single full-stack SvelteKit project.

Read more

Verify Paystack Payments in Flask

Verify Paystack payments server-side in your Flask application. This guide covers calling the Paystack verify endpoint, validating amounts and currencies, building reusable verification helpers, and preventing double-granting.

Read more

Build Paystack Subscriptions in ASP.NET Core

Implement Paystack recurring billing in ASP.NET Core. This guide covers creating plans, subscribing customers through transaction initialization, handling renewal webhooks with C#, and cancelling subscriptions.

Read more

Handling Slow Networks in Paystack Checkout Flows

How to handle slow, unstable, and intermittent networks in Paystack checkout flows. Covers timeout configuration, meaningful loading states, smart retry logic, and the specific network conditions you face building for African markets.

Read more

Paystack Sandbox Card Numbers Not Working

Paystack sandbox card numbers fail for three reasons: you are using Stripe test cards instead of Paystack ones, you forgot the PIN and OTP steps, or your integration is hitting the live API with test keys. Here is how to fix each one.

Read more

Explore related topics

M-Pesa & African Stack

M-Pesa Daraja API tutorials, USSD development, and WhatsApp Business API guides. The African Stack that global bootcamps do not teach.

Learn to Code in Kenya

Everything a Kenyan needs to know before writing their first line of code. Career paths, real costs, hardware requirements, and honest answers about what it takes.

Learning to Code

Roadmaps, language guides, and practical advice for learning to code and launching a programming career.

Breaking Into Tech

Practical, no-nonsense guides for anyone looking to start or change their career in tech. From choosing your first language to acing interviews.

The African Stack: Skills for This Market

The skills that make Kenyan developers hard to replace: M-Pesa, USSD, WhatsApp, fintech, and building for the African market.

Bonaventure Ogeto

Bonaventure Ogeto

Founder, McTaba Labs

Bonaventure is the founder of McTaba Labs, a coding bootcamp in Nairobi, Kenya. He has spent years building products for the African market and mentoring the next generation of developers across the continent.