学生向けプログラミング入門 | 無料

学生向けにプログラミングを無料で解説。Java、C++、Ruby、PHP、データベース、Ruby on Rails, Python, Django

Rails7.1 | 仕事売買アプリ作成 | 43 | クレジットカード決済

↓↓クリックして頂けると励みになります。


42 | Stripe Connect】 << 【ホーム】 >> 【44 | メッセージ




仕事を登録したクレジットカードで購入できるよう実装します。

コントローラー



チェックアウトメソッドを実装します。
1. 記述追加 app\controllers\gigs_controller.rb(104行目)

  def checkout
    if current_user.stripe_id
      @stripe_customer = Stripe::Customer.retrieve(current_user.stripe_id)

      @gig = Gig.find(params[:id])
      @pricing = @gig.pricings.find_by(pricing_type: params[:pricing_type])
    else
      redirect_to settings_payment_path, alert: "先にクレジットカードを登録して下さい"
    end
  end



仕事を売る人が仕事を新規登録する際、先に振込口座の登録しなければ新規登録できないようにします。


2.記述追加 app\controllers\gigs_controller.rb(9行目)

  def new
    if current_user.merchant_id.blank?
      return redirect_to settings_payout_path, alert: "振込先の登録を先に行ってください。"
    else
      @gig = current_user.gigs.build
      @categories = Category.all
    end
  end



記述編集 app\controllers\gigs_controller.rb

class GigsController < ApplicationController
 
  protect_from_forgery except: [:upload_photo]
  before_action :authenticate_user!, except: [:show]
  before_action :set_gig, except: [:new, :create]
  before_action :is_authorised, only: [:edit, :update, :upload_photo, :delete_photo]
  before_action :set_step, only: [:update, :edit]
  
  def new
    if current_user.merchant_id.blank?
      return redirect_to settings_payout_path, alert: "振込先の登録を先に行ってください。"
    else
      @gig = current_user.gigs.build
      @categories = Category.all
    end
  end

  def create
    @gig = current_user.gigs.build(gig_params)

    if @gig.save
      @gig.pricings.create(Pricing.pricing_types.values.map{ |x| {pricing_type: x} })
      redirect_to edit_gig_path(@gig), notice: "保存しました"
    else
      redirect_to request.referrer, flash: { error: @gig.errors.full_messages }
    end
  end

  def edit
    @categories = Category.all
  end

  def update

    if @step == 2
      gig_params[:pricings_attributes].each do |index, pricing|
        if @gig.has_single_pricing && pricing[:pricing_type] != Pricing.pricing_types.key(0)
          next;
        else
          if pricing[:title].blank? || pricing[:description].blank? || pricing[:delivery_time].blank? || pricing[:price].blank?
            return redirect_to request.referrer, flash: {error: "価格が無効です"}
          end
        end
      end
    end

    if @step == 3 && gig_params[:description].blank?
      return redirect_to request.referrer, flash: {error: "詳細を空白にすることはできません"}
    end

    if @step == 4 && @gig.photos.blank?
      return redirect_to request.referrer, flash: {error: "写真がありません"}
    end

    if @step == 5
      @gig.pricings.each do |pricing|
        if @gig.has_single_pricing && !pricing.basic?
          next;
        else
          if pricing[:title].blank? || pricing[:description].blank? || pricing[:delivery_time].blank? || pricing[:price].blank?
            return redirect_to edit_gig_path(@gig, step: 2), flash: {error: "価格が無効です"}
          end
        end
      end

      if @gig.description.blank?
        return redirect_to edit_gig_path(@gig, step: 3), flash: {error: "詳細を空白にすることはできません"}
      elsif @gig.photos.blank?
        return redirect_to edit_gig_path(@gig, step: 4), flash: {error: "写真がありません"}
      end
    end

    if @gig.update(gig_params)
      flash[:notice] = "保存しました"
    else
      return redirect_to request.referrer, flash: {error: @gig.errors.full_messages}
    end

    if @step < 5
      redirect_to edit_gig_path(@gig, step: @step + 1)
    else
      redirect_to dashboard_path
    end

  end

  def show
    @photos = @gig.photos
    @categories = Category.all
    @i = 0
  end

  def upload_photo
    @gig.photos.attach(params[:file])
    render json: { success: true }
  end

  def delete_photo
    @image = ActiveStorage::Attachment.find(params[:photo_id])
    @image.purge
    redirect_to edit_gig_path(@gig, step: 4)
  end

  def checkout
    if current_user.stripe_id
      @stripe_customer = Stripe::Customer.retrieve(current_user.stripe_id)

      @gig = Gig.find(params[:id])
      @pricing = @gig.pricings.find_by(pricing_type: params[:pricing_type])
    else
      redirect_to settings_payment_path, alert: "先にクレジットカードを登録して下さい"
    end
  end

  private
  def set_step
    @step = params[:step].to_i > 0 ? params[:step].to_i : 1
    if @step > 5
      @step = 5
    end
  end

  def set_gig
    @gig = Gig.find(params[:id])
  end

  def is_authorised
    redirect_to root_path, alert: "あなたには権限がありません。" unless current_user.id == @gig.user_id
  end

  def gig_params
    params.require(:gig).permit(:title, :video, :summary, :description, :active, :category_id, :has_single_pricing, :photos, 
                                pricings_attributes: [:id, :title, :description, :delivery_time, :price, :pricing_type])
  end
