Coding

Building an E-Commerce Store with Rails and Stripe Checkout: Full Tutorial

Today, we will be doing a step by step guide of how to create an E-Commerce store with Ruby on Rails using a session-based shopping cart and Stripe Checkout. 
I will take you through each step, from creating the application to handling payments with Stripe.
I will assume you have basic knowledge of Ruby on Rails. That is just the tip of the iceberg to get you going in this strategy. Add admin just for uploading or/and editing products and all the backends. Let me know in the comments and I may do a part 2.

Table of Contents

1. Establishing the Rails Application

2. Creating the Product Model

3. Session Based Shopping Cart

4. Stripe Integrated Checkout Process

5. Enable Product Image Uploads

6. Final Thoughts and Next Steps


1. Setting Up the Rails Application
Let’s start by setting up a new Rails project.

  1. Create a new Rails application:

  2. rails new ecommerce_store
    cd ecommerce_store

  1. You can build an authentication system from scratch but that is very time-consuming, plus devise already has all the functionality we need.

  2. Install Devise (optional but recommended for user authentication):
  3. Add the gem to your Gemfile:

  4. gem 'devise'

  5. Then run the following commands:

  6. bundle install
    rails generate devise:install
    rails generate devise User
    rails db:migrate

  7. Set up the home page:

  8. Open config/routes.rb and set the root path to the products index page:

  9. root 'products#index'

  1. Install Stripe gem:

  2. Add the following gem to your Gemfile for Stripe:

  3. gem 'stripe'

  4. Run bundle install to install it.

2. Creating the Product Model
Let’s create a Product model with attributes like title, description, price, and stock.

  1. Generate the Product model:

  2. rails generate model Product title:string description:text price:decimal stock:integer
    rails db:migrate


  3. Add validations to the Product model (app/models/product.rb):
  4. class Product < ApplicationRecord
      validates :title, :price, :stock, presence: true
    end

    Create the ProductsController:

  1. Generate the controller:
  2. rails generate controller Products

  1. Define CRUD actions for products (app/controllers/products_controller.rb):
  2. class ProductsController < ApplicationController
      def index
        @products = Product.all
      end
    
      def show
        @product = Product.find(params[:id])
      end
    
      def new
        @product = Product.new
      end
    
      def create
        @product = Product.new(product_params)
        if @product.save
          redirect_to @product, notice: 'Product created successfully.'
        else
          render :new
        end
      end
    
      private
    
      def product_params
        params.require(:product).permit(:title, :description, :price, :stock)
      end
    end

  3. Set up routes for products in config/routes.rb:
  4. resources :products

  1. Create the views:

    • app/views/products/index.html.erb:
    • <h1>Products</h1>
      <ul>
        <% @products.each do |product| %>
          <li><%= link_to product.title, product %> - <%= number_to_currency(product.price) %></li>
        <% end %>
      </ul>
      <%= link_to 'New Product', new_product_path %>

  1.     app/views/products/show.html.erb:
    • <h1><%= @product.title %></h1>
      <p><%= @product.description %></p>
      <p>Price: <%= number_to_currency(@product.price) %></p>

3. Implementing a Shopping Cart Using Sessions
Now we’ll create a session-based shopping cart to store items as users browse the store.

  1. Generate a controller for the cart:

  2. rails generate controller Carts

  1. Define actions for the cart in app/controllers/carts_controller.rb:
  2. class CartsController < ApplicationController
      def show
        @cart_items = current_cart
      end
    
      def add_item
        product = Product.find(params[:product_id])
        cart = current_cart
        cart[product.id.to_s] ||= { 'quantity' => 0 }
        cart[product.id.to_s]['quantity'] += 1
        session[:cart] = cart
    
        redirect_to cart_path
      end
    
      def remove_item
        cart = current_cart
        cart.delete(params[:product_id])
        session[:cart] = cart
    
        redirect_to cart_path
      end
    
      private
    
      def current_cart
        session[:cart] ||= {}
      end
    end

  1. Set up routes for the cart in config/routes.rb:
  2. resource :cart, only: [:show] do
      post 'add_item/:product_id', to: 'carts#add_item', as: :add_item
      delete 'remove_item/:product_id', to: 'carts#remove_item', as: :remove_item
    end

  1. Create views for the cart (app/views/carts/show.html.erb):
  2. <h1>Your Cart</h1>
    
    <% if @cart_items.any? %>
      <% @cart_items.each do |product_id, details| %>
        <% product = Product.find(product_id) %>
        <div>
          <h3><%= product.title %></h3>
          <p>Quantity: <%= details['quantity'] %></p>
          <p>Price: <%= number_to_currency(product.price * details['quantity']) %></p>
          <%= button_to 'Remove', remove_item_cart_path(product_id: product.id), method: :delete %>
        </div>
      <% end %>
    <% else %>
      <p>Your cart is empty.</p>
    <% end %>

  3. Add "Add to Cart" buttons to product views:

  4. In app/views/products/show.html.erb:
  5. <%= button_to 'Add to Cart', add_item_cart_path(product_id: @product.id), method: :post %>

