Skip to content

Instantly share code, notes, and snippets.

@DeepNeuralAI
Last active April 24, 2019 05:49
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save DeepNeuralAI/952c84174db677e1afe9e500a138b3d6 to your computer and use it in GitHub Desktop.
Save DeepNeuralAI/952c84174db677e1afe9e500a138b3d6 to your computer and use it in GitHub Desktop.
Rails - Stripe

Rails - Stripe Add-on

image

Add stripe and dotenv to your Gemfile.

gem 'stripe'
gem 'dotenv-rails', groups: [:development, :test]

Run bundle install

Generate a Charges Controller

Run rails g controller charges

The controller does two things:

  1. Shows a credit card form (using Checkout).
  2. Creates the actual charges by calling Stripe API

Add Actions to Charges Controller (New & Create)

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

Define the Route

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

Configuring Dotenv

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_****

Example: image

Configure Application

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]

Stripe Advises:

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.

Add A View

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.

Add a Confirmation Page

Make a create.html.erb view under app/views/charges

<h2>Thanks, you paid <strong>$5.00</strong>!</h2>

Check Stripe Dashboard for Purchases

image

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment