Add stripe and dotenv to your Gemfile.
gem 'stripe'
gem 'dotenv-rails', groups: [:development, :test]
Run bundle install
Run rails g controller charges
The controller does two things:
- Shows a credit card form (using Checkout).
- Creates the actual charges by calling Stripe API
class ChargesController < ApplicationController
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
end
Add resources :charges
to config/routes.rb
Your routes.rb file could look like this:
Rails.application.routes.draw do
root 'books#index'
resources :books
devise_for :users
resources :authors
resources :reviews
resources :charges
# For details on the DSL available within this file, see http://guides.rubyonrails.org/routing.html
end
Navigate to .env
or create it if it does not exist. You need to create this file in the root folder of your project.
Create the following variables and paste in the appropriate information from Stripe.
.env file should look similar to this:
PUBLISHABLE_KEY=pk_test_****
SECRET_KEY=sk_test_****
Add the following to config/initializers/stripe.rb:
Rails.configuration.stripe = {
:publishable_key => ENV['PUBLISHABLE_KEY'],
:secret_key => ENV['SECRET_KEY']
}
Stripe.api_key = Rails.configuration.stripe[:secret_key]
These keys values are pulled out of environmental variables so as not to hardcode them.
It’s best practice not to write API keys into your code, where they could easily wind up in source control repositories and other non-private destinations.
In order to use this view over and over, we will place it in a partial template in a shared folder.
Specifically, app/views/layouts/shared/_stripe_form.html.erb
<%= 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="Purchase Book"
data-amount="500"
data-locale="auto"></script>
<% end %>
We place the partial template in our app/views/books/show.html.erb page.
<div class="show-page">
<h2><%= @book.title %></h2>
<hr>
<p>Author: <%=link_to @book.author.name.upcase, author_path(@book.author) %></p>
<p>Genre: <%= @book.description %></p>
<%= render "layouts/shared/stripe_form" %>
[...]
If you are using another application, place the partial render line wherever you want the 'Purchase" button on your page.
Make a create.html.erb
view under app/views/charges
<h2>Thanks, you paid <strong>$5.00</strong>!</h2>