Integration of Paddle Payment Gateway in Rails

Total Blog Views: 287

Blog Status: publish

Created By: swaz_ahmed Created at: 06-19-2024

Tags: payment gateway integration ror paytm india integrate card payment in ruby on rails

Integrating a payment gateway is an essential step in enabling online transactions for any web application. While popular options like Stripe and PayPal often take the spotlight, this guide dives into integrating Paddle, a versatile platform that provides tools for subscription management, SaaS analytics, and fraud prevention. This comprehensive walkthrough aims to provide a seamless and scalable solution for handling online payments using Paddle in a Rails application.

Why Choose Paddle?
Paddle stands out for its robust feature set, which includes advanced subscription management, detailed analytics, and effective fraud prevention. It is particularly well-suited for SaaS businesses and digital product vendors seeking a flexible and reliable payment processing solution.

Prerequisites
Before we dive into the integration, ensure you have the following setup:

  • Ruby (version 2.5 or higher)
  • Rails (version 6 or higher)
  • A Paddle account (you can sign up at Paddle)


Step-by-Step Integration Process
Step 1: Setting Up Your Rails Application
If you haven't already set up a Rails application, let's create a new one:

 

rails new PaddleIntegration
cd PaddleIntegration

rails new PaddleIntegration
cd PaddleIntegration

 

Step 2: Adding the Paddle Gem
Paddle does not provide an official Ruby gem. Instead, we will use paddle-rb, an unofficial but well-maintained gem that wraps around the Paddle API.

Add paddle-rb to your Gemfile:

 

gem 'paddle-rb'

 Run bundle install to install the gem.

Step 3: Configuring Paddle
Create an initializer for Paddle configuration. This initializer will set up the Paddle API with your credentials. Create a file at config/initializers/paddle.rb:

 

Paddle.configure do |config|
  config.vendor_id = ENV['PADDLE_VENDOR_ID']
  config.api_key = ENV['PADDLE_API_KEY']
end

 Ensure you have set PADDLE_VENDOR_ID and PADDLE_API_KEY in your environment variables. You can obtain these credentials from your Paddle account dashboard.

Step 4: Creating a Payment Form
Next, we will create a simple form where users can enter their payment details. Paddle's checkout.js will handle the front-end part.

Generate a new controller and view for the payment form:

 

rails generate controller Payments new

 In app/controllers/payments_controller.rb, define the new and create actions:

 

class PaymentsController < ApplicationController
  require 'paddle'

  def new
  end

  def create
    email = params[:email]
    product_id = YOUR_PRODUCT_ID # Replace with your Paddle product ID

    begin
      # Create a checkout link
      checkout_response = Paddle::Checkout.generate_link(
        product_id: product_id,
        title: "Purchase of Product #{product_id}",
        webhooks: "https://your-domain.com/paddle/webhook",
        customer_email: email
      )
      if checkout_response.success?
        # Redirect user to the Paddle checkout URL
        redirect_to checkout_response[:url]
      else
        # Handle error response
        flash[:alert] = "There was an error creating the payment: #{checkout_response[:message]}"
        render :new
      end
    rescue => e
      # Handle exceptions
      flash[:alert] = "An error occurred: #{e.message}"
      render :new
    end
  end

  private
  # Strong parameters for security
  def payment_params
    params.require(:payment).permit(:email)
  end
end

 

In app/views/payments/new.html.erb, create the payment form: 

 

<h1>Checkout</h1>
<form id="payment-form">
  <input type="text" id="customer-email" placeholder="Enter your email">
  <button type="button" id="checkout-button">Pay Now</button>
</form>

<script src="https://cdn.paddle.com/paddle/paddle.js"></script>
<script type="text/javascript">
  Paddle.Setup({ vendor: <%= ENV['PADDLE_VENDOR_ID'] %> });
  document.getElementById('checkout-button').addEventListener('click', function() {
    var email = document.getElementById('customer-email').value;
    Paddle.Checkout.open({
      email: email,
      product: YOUR_PRODUCT_ID, // Replace with your Paddle product ID
      successCallback: function(data) {
        // Handle successful payment here
        console.log(data);
      },
      closeCallback: function() {
        // Handle checkout closure here
        console.log('Checkout closed');
      }
    });
  });
</script>

 

Replace YOUR_PRODUCT_ID with your actual product ID from your Paddle account. 

Step 5: Handling Payment Confirmation with Webhooks
After a payment is processed, Paddle sends a webhook notification to your server. Let's set up a webhook endpoint to handle these notifications.

Add a route for the webhook in config/routes.rb

 

Rails.application.routes.draw do
  # Other routes
  post 'paddle/webhook', to: 'webhooks#paddle'
end

 

 Generate a controller to handle webhooks:

 

rails generate controller Webhooks paddle

 In app/controllers/webhooks_controller.rb, handle the webhook logic:

 

class WebhooksController < ApplicationController
  skip_before_action :verify_authenticity_token

  def paddle
    # Verify the webhook
    verified = Paddle::Webhook.verify(params, ENV['PADDLE_PUBLIC_KEY'])
    if verified
      # Process the webhook data
      Payment.create!(
        email: params[:email],
        amount: params[:amount],
        payment_id: params[:order_id],
        status: params[:status]
      )
      render json: { message: 'Payment processed' }, status: :ok
    else
      render json: { message: 'Invalid webhook' }, status: :unprocessable_entity
    end
  end
end

 

 Make sure you have set PADDLE_PUBLIC_KEY in your environment variables, which you can find in your Paddle account settings.

Step 6: Testing the Integration

Run your Rails server and navigate to http://localhost:3000/payments/new. Enter your email and click "Pay Now" to complete the checkout process with Paddle.

Once the payment is successful, Paddle will send a webhook to your server. Your server will process the payment data and create a record in your database.

Conclusion

Integrating Paddle into your Rails application provides a powerful, scalable solution for managing online payments. With features tailored for SaaS businesses and digital product vendors, Paddle's integration can streamline your payment processes and offer robust analytics and fraud prevention.

By following this guide, you have set up Paddle in your Rails application, created a payment form, handled payment confirmations via webhooks, and ensured secure communication with Paddle. This integration not only diversifies your payment processing capabilities but also equips your application with a reliable and scalable payment solution.


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