end



「app\controllers\orders_controller.rb」ファイルに以下の記述を追加します。


記述追加 app\controllers\orders_controller.rb
createメソッドの9~11行目、42行目からの「charge()」メソッドの記述を大幅に変更しています。
コードをコピーしてファイルの内容を置き換えて下さい。

class OrdersController < ApplicationController
    before_action :authenticate_user!
    
    def create
        gig = Gig.find(params[:gig_id])
        pricing = gig.pricings.find_by(pricing_type: params[:pricing_type])

        if (pricing && !gig.has_single_pricing) || (pricing && pricing.basic? && gig.has_single_pricing)
            if charge(gig, pricing)
               return redirect_to buying_orders_path
            end
        else
            flash[:alert] = "価格が間違っています。"
        end

        redirect_to request.referrer
    end

    def selling_orders
        @orders = current_user.selling_orders
    end

    def buying_orders
        @orders = current_user.buying_orders
    end

    def complete
        @order = Order.find(params[:id])

        if !@order.completed?
            if @order.completed!
                flash[:notice] = "保存しました"
            else
                flash[:notice] = "問題が発生しました"
            end
            redirect_to request.referrer
        end    
    end

    private

    def charge(gig, pricing)
        order = gig.orders.new
        order.title = gig.title
        order.due_date = Date.today() + pricing.delivery_time.days
        order.seller_name = gig.user.full_name
        order.seller_id = gig.user.id
        order.buyer_name = current_user.full_name
        order.buyer_id = current_user.id
        order.amount = pricing.price * 1.1

        amount = pricing.price * 1.1
        
        host_amount = (amount * 0.8).to_i # 売上の80%がホストに入る

        charge = Stripe::Charge.create({
            amount: (amount).to_i,
            customer: current_user.stripe_id,
            source: params[:payment],
            currency: "jpy",
            transfer_data: {
                    amount: host_amount, 
                    destination: gig.user.merchant_id, # ホストのストライプID
                    },
        })

        order.save
        flash[:notice] = "決済が完了しました。。"

        return true

    rescue ActiveRecord::RecordInvalid
        flash[:alert] = "問題が発生しました。"
        return false
    end
end


ルート設定



ルートの設定をします。


「config\routes.rb」ファイルに以下の記述を追加します。


記述追加 config\routes.rb(18行目)

get '/gigs/:id/checkout/:pricing_type', to: 'gigs#checkout', as: 'checkout'



config\routes.rb

