Friday, 27 September 2019

Stripe gem for Using checkout

Stripe gem for Using checkout

1. The first step is adding the Stripe gem to your application’s Gemfile:
     gem 'stripe' 
     gem "figaro"
  
    Then, run bundle install to install the gem.
 
2. Next, generate a new Charges controller:
     rails g controller charges

    The controller does two things:
  1. Shows a credit card form (using Checkout).
  2. Creates the actual charges by calling our API.
3.  Add two actions to the controller:
       
        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 

4.  Defining the route:-
      So users can access the newly created controller, add a route to it in    
      config/routes.rb:
         resources :charges

5.  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]

      # pk_test_WOuxu6ZZPDsPH6NEpxUYKagu00nMNIXrtl
      # sk_test_AULa1uC5wSoUXCfjIexEsTc400FA8BSNpZ


6.  Add the following to config/application.yml:
     
      publishable_key: pk_test_WOuxu6ZZPDsPH6NEpxUYKagu00nMNIXrtl
      secret_key:      sk_test_mjoMHspX73ijf6dnIT4n7j7J00gcIp1dtK

      RAILS_SERVE_STATIC_FILES: true

7.  Creating the views:-  Now create new.html.erb under app/views/charges
      
<%= 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="A month's subscription"
          data-amount="500"
          data-locale="auto"></script>
<% end %>
 
 
8.  Finally, make a create.html.erb view under app/views/charges that shows 
     users a success message:

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



 
  

No comments:

Post a Comment

  Common Git Commands   Take clone of a repository git clone <remote-repository-url> ex: git clone  https://github.com/agricor/RegTech...