Stripe Integration with Ruby on Rails

Krutik Thaker
Simform Engineering
4 min readMar 29, 2023

Learn how to integrate Stripe into the Ruby on Rails application and start receiving customer payments online.

Stripe is a popular payment processing platform that allows businesses to accept payments online. Integrating Stripe with your Ruby on Rails application is a great way to start accepting customer payments.

I'll walk you through the process of integrating Stripe in this blog article

Step 1 :

Firstly, you need to set up the stripe account

You can visit the Stripe dashboard by following this URL https://dashboard.stripe.com and sign up or log in to the Stripe dashboard.

Once you log in, you can retrieve your stripe API keys from the stripe account dashboard and go to the developer's section. Further, you can find your publishable and secret keys(which you can't share and should keep to yourself) in the API keys in the developer's section.

Step 2 :

The next step would be to add a striped gem to your rails application gemfile

gem 'stripe'

Then run bundle install to install the gem

Step 3 :

Next, you have to create a stripe initializers file

Create a file in config/initializers called Stripe. rb. and add the following

Rails.configuration.stripe = {
publishable_key: ENV["STRIPE_PUBLISHABLE_KEY"],
secret_key: ENV["STRIPE_SECRET_KEY"]
}
Stripe.api_key = Rails.configuration.stripe[:secret_key]

This code sets up the stripe API key authentication, the publishable and secret keys.

Step 4 :

The next step would be to create a Stripe customer and set up a charge for that customer.

Generate a controller and setup the routes
I am using a payments controller with the following code:

resources :payments

Then in the payments controller, under create method

Class PaymentsController < ApplicationController
def new
end

def create
customer = Stripe::Customer.create({
:email => params[:stripeEmail],
:source => params[:stripeToken]
})

charge = Stripe::Charge.create({
:customer => customer.id,
:amount => 500,
:description => 'Description of your product',
:currency => 'usd'
})

rescue Stripe::CardError => e
flash[:error] = e.message
redirect_to new_payment_path
end
end

Step 5 :

Now you must create a view file for the user to enter payment details.

Create a file under app/views/payments/new.html.erb. Add the following to it:

<%= form_tag payments_path do %>
<label class="amount">
<span>Amount: $5.00</span>
</label>

<script
src="https://checkout.stripe.com/checkout.js" class="stripe-button"
data-key="<%= Rails.configuration.stripe[:publishable_key] %>"
data-description="A month's subscription"
data-amount="500"
data-locale="auto">
</script>
<% end %>

The code above generates a Stripe checkout button, opening a Stripe-hosted checkout page where customers can enter their payment details. This will charge a fixed fee of USD 5.00 using your Stripe API credentials.

How to charge customers for monthly subscriptions using Stripe

But is this all that you can do with Stripe?

You can use Stripe for much more use, like using a Rails helper method called "checkout session path."

You can use the Stripe checkout session path when you don't want a view specific to adding user payment details, like the checkout javascript mentioned above.

Stripe checkout path helper generates a unique checkout session ID for Stripe's Checkout API. The checkout session can be customized with various options, such as product and pricing details, customer information, and payment and shipping preferences.

You can use either method that is feasible for you. Let's say you want to create a subscription for your application so you can go to the products in the stripe dashboard.

Add a product and create pricing for it; for example, I am naming it the premium plan with a price of $500.

Adding a product in the stripe dashboard image

After that, you can open that product and check the price ID and product ID, which you can use in the checkout path. I am using the price ID of the plan.

So, therefore in the payments controller under create method add the following

Class PaymentsController < ApplicationController
def create
#create stripe customer for payment, update if already created
customer = Stripe::Customer.create(
name: current_user.full_name,
email: current_user.email,
description: "Customer id: #{current_user.id}",
)

session = Stripe::Checkout::Session.create(
customer: customer,
payment_method_types: [‘card’],
line_items: [{
price: 'price_1234', #price api id usually starts with price_ApIiD
quantity: 1,
}],
mode: 'subscription',
success_url: payments_success_url,
cancel_url: payments_cancel_url
)
redirect_to session.url
end

def success
#handle successful payments
redirect_to root_url, notice: "Purchase Successful"
end

def cancel
#handle if the payment is cancelled
redirect_to root_url, notice: "Purchase Unsuccessful"
end
end

Add the success and cancel methods in the controller to handle successful and unsuccessful payments. This will create a Stripe subscription and add it to Stripe::Subscription.list, which you can check.

Also, add a checkout button and any routes needed.

<%= button_to ‘Subscribe’, payment_create_path, method: :post %>
post ‘payments/create’ 
get ‘payments/success’
get ‘payments/cancel’

Finally, you can start the Rails server and test the code you have added.

rails server

Conclusion
We often want to use a payment gateway for receiving payments from customers. That's where the Stripe comes in. With the help of Stripe API, you can charge customers for their subscriptions or payments for the products they purchase.

You can explore more about Stripe through the stripe docs for Ruby https://stripe.com/docs/api/pagination/auto. Happy Coding!!

Follow Simform engineering to keep up with all the latest trends in the development ecosystem.

--

--