Rails.application.routes.draw do

  # ルートを app\views\pages\home.html.erb に設定
  root 'pages#home'

  # get
  get 'pages/home'
  get '/dashboard', to: 'users#dashboard'
  get '/users/:id', to: 'users#show', as: 'user'
  get '/selling_orders', to: 'orders#selling_orders'
  get '/buying_orders', to: 'orders#buying_orders'
  get '/all_requests', to: 'requests#list'
  get '/request_offers/:id', to: 'requests#offers', as: 'request_offers'
  get '/my_offers', to: 'requests#my_offers'
  get '/search', to: 'pages#search'
  get 'settings/payment', to: 'users#payment', as: 'settings_payment'
  get 'settings/payout', to: 'users#payout', as: 'settings_payout'
  get '/gigs/:id/checkout/:pricing_type', to: 'gigs#checkout', as: 'checkout'

  # post
  post '/users/edit', to: 'users#update'
  post '/offers', to: 'offers#create'
  post '/reviews', to: 'reviews#create'
  post '/search', to: 'pages#search'
  post '/settings/payment', to: 'users#update_payment', as: "update_payment"

  # put
  put '/orders/:id/complete', to: 'orders#complete', as: 'complete_order'
  put '/offers/:id/accept', to: 'offers#accept', as: 'accept_offer'
  put '/offers/:id/reject', to: 'offers#reject', as: 'reject_offer'

  resources :gigs do
    member do
      delete :delete_photo
      post :upload_photo
    end
    resources :orders, only: [:create]
  end

  resources :requests
  resources :reviews, only: [:create, :destroy]
  
  # device
  devise_for :users, 
    path: '', 
    path_names: {sign_up: 'register', sign_in: 'login', edit: 'profile', sign_out: 'logout'},
    controllers: {omniauth_callbacks: 'omniauth_callbacks', registrations: 'registrations'}
  # Define your application routes per the DSL in https://guides.rubyonrails.org/routing.html

  # Reveal health status on /up that returns 200 if the app boots with no exceptions, otherwise 500.
  # Can be used by load balancers and uptime monitors to verify that the app is live.
  get "up" => "rails/health#show", as: :rails_health_check

  # Defines the root path route ("/")
  # root "posts#index"
end



「app\views\gigs\show.html.erb」ファイルの記述を変更します。


仕事を依頼するボタンの記述を以下の記述に置き換えます。
記述変更 app\views\gigs\show.html.erb(64行目)

<% if (!user_signed_in? && @gig.active) || (user_signed_in? && @gig.active && @gig.user_id != current_user.id) %>
         <%= link_to "仕事を依頼する (#{number_to_currency(p.price)})", checkout_path(id: @gig.id, pricing_type: p.pricing_type), class: "btn btn-danger w-100" %>
<% else %>
        <button class="btn btn-danger" disabled>依頼できません</button>  
<% end %>



app\views\gigs\show.html.erb

