Payment Integration Using Stripe in 5 Easy Steps

Stripe minimal effrst payment gateway to get started. As of official says for stripe

A beautiful, optimized, cross-device payment form, with support for single click payments.

How to Setup

Add gem "stripe" and run bundle install

Create an account on Stripe.com and get API keys and publishable keys. Include them in initializers stripe.rb

stripe.rb
1
2
  Stripe.api_key = "sk_test_xxxxxxxxxxxxxxxxxxxxxxx"
  STRIPE_PUBLISHABLE_KEY = "pk_test_xxxxxxxxxxxxxxxxxxxxxxx"

Include stripe.JS and add stripe meta tag to your application

application.html.erb
1
2
  <%= javascript_include_tag "https://js.stripe.com/v1/", "application" %>
  <%= tag :meta, :name => "stripe-key", :content => STRIPE_PUBLISHABLE_KEY %>

Create a form, with action target as your back end controller and action where you want to handle. I will explain later why we need controller and action.

payment.html.erb
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
<%= form_tag('/custom_path') do |f| %>
<script src="https://checkout.stripe.com/checkout.js" class="stripe-button"

//Publishable Key From stripe
data-key="<%= STRIPE_PUBLISHABLE_KEY %>"

//Appliation Name
data-name="My Appliation"

//Payment amount(in cents)
data-amount="10000"

//Description for payment
data-description="my custom description"

//Text as will appear on payment button.
data-label='Proceed with payment'

//Users email, who is paying
data-email="<%= user.email  %>"
></script>

<% end %>

This will add a nice looking button to your we page.

Clicking on button will open up a popup

Stripe will handle everything from card validation to authorization over card. When user is successfully authenticated the form will be submitted and we get a token at backend alongwith other form fields value. That is where backend comes into play. The token from above can be used only once. We can use it for

Create a customer

def custom_action
  customer = Stripe::Customer.create(
  :email => 'example@stripe.com',
  :card  => params[:stripeToken]
  )
end

We can save the customer_id for customer create above. Now this customer is registered with stripe. We can charge him anytime.

charge = Stripe::Charge.create(
  :customer    => customer.id,
  :amount      => 10000, # amount in cents
  :description => 'Rails Stripe customer',
  :currency    => 'usd'
)

charge.id will return us the unique transaction id for which we can save.

Directly charge the user

begin
  charge = Stripe::Charge.create(
    :amount => 1000, # amount in cents, again
    :currency => "usd",
    :card => token,
    :description => "payinguser@example.com"
  )
rescue Stripe::CardError => e
  # The card has been declined
end

For more details checkout here and here.

Comments