#Tech | 5 min read | Updated: 8/11/2020

How to Use Stripe in Ruby on Rails App

Olga Iakubovska , Senior Project Manager

The time has passed when you were forced to manage all your payments manually. Now all you need is a reliable payment gateway and some time to integrate it into your website.

Reasons why Stripe is one of the best online payment gateway solutions: an international payment system that allows both individuals and businesses to use online payment methods. Let’s learn how to integrate a payment gateway into a website.

How to implement payment gateway: Stripe payment integration

Due to its convenient interface and extensive documentation, Stripe is an easy-to-use solution for any business. We have prepared a brief guide about Stripe payment integration for you entitled, ‘How to add Stripe to a Ruby on Rails application.

Creating the developer’s profile

In order to receive access to a Stripe API key, you will need to create a developer profile. On the Dashboard, go to Account Settings => API keys. You will find two secret keys: the Stripe test and publish keys. These keys are used for the deployment of pre-made integration.

stripe-test-cards

There are three types of keys, including test and live versions.

During the online payment gateway integration, you should only use the Stripe test keys in order to avoid charging real customers accidentally. The live keys are only used when you are ready to deploy your application.

Installing Stripe to the Project

In order to use Stripe in your application, you need to add the Stripe Ruby gem:
gem 'stripe'

Then, add it to the project by launching the $ bundle command and create the controller via the command line $ rails g controller charges.
Upon adding the controller, create the Customer object. Although you can perform the charges directly, creating the customer will allow you to use repetitive billing.

def new
end

def create
# Amount in cents
@amount = 500

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

charge = Stripe::Charge.create(
:customer => customer.id,
:amount => @amount,
:description => ‘Rails Stripe customer’,
:currency => ‘usd’
)

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

Configuring Stripe Keys

Return to your Stripe profile and open the API keys tab. Save your test and live keys in the file secrets.yml and store it in the config folder. The contents of the file should look like this (we used the keys from our test account):

Development:

stripe_secret_key: 'sk_test_nWjL9fQH8v23uSiEPJT5d1Xs'
stripe_publishable_key: 'pk_test_NxfJqAJ1j1w8p0K3959byw1P'

production:

stripe_secret_key: 'sk_live_wHzOtGqRSHVCCh1eaJiVd3M1'
stripe_publishable_key: 'pk_live_iGxbYHVwYXZlQBZAKeuhzYEW'

Then go to the stripe.rb file located in the directory config/initializers/stripe.rb and add the following code there:

Rails.configuration.stripe = {
:publishable_key => ENV['PUBLISHABLE_KEY'],
:secret_key => ENV['SECRET_KEY']
}

Stripe.api_key = Rails.configuration.stripe[:secret_key]

Remember that in order to avoid compromising the application affecting real customers, you should only add the test keys.

Creating Page Views

The next step is to set up how the payment form will be viewed on the page: to create a credit card payment form and the page that is viewed after the charge is processed.

The payment form is necessary for you to charge your customer. The easiest way to integrate it is to use Stripe Checkout – a tool that allows you to accept payments easily. How to use Stripe Checkout? It automatically generates a simple, but functional payment form. To get it, include this code on your payment page.

Now create a charges.html.erb layout under the app/views/layouts directory:

<!DOCTYPE html>
<html>
<head></head>
<body>
<%= yield %>
</body>
</html>

The next step is to create a checkout page new.html.erb in the app/views/charges folder in order to display the payment form, validate the credit card details and report errors:

<%= form_tag charges_path do %>
<article>
<% if flash[:error].present? %>
<div id="error_explanation">
<p><%= flash[:error] %></p>
</div>
<% end %>
<label class="amount">
<span>Amount: $5.00</span>
</label>
</article>

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

Then add a create.html.erb view in the same directory in order to show the user a message about a successful transaction:

<h2>Great! Your payment of $100 was successful!</h2>

Now you know how to implement a payment gateway. We have added the payment form validating the details provided by the customer. The next step we generated a one-time token that will be submitted directly to your server. By default, the snippet will look like below, but it can be customized to match your brand’s colors. Learn how to do this here.

stripe-payment-form

We have successfully implemented Stripe into a Ruby on Rails app. Now it’s time to test what we’ve done and deploy it.

Testing the performance

You successfully did the implement payment gateway. To test the functionality of the integrated payment system, launch the Rails server and set the variables for your test publishable and private keys:

PUBLISHABLE_KEY=pk_test_NxfJqAJ1j1w8p0K3959byw1P
SECRET_KEY=sk_test_nWjL9fQH8v23uSiEPJT5d1Xs rails s

Now, go to http://localhost:3000/charges/new to see the usable payment form. Enter the Stripe test card number, a random three-digit CVC and any future expiration date. If the charge is successful, it will display on your dashboard.

Deploy to Heroku

Having successfully performed the transaction, you are ready to make it publicly available for your users. To deploy the application, you need a Heroku account and an installed Heroku Toolbelt.

Launch the following code:

git init
git add
git commit -m 'My simple Stripe application'
heroku create
heroku config:set PUBLISHABLE_KEY=pk_test_NxfJqAJ1j1w8p0K3959byw1P SECRET_KEY=sk_test_nWjL9fQH8v23uSiEPJT5d1Xs
git push heroku master
heroku open

Since Stripe is now ready to be used, replace your test keys with the live ones. Congratulations! You have successfully set up Stripe for your Ruby on Rails site.

Conclusion

Now you know how to integrate an online payment system on the website. The Stripe deployment with Ruby on Rails isn’t that hard as it looks from the first sight. Nevertheless, in case if you choose and implement any other payment solution or need to develop your website from scratch – Sloboda Studio is here, ready to help.

Do you need any help with Stripe?

How useful was this post?

Click on a star to rate it!

Average rating / 5. Vote count:

No votes so far! Be the first to rate this post.

Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments
Recommended articles
#Guides 10 min

It’s hard to believe that less than a decade ago people had to buy and install all the software they needed on their personal computers. The application disks often got lost or ruined. And if…

#Guides 15 min

One of the things that 2020’s lockdown has taught us is that the Internet is a powerful tool for finding information. Due to the lockdown, many people have lost their jobs and were forced to…

How to make an eCommerce website like Amazon? The story of Amazon started back in 1994 in Jeff Bezos’s garage.  The marketplace grew rapidly, and in 2018, Amazon capitalization grew to $1 trillion making the…

Get more insights

    Let's talk about your idea?

      Alex, Project Lead
      Alex, Project Lead

      +380 99 759 6995