4. Checkout Process with Stripe Integration
Now we’ll integrate Stripe to handle payments.

  1. Set up Stripe:

    • Sign up for a Stripe account and get your API keys from the Stripe Dashboard.

    • Create environment variables for STRIPE_PUBLISHABLE_KEY and STRIPE_SECRET_KEY in config/credentials.yml.enc:
    • stripe:
        publishable_key: pk_test_xxxxx
        secret_key: sk_test_xxxxx


  2. Add Stripe to the application by creating a Checkout controller:

  3. rails generate controller Checkouts

  1. Set up Stripe Checkout in the CheckoutsController:

  2. class CheckoutsController < ApplicationController
      def create
        product = Product.find(params[:product_id])
        @session = Stripe::Checkout::Session.create(
          payment_method_types: ['card'],
          line_items: [{
            name: product.title,
            amount: (product.price * 100).to_i,
            currency: 'usd',
            quantity: 1
          }],
          mode: 'payment',
          success_url: checkout_success_url + "?session_id={CHECKOUT_SESSION_ID}",
          cancel_url: checkout_cancel_url
        )
    
        respond_to do |format|
          format.js # renders create.js.erb for Stripe redirection
        end
      end
    
      def success
        # Handle successful payment logic here
      end
    
      def cancel
        # Handle canceled payment logic here
      end
    end

  1. Set up routes for the checkout process in config/routes.rb:
  2. post 'checkout/create', to: 'checkouts#create'
    get 'checkout/success', to: 'checkouts#success'
    get 'checkout/cancel', to: 'checkouts#cancel'

  1. Create the Stripe Checkout view in JavaScript (app/views/checkouts/create.js.erb):
  2. var stripe = Stripe('<%= Rails.application.credentials[:stripe][:publishable_key] %>');
    stripe.redirectToCheckout({ sessionId: '<%= @session.id %>' });
    

  3. Add a checkout button in the cart:

  4. Modify the app/views/carts/show.html.erb:
  5. <%= button_to 'Checkout with Stripe', checkout_create_path(product_id: product.id), remote: true %>

  6. Ensure you handle payment success and failure properly:

  7. In the CheckoutsController, after payment success, clear the cart and display a confirmation message.

5. Allowing Product Image Uploads
To add image upload functionality, we’ll use Active Storage.

  1. Install Active Storage:

  2. rails active_storage:install
    rails db:migrate

  3. Attach images to the Product model:

  4. Update the Product model to support images:
  5. class Product < ApplicationRecord
      has_one_attached :main_image
      has_many_attached :gallery_images
      validates :title, :price, :stock, presence: true
    end

  1. Update the product form to accept image uploads:

  2. In app/views/products/_form.html.erb:
  3. <%= form_with(model: @product, local: true) do |form| %>
      <div class="field">
        <%= form.label :main_image %>
        <%= form.file_field :main_image %>
      </div>
    
      <div class="field">
        <%= form.label :gallery_images %>
        <%= form.file_field :gallery_images, multiple: true %>
      </div>
    <% end %>

6. Final Thoughts and Next Steps
You now have a basic e-commerce store that allows users to:
  • View and add products to their cart.
  • Use Stripe Checkout to process payments.
  • Upload product images.

From here, you can improve the application by adding features like:
  • User authentication with Devise.
  • Order history and confirmation emails.
  • Enhanced image handling with MiniMagick for resizing.
  • Only allow admin to upload products and product images.
This tutorial serves as a foundation; you can extend it based on your specific requirements.



No comment
Leave a Reply

Your email adress will not be published ,Requied fileds are marked*.

Hi, I'm Kenroy Reid

Hello there

More Form Aurthor
Categories

Get The Best Blog Stories into Your inbox!

Sign up for free and be the first to get notified about new posts.