Join the social network of Tech Nerds, increase skill rank, get work, manage projects...
 
  • Integrating payment gateway in Rails - Part 1

    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 196
    Comment on it

    Payment gateways are used in websites for online shopping and money transactions. It safely handles customer payments. Payment gateway can easily be integrated in Rails application. Few applications for payment gateway integration in Rails are Sripe, PayPal, Braintree etc.

    In this tutorial we will add stripe payment to our application.


    1. first create Stripe Account. You will need an email account to sign up for Stripe.

     

    2. create project and set up for stripe.

      Add stripe gem to your Gemfile and run bundle install. create course and registration models. We will register user for provided courses. Registration model will also store stripe token and user stripe email.3. To setup the strip and api key, create stripe.rb in initializer and add following code:
      

    Rails.configuration.stripe = {
        :publishable_key => Rails.application.secrets.stripe_publishable_key,
        :secret_key      => Rails.application.secrets.stripe_secret_key
    }
    
    Stripe.api_key = Rails.application.secrets.stripe_secret_key

    The stripe keys can be found in your stripe account: Your account > Account Settings > API keys

     

    4. We will use testing keys for the development environment. add these keys in secrets.yml.

     development:
        stripe_publishable_key: publisherKey_xxxxxxxxxxxxxxxxxxxxxxxx
        stripe_secret_key: secretKey_xxxxxxxxxxxxxxxxxxxxxxxx

    In production environment you will not want to have those keys in secrets.yml for security purpose. You can use environment variables instead. Figaro and Dotenv gem helps setting environment variables.


    5. Now we need to create a registration form for checkout. 
       

    app/views/registrations/new.html.erb
    
      <section>
        <section>
          <section>
            <div>
              <%= form_for @registration do |f| %>
                <% if @registration.errors.any? %>
                  <div id="error_explanation">
                    <h2>
                      <%= pluralize(@registration.errors.count, "error") %>
                      prohibited this registration from being saved
                    </h2>
                    <ul>
                      <% @registration.errors.full_messages.each do |message| %>
                        <li>
                          <%= message %>
                        </li>
                      <% end %>
                    </ul>
                  </div>
                <% end %>
                <div class="field">
                  <%= f.hidden_field :course_id, value: @course.id %>
                </div>
                <div class="field">
                  <%= f.label :name %>
                  <%= f.text_field :name %>
                </div>
                <div class="field">
                  <%= f.label :contact %>
                  <%= f.text_field :contact %>
                </div>
                <div class="actions">
                  <script class="stripe-button" src="https://checkout.stripe.com/checkout.js"
                    data-amount="<%=@course.price*100%>" data-description="<%=@course.name%>" data-key="<%=Rails.application.secrets.stripe_publishable_key%>">
                  </script>
                </div>
              <% end %>
            </div>
          </section>
        </section>
      </section>

    The checkout.js script creates a Submit button for the form and a popup window to input card details for payment. When user submits the form in pop-up window, checkout.js sends the user information to Stripe. If user details is valid stripe returns token for payment. The scipt add 2 hidden fields (stripeEmail and stripeToken) in the form before submitting.

    This way checkout.js makes sure the user card details does not flow to application server.

     

    Parameters received on registration#create :

      Parameters: {"utf8"=>"", "authenticity_token"=>"rvjoou08492BuEfswz04BOAWaW5ebDLQIAChoA3Q=", "registration"=>{"course_id"=>"2", "name"=>"joseph", "contact"=>"9999999"}, "stripeToken"=>"tok_17wn1VH0bpYggiY4JWBE2rT8o", "stripeTokenType"=>"card", "stripeEmail"=>"dummy@gmail.com"}


    6. In our registration model we create an instance method process_payment.

     def process_payment
        customer = Stripe::Customer.create email: email, card: card_token
        Stripe::Charge.create customer: customer.id, amount: course.price * 100, description: course.name, currency: 'usd'
      end

    Note: here in amount we are passing course.price*100, because Stripe expects the amount in cents, not dollars.


    7. Creating registration#create and processing payment 

      In controller we will create registration and process payments: 

    app/controller/registration_controller.rb
    
      def new
        @registration = Registration.new
        @course = Course.find_by id: params["course_id"]
      end
    
      def create
        @registration = Registration.new registration_params.merge(email: stripe_params["stripeEmail"],
                                                                   card_token: stripe_params["stripeToken"])
        
        raise "Registration not vaild" unless @registration.valid?
        @registration.process_payment
        @registration.save
        redirect_to @registration, notice: 'Registration created successfully.'
        rescue
          flash[:error] = e.message
          render :new
      end
    
      private
    
        def stripe_params
          params.permit :stripeEmail, :stripeToken
        end
    
        def registration_params
          params.require(:registration).permit(:course_id, :name, :contact)
        end


    In above code we create registration and also save stripeEmail and stripeToken in registration. If any error raises, the registration will not be created and error will be shown on the page.

     

    If registration is successfully saved to database. You may also see payments made to your stripe dashboard also a new customer is created for payment. 

     

    You can test payments with card number for testing: 4242 4242 4242 4242, with any 3-digit CVV. You may also try other cards mentioned on stripe's website. Visit the link: https://stripe.com/docs/testing

    In next tutorial we will integrate PayPal with our rails app. 
     

 0 Comment(s)

Sign In
                           OR                           
                           OR                           
Register

Sign up using

                           OR                           
Forgot Password
Fill out the form below and instructions to reset your password will be emailed to you:
Reset Password
Fill out the form below and reset your password: