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
    • 996
    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.

        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. 

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

    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"=>""}

    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:, amount: course.price * 100, description:, currency: 'usd'

    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: 

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

    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:

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

 0 Comment(s)

Sign In

Sign up using

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: