Integrating Payment Gateways in Ruby on Rails

๐Ÿ’ณ Unlocking Payments: Integrating Payment Gateways in Ruby on Rails ๐Ÿš€

In the modern web world, online transactions have become a cornerstone for e-commerce and service-based platforms. Setting up payment gateways might seem daunting, but Ruby on Rails (RoR) makes it streamlined and efficient. This blog dives into popular payment gateways and explains how to implement them with code examples, covering payment processing and refund initialization.

image-1570007044997-813127114d2d6471a505ecde09096475


Here are some of the most commonly used payment gateways with RoR:

  1. Stripe ๐Ÿงก
  2. PayPal ๐Ÿ›ก๏ธ
  3. Razorpay ๐Ÿ‡ฎ๐Ÿ‡ณ
  4. Square ๐Ÿ”ณ

๐Ÿ’ก Setting Up a Payment Gateway in Rails

Letโ€™s walk through the process of integrating Stripe as an example.


๐Ÿ› ๏ธ Step 1: Install the Required Gem

Add the Stripe gem to your Gemfile:

gem 'stripe'

Run:

bundle install

๐Ÿ”‘ Step 2: Configure Stripe API Keys

Create a new initializer file, config/initializers/stripe.rb:

Stripe.api_key = ENV['STRIPE_SECRET_KEY']

Set your API keys in .env:

STRIPE_SECRET_KEY=your_secret_key
STRIPE_PUBLISHABLE_KEY=your_publishable_key

๐Ÿ“„ Step 3: Create a Payment Form

In your views/payments/new.html.erb, add a simple payment form:

<h1>Make a Payment ๐Ÿ’ต</h1>

<form action="/payments" method="POST">
  <script src="https://checkout.stripe.com/checkout.js"
          class="stripe-button"
          data-key="<%= ENV['STRIPE_PUBLISHABLE_KEY'] %>"
          data-amount="5000"  <!-- Amount in cents -->
          data-name="My Shop"
          data-description="Payment for your order"
          data-currency="usd">
  </script>
</form>

๐Ÿ”„ Step 4: Handle the Payment Request

Create a PaymentsController to handle payments:

class PaymentsController < ApplicationController
  def create
    # Token is generated by Stripe Checkout
    token = params[:stripeToken]

    begin
      charge = Stripe::Charge.create(
        amount: 5000, # Amount in cents
        currency: 'usd',
        source: token,
        description: 'Payment for order #1234'
      )
      flash[:success] = "Payment successful! ๐ŸŽ‰"
    rescue Stripe::CardError => e
      flash[:error] = e.message
    end

    redirect_to root_path
  end
end

๐Ÿ” Initializing a Refund

Refunds are just as easy to implement:

def refund
  begin
    refund = Stripe::Refund.create(
      charge: 'charge_id_here' # Replace with the actual charge ID
    )
    flash[:success] = "Refund processed successfully! ๐Ÿ’ธ"
  rescue Stripe::InvalidRequestError => e
    flash[:error] = e.message
  end

  redirect_to root_path
end

๐Ÿฆ Other Payment Gateways

Hereโ€™s how to integrate other gateways briefly:

๐Ÿ”ต PayPal

  • Install the paypal-sdk-rest gem.
  • Use the PayPal REST API for payments and refunds.
  • Create a payment URL and redirect the user to complete the payment.

๐Ÿ‡ฎ๐Ÿ‡ณ Razorpay

  • Install the razorpay gem.
  • Use its APIs for creating orders, capturing payments, and initiating refunds.

๐Ÿ”ณ Square

  • Install the square gem.
  • Use its APIs for creating checkout links and processing refunds.

๐Ÿ“ˆ Best Practices for Payment Gateways

  1. Secure your API keys ๐Ÿ›ก๏ธ โ€“ Never expose secret keys.
  2. Validate inputs โœ… โ€“ Sanitize and validate all payment-related data.
  3. Handle errors gracefully ๐Ÿšจ โ€“ Always provide a fallback plan for failed transactions.
  4. Use webhooks ๐Ÿ”” โ€“ Get real-time updates about payment statuses.

๐Ÿš€ Wrapping Up

Integrating payment gateways into your Ruby on Rails application is essential for any modern web app. By following the steps outlined above, you can set up a seamless payment experience for your users, process payments, and even handle refunds.

Have questions or want to share your payment integration experiences? Drop them in the comments below! ๐Ÿ’ฌ

© Lakhveer Singh Rajput - Blogs. All Rights Reserved.