<div class="container">
    <div class="mt-4 mb-4">
        <%= render 'shared/categories' %>
    </div>
    <div class="row">
        <!--  左側 -->
        <div class="col-md-4">
            <h5 class="font2 bg-light p-2" style="border-radius: 10px;"><%= @gig.title %></h5>
            <% if @gig.has_single_pricing %>
                <div class="card">
                    <div class="card-body">
                        <% @gig.pricings.each do |p| %>
                            <% if p.title %>
                                <div class="card-title font1">シングルプラン <span class="badge bg-danger"><%= number_to_currency(p.price) %></span></div>                            
                                <div class="font2"><%= p.description %></div>
                                <div><i class="far fa-clock"></i><span class="font2">期日:<%= p.delivery_time %></span></div>                                             
                                <div class="mt-4">
                                    <% if (!user_signed_in? && @gig.active) || (user_signed_in? && @gig.active && @gig.user_id != current_user.id) %>
                                        <%= form_for([@gig, @gig.orders.new]) do |f| %>
                                            <%= hidden_field_tag 'pricing_type', p.pricing_type %>
                                            <%= f.submit "仕事を依頼する(#{number_to_currency(p.price)})", class: "btn btn-danger w-100", data: {confirm: "本当によろしいですか?"} %>
                                        <% end %>    
                                    <% else %>
                                        <button class="btn btn-danger" disabled>ご利用できません</button>  
                                    <% end %>
                                </div>
                            <% end %>
                        <% end %>
                    </div>
                </div>
            <% else %>
                <ul class="nav nav-pills mb-3" id="pills-tab" role="tablist">          
                    <% Pricing.pricing_types.each do |key, value| %>
                        <li class="nav-item" role="presentation">
                            <button class="nav-link <%= 'active' if value == 0 %>" id="pills-<%= key %>-tab" data-bs-toggle="pill" data-bs-target="#pills-<%= key %>" type="button" role="tab" aria-controls="pills-<%= key %>" aria-selected="<%= 'true' if value == 0 %><%= 'false' if !value == 0 %>">

                                <% if value == 0 %>
                                    ベーシック
                                <% elsif value == 1 %>
                                    スタンダード
                                <% else %>
                                    プレミアム
                                <% end %>

                            </button>
                        </li>
                    <% end %>
                </ul>
                <div class="tab-content" id="pills-tabContent">
                    
                    <% @gig.pricings.each do |p| %>
                        <div class="tab-pane fade <%= 'show active' if p.pricing_type == 'basic' %>" id="pills-<%= p.pricing_type %>" role="tabpanel" aria-labelledby="pills-<%= p.pricing_type %>-tab" tabindex="0">
                        
                            <div class="card">
                                <div class="card-body">
            
                                    <div class="card-title font1"><%= p.title %> <span class="badge bg-danger"><%= number_to_currency(p.price) %></span></div>
                                                                                                        
                                    
                                    <div class="font2"><%= p.description %></div>
                                    <div><i class="far fa-clock"></i><span class="font2">期日:<%= p.delivery_time %></span></div>                                             

                                    <div class="mt-4">
                                        <% if (!user_signed_in? && @gig.active) || (user_signed_in? && @gig.active && @gig.user_id != current_user.id) %>
                                            <%= link_to "仕事を依頼する (#{number_to_currency(p.price)})", checkout_path(id: @gig.id, pricing_type: p.pricing_type), class: "btn btn-danger w-100" %>
                                        <% else %>
                                            <button class="btn btn-danger" disabled>依頼できません</button>  
                                        <% end %>
                                    </div>
                                    
                                </div>
                            </div>
                        </div>
                    <% end %>
                </div>
            <% end %>           
        </div>

        <!--右側 -->
        <div class="col-md-8">
            <div class="card mt-4 mb-4">
                <div class="card-body">
                    <h5 class="font1">フリーランサー</h5>
                    <div class="mt-2">
                    <%= link_to user_path(@gig.user), style: "text-decoration:none;" do %>
                        <%= image_tag avatar_url(@gig.user), class: "bd-placeholder-img figure-img img-fluid rounded-pill", style: "width: 80px;" %>
                        <span class="font2 text-dark h4"><%= @gig.user.full_name %></span>
                    <% end %>
                    </div>
                    <div class="font2">
                        <%= @gig.description %>
                    </div>
                </div>
            </div>
            <!-- カルーセル表示 -->
            <div class="card">
                <div class="card-body">

                    <div id="carouselExampleIndicators" class="carousel slide" data-bs-ride="carousel">
                        <div class="carousel-indicators">
                            <% @photos.each do |photo| %>
                                <button type="button" data-bs-target="#carouselExampleIndicators" data-bs-slide-to="<%= @i %>" class="<%= 'active' if photo.id == @photos[0].id %>" aria-current="true" aria-label="Slide <%= @i+1 %>"></button>
                                <% @i = @i +1 %>
                            <% end %>
                        </div>
                        <div class="carousel-inner">
                            <%  @gig.photos.each do |photo| %>
                                <div class="carousel-item <%= 'active' if photo.id == @photos[0].id %>">
                                    <%= image_tag url_for(photo), class: "d-block w-100", style: "border-radius: 10px;" %>
                                </div>
                            <% end %>
                        </div>
                        <button class="carousel-control-prev" type="button" data-bs-target="#carouselExampleIndicators" data-bs-slide="prev">
                            <span class="carousel-control-prev-icon" aria-hidden="true"></span>
                            <span class="visually-hidden">Previous</span>
                        </button>
                        <button class="carousel-control-next" type="button" data-bs-target="#carouselExampleIndicators" data-bs-slide="next">
                            <span class="carousel-control-next-icon" aria-hidden="true"></span>
                            <span class="visually-hidden">Next</span>
                        </button>
                    </div>
                </div>
            </div>

            <!-- Youtube表示 -->
            <% if @gig.video.present? %>
            <div class="card mt-4">
                <iframe height="360" src="https://www.youtube.com/embed/<%= @gig.video %>" allowfullscreen></iframe>
            </div>
            <% end %>
        </div>

    </div>
