Integrating Razorpay with Rails: A Complete Guide

Total Blog Views: 20

Blog Status: publish

Created By: swaz_ahmed Created at: 04-30-2025

Tags: web development paytm inetgration ruby on rails rubyonrails payments railsgem razorpay ruby gems rails ecommerce razorpay rails integration rails backend api integration rails

 

Why Integrate Razorpay in Rails?

If you're building a Rails app that requires online payments — for products, subscriptions, or donations — integrating a reliable payment gateway like Razorpay ensures a seamless and secure transaction process for your users.

 

Key Advantages:

  • Secure Transactions – PCI DSS compliant.

  • Simple Integration – SDKs and APIs tailored for Ruby/Rails.

  • Custom Payment Interfaces – Embedded payment windows, webhooks for payment updates.

Prerequisites

Before we start: 

   

  • Ruby on Rails installed.

  • Razorpay account (sign up at https://dashboard.razorpay.com).

  • API Key and Secret from your Razorpay dashboard.

  • Bundler to manage gems.

      

 

Setting Up Razorpay in Rails

   Step 1: Install the Razorpay Gem

Add this to your Gemfile:

gem razorpay

Run:

bundle install

 

Step 2: Configure Razorpay Credentials

Create a file config/initializers/razorpay.rb:

Razorppay.setup(ENV['RAZORPAY_KEY_ID'], ENV['RAZORPAY_KEY_SECRET'])

Add your keys to .env or credentials for security.

RAZORPAY_KEY_ID=your_key_id
RAZORPAY_KEY_SECRET=your_secret

 

Use dotenv-rails if you’re using .env:

gem dotenv-rails

  And run:

bundle install

 

 

Step 3: Create an Orders Controller

Generate a controller:

rails g controller Orders

 

Step 4: Generate an Order on Payment Initialization

In orders_controller.rb:

class OrdersController < ApplicationController
  def create
    order = Razorpay::Order.create(
      amount: params[:amount], # amount in paise
      currency: 'INR',
      receipt: "receipt_#{SecureRandom.hex(5)}"
    )

    render json: { order_id: order.id }
  rescue => e
    render json: { error: e.message }, status: :unprocessable_entity
  end
end

 

Notes:

  • Amount is in paise (₹1 = 100 paise).

  • Receipt number can be any unique string.

 

Step 5: Handle Razorpay Webhooks (Optional but Recommended)

Create a webhooks_controller.rb:

class WebhooksController < ApplicationController
  skip_before_action :verify_authenticity_token

  def payment_success
    payload = request.body.read
    signature = request.headers['X-Razorpay-Signature']

    is_valid = verify_signature(payload, signature)

    if is_valid
      data = JSON.parse(payload)
      # Process payment status, update orders, etc.
      head :ok
    else
      head :unauthorized
    end
  end

  private

  def verify_signature(payload, signature)
    secret = ENV['RAZORPAY_WEBHOOK_SECRET']
    expected_signature = OpenSSL::HMAC.hexdigest('SHA256', secret, payload)
    expected_signature == signature
  end
end

 
 

Add route in routes.rb:

post '/razorpay_webhook', to: 'webhooks#payment_success'
 
 
 
 Frontend Payment Integration (Example with JavaScript)
 
On your frontend (ERB/React/Angular/JS) call the backend to get the order_id then:

var options = {
  "key": "<%= ENV['RAZORPAY_KEY_ID'] %>",
  "amount": 50000, // 500 INR in paise
  "currency": "INR",
  "order_id": "order_XXXXXX",
  "handler": function (response){
    alert(response.razorpay_payment_id);
    alert(response.razorpay_order_id);
  }
};
var rzp1 = new Razorpay(options);
rzp1.open();

 

 

Note: Load Razorpay script in your HTML head:

<script src="https://checkout.razorpay.com/v1/checkout.js"></script>

 

Test the Integration

1. Start your Rails server:

rails s

2. Use Razorpay's test key and secret.

3. Initiate a payment using Razorpay's test cards.

4. Check payment success webhook logs in your server.

 

Conclusion

Integrating Razorpay with Rails is straightforward thanks to its clean API, solid Ruby gem, and secure webhooks. This setup ensures:

  • Smooth backend payment handling.

  • Reliable webhook-based payment status updates.

  • Secure credential management via environment variables.

This forms a solid base for adding subscription payments, invoice management, and advanced analytics later on.


swaz_ahmed

I am swaz_ahmed blogger on shadbox. I am influencer,content writer,author and publisher. Feel free to ask me any question and suggestions.



Comments



Buy traffic for your website

About Shadbox

we have the “Get things executed” lifestyle at our place of work. There are not any excuses, no if’s or however’s in our dictionary. committed to navigating the ship of creativity to create cell answers, we resolve the real-lifestyles troubles of our clients and their clients. Our passion for work has won us many awards, year after 12 months.

Services

Downloads