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
    • 1.10k
    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:
      

    1. Rails.configuration.stripe = {
    2. :publishable_key => Rails.application.secrets.stripe_publishable_key,
    3. :secret_key => Rails.application.secrets.stripe_secret_key
    4. }
    5.  
    6. 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.

    1. development:
    2. stripe_publishable_key: publisherKey_xxxxxxxxxxxxxxxxxxxxxxxx
    3. 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. 
       

    1. app/views/registrations/new.html.erb
    2.  
    3. <section>
    4. <section>
    5. <section>
    6. <div>
    7. <%= form_for @registration do |f| %>
    8. <% if @registration.errors.any? %>
    9. <div id="error_explanation">
    10. <h2>
    11. <%= pluralize(@registration.errors.count, "error") %>
    12. prohibited this registration from being saved
    13. </h2>
    14. <ul>
    15. <% @registration.errors.full_messages.each do |message| %>
    16. <li>
    17. <%= message %>
    18. </li>
    19. <% end %>
    20. </ul>
    21. </div>
    22. <% end %>
    23. <div class="field">
    24. <%= f.hidden_field :course_id, value: @course.id %>
    25. </div>
    26. <div class="field">
    27. <%= f.label :name %>
    28. <%= f.text_field :name %>
    29. </div>
    30. <div class="field">
    31. <%= f.label :contact %>
    32. <%= f.text_field :contact %>
    33. </div>
    34. <div class="actions">
    35. <script class="stripe-button" src="https://checkout.stripe.com/checkout.js"
    36. data-amount="<%=@course.price*100%>" data-description="<%=@course.name%>" data-key="<%=Rails.application.secrets.stripe_publishable_key%>">
    37. </script>
    38. </div>
    39. <% end %>
    40. </div>
    41. </section>
    42. </section>
    43. </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 :

    1. 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.

    1. def process_payment
    2. customer = Stripe::Customer.create email: email, card: card_token
    3. Stripe::Charge.create customer: customer.id, amount: course.price * 100, description: course.name, currency: 'usd'
    4. 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: 

    1. app/controller/registration_controller.rb
    2.  
    3. def new
    4. @registration = Registration.new
    5. @course = Course.find_by id: params["course_id"]
    6. end
    7.  
    8. def create
    9. @registration = Registration.new registration_params.merge(email: stripe_params["stripeEmail"],
    10. card_token: stripe_params["stripeToken"])
    11. raise "Registration not vaild" unless @registration.valid?
    12. @registration.process_payment
    13. @registration.save
    14. redirect_to @registration, notice: 'Registration created successfully.'
    15. rescue
    16. flash[:error] = e.message
    17. render :new
    18. end
    19.  
    20. private
    21.  
    22. def stripe_params
    23. params.permit :stripeEmail, :stripeToken
    24. end
    25.  
    26. def registration_params
    27. params.require(:registration).permit(:course_id, :name, :contact)
    28. 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
Reset Password
Fill out the form below and reset your password: