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:
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.
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.
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:
@registration = Registration.new
@course = Course.find_by id: params["course_id"]
@registration = Registration.new registration_params.merge(email: stripe_params["stripeEmail"],
raise "Registration not vaild" unless @registration.valid?
redirect_to @registration, notice: 'Registration created successfully.'
flash[:error] = e.message
params.permit :stripeEmail, :stripeToken
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: https://stripe.com/docs/testing
In next tutorial we will integrate PayPal with our rails app.