</div>



「app\views\gigs」フォルダに「checkout.html.erb」ファイルを新規作成して下さい。


app\views\gigs\checkout.html.erb(新規作成したファイル)

<div class="container">
    <div class="row">

        <!-- 左側 -->
        <div class="col-md-4">
            <div class="card mt-4">
                <div class="card-body">
                    <div class="card-title font1">
                        クレジットカード
                    </div>
                    <% @stripe_customer.sources.each do |payment| %>
                        <%= radio_button_tag 'payment', payment.id, checked: true %>
                        <%= payment.brand %><%= " **** **** **** " + payment.last4 %>
                    <% end %>
                </div>
            </div>
        </div>
        <!-- 右側 -->
        <div class="col-md-8">
            <div class="container mt-4 mb-4">
                <div class="card mt-4">
                    <%= form_with model: [@gig, @gig.orders.new] do |f| %>
                        <%= hidden_field_tag 'pricing_type', @pricing.pricing_type %>
                        <%= image_tag gig_cover(@gig), style: "width: 100%;", class: "card-img-top" %>
                            <div class="card-body">
                                <div>
                                <h4><strong><%= @gig.title %></strong></h4>
                                </div>
                                <div>
                                    <h6><strong>プラン:
                                 
                                        <% if @pricing.pricing_type == 'basic' %>
                                            <span class="badge bg-info">ベーシック</span>
                                        <% elsif @pricing.pricing_type == 'standard' %>
                                            <span class="badge bg-primary">スタンダード</span>
                                        <% else %>
                                            <span class="badge bg-dark">プレミアム</span> 
                                        <% end %>                                    
                                    </strong></h6>
                                </div>        
                                <div>
                                    <h6><strong>期日: <%= @pricing.delivery_time %></strong></h6>
                                </div>                                
                                <div>
                                    <h6><strong>小計: <%= number_to_currency(@pricing.price) %></strong></h6>
                                </div>
                                <div>
                                    <h6><strong>消費税(10%): <%= number_to_currency(@pricing.price * 0.1) %></strong></h6>
                                </div>        
                                <div>
                                    <h5><strong>合計: <%= number_to_currency(@pricing.price * 1.1) %></strong></h5>
                                </div>        
                        
                                <%= f.submit "購入する", class: "btn btn-danger w-100", data: {confirm: "本当によろしいですか?"} %>
                            </div>
                    <% end %>
                </div>
            </div>
        </div>       
    </div>
</div>


テストで仕事を購入する際、売り手の振込先登録がないとエラーがでます。
ユーザテーブルの「merchant_id」をコピーしておくとテストがスムーズにいきます。

merchant_id
merchant_id



また、Stripeの個人設定で国を「日本」にしていない場合、「Stripe::InvalidRequestError」エラーが出てしまいます。
以下のリンクから設定を変更してください。
https://dashboard.stripe.com/settings/account


実際に仕事を購入して動作を確認します。
ブラウザ確認
http://localhost:3000/gigs/4


仕事を依頼するボタンをクリックします。

仕事を依頼する
仕事を依頼する



購入するボタンをクリックします。

購入する
購入する



購入済み仕事一覧ページに推移します。

購入済み仕事一覧
購入済み仕事一覧



Stripeのダッシュボードで「支払い」を確認します。

Stripeダッシュボード「支払い」
Stripeダッシュボード「支払い」



詳細を見ると売上の80%が売り手の口座に支払われているのが確認できます。

自動支払振り込み
自動支払振り込み



42 | Stripe Connect】 << 【ホーム】 >> 【44 | メッセージ




↓↓クリックして頂けると励みになります。