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

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

Rails6.0 | 仕事売買サイトの構築 | 40 | 購入

[39]Stripeコネクト << [ホームに戻る] >> [41]trestle


お仕事を購入できるようにします。


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

  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



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
    @gig = current_user.gigs.build
    @categories = Category.all
  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
    @categories = Category.all
  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, :description, :active, :category_id, :has_single_pricing, 
                                pricings_attributes: [:id, :title, :description, :delivery_time, :price, :pricing_type])
  end
  
end



ルートの設定をします。


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


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

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'

  devise_for :users, 
              path: '', 
              path_names: {sign_up: 'register', sign_in: 'login', edit: 'profile', sign_out: 'logout'},
              controllers: {omniauth_callbacks: 'omniauth_callbacks', registrations: 'registrations'}

  get 'pages/home'
  get '/dashboard', to: 'users#dashboard'
  get '/users/:id', to: 'users#show', as: 'users'
  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 '/users/edit', to: 'users#update'
  post '/offers', to: 'offers#create'
  post '/reviews', to: 'reviews#create'
  post '/settings/payment', to: 'users#update_payment', as: "update_payment"

  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

  # For details on the DSL available within this file, see https://guides.rubyonrails.org/routing.html
end



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


記述変更 app\views\gigs\show.html.erb(99~106行目)

<% 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: "button is-fullwidth is-danger" %>
<% else %>
    <button class="button is-fullwidth is-danger" disabled>購入できません</button>  
<% end %>



app\views\gigs\show.html.erb
コードをコピーしてファイルの内容を置き換えて下さい。

<% content_for :head do %>
    <meta name="turbolinks-cache-control" content="no-cache">
<% end %>

<%= render 'shared/categories' %>

<section class="section">
    <div class="container">
        <div class="columns">

            <!-- 左側 -->
            <div class="column is-two-thirds">
                <div class="columns is-multiline">
                    <!-- 画像カルーセル表示 -->
                    <div class="column is-full">   
                        <div class="card">
                            <div class="card-content">
                                <div class="content">
                                    <p class="title is-4"><%= @gig.title %></p>
                                </div>
                                <hr>
                                <div class="hero-carousel" id="carousel-photo">
                                    <% @gig.photos.each do |photo| %>
                                        <div class="carousel-item has-background image is-16by9">
                                            <%= image_tag url_for(photo), class: "is-background", width: "100%" %>
                                        </div>
                                    <% end %>
                                    <% if @gig.video.present? %>
                                        <div class="video-container">
                                            <iframe src="https://www.youtube.com/embed/<%= @gig.video %>" allowfullscreen></iframe>
                                        </div>
                                    <% end %>
                                </div>
                            </div>
                        </div>
                    </div>
                    
                    <!-- お仕事の内容 -->
                    <div class="column">
                        <div class="card">
                            <div class="card-content">
                                <article class="media">
                                    <div class="media-content">
                                        <p><strong>このお仕事について</strong></p>
                                        <hr>
                                        <%= @gig.description %>
                                    </div>
                                </article>
                            </div>
                        </div>                        
                    </div>
                    
                </div>
            </div>

            <!-- 右側 -->
            <div class="column">
                <div class="columns is-multiline">

                    <!-- 価格プラン -->
                    <div class="column is-full">
                        <div class="tabs is-fullwidth" id="tabs">
                            <ul>
                                <% Pricing.pricing_types.each do |key, value| %>
                                    <li class="tab <%= 'is-active' if value == 0 %>" data-tab="<%= key %>" style="<%= 'display: none' if @gig.has_single_pricing && value != 0 %>">
                                        <a>
                                            <% if value == 0 %>
                                                ベーシック
                                            <% elsif value == 1 %>
                                                スタンダード
                                            <% else %>
                                                プレミアム
                                            <% end %>
                                        </a>
                                    </li>
                                <% end %>
                            </ul>
                        </div>

                        <div class="tabs-content">
                            <% @gig.pricings.each do |p| %>
                                <div class="tab-content" id="tab-<%= p.pricing_type %>" style="<%= 'display: none' if !p.basic? %>">
                                    <div class="card">
                                        <div class="card-content">
                                            <div class="media">
                                                <div class="media-content">
                                                    <strong><%= p.title %></strong>                                                                                                        
                                                </div>
                                                <div class="media-right">
                                                    <p class="title is-4"><%= number_to_currency(p.price) %></p>
                                                </div>                                                
                                            </div>
                                            <div class="content f-15">
                                                <p class="m-t-30"><%= p.description %></p>
                                                <p class="m-t-30">
                                                    <strong><i class="far fa-clock"></i> 期日: <%= p.delivery_time %></strong>                                                    
                                                </p>
                                            </div>
                                            <% 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: "button is-fullwidth is-danger" %>
                                            <% else %>
                                                <button class="button is-fullwidth is-danger" disabled>購入できません</button>  
                                            <% end %>                                            
                                        </div>
                                    </div>
                                </div>
                            <% end %>
                        </div>
                    </div>
                    
                    <!-- プロフィール -->
                    <div class="column">
                        <div class="card">
                            <div class="card-content is-horizontal-center is-flex">
                                <figure class="image is-256x256">
                                    <%= image_tag avatar_url(@gig.user), class: "is-rounded" %>
                                </figure>
                            </div>
                            <div class="card-content f-15">
                                <div class="content has-text-centered">
                                    <p class="title is-5"><%= @gig.user.full_name %></p>
                                    <button class="button is-black is-outlined is-fullwidth">メッセージを送る</button>
                                </div>
                                <article class="media">
                                    <div class="media-content">
                                        <i class="fas fa-user m-r-5"></i> アカウント登録日
                                    </div>
                                    <div class="media-right">
                                        <%= I18n.l(@gig.user.created_at, format: :full_date) %>
                                    </div>
                                </article>
                                <article class="media">
                                    <div class="media-content">
                                        <i class="fas fa-map-marker-alt m-r-5"></i> 出身地
                                    </div>
                                    <div class="media-right">
                                        <%= @gig.user.from %>
                                    </div>
                                </article>
                                <article class="media">
                                    <div class="media-content">
                                        <%= @gig.user.about %>
                                    </div>
                                </article>
                            </div>
                        </div>
                    </div>
                    
                </div>
            </div>
            
        </div>
    </div>
</section>

<script>
    BulmaCarousel.attach('#carousel-photo', {
        slidesToScroll: 1,
        slidesToShow: 1
    });
    $(document).ready(function() {
        $('#tabs li').on('click', function() {
            var type = $(this).data('tab');
            $('#tabs li').removeClass('is-active');
            $(this).addClass('is-active');
            $('.tab-content').hide();
            $('#tab-' + type).show();
        }) 
    })
</script>



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


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

<section class="section">
    <div class="container">

        <%= form_with model: [@gig, @gig.orders.new] do |f| %>
            <%= hidden_field_tag 'pricing_type', @pricing.pricing_type %>

            <div class="columns">

                <!-- 左側 -->
                <div class="column is-two-thirds">
                    <div class="columns is-multiline">
                        <div class="column is-full">
                            <div class="card">
                                <div class="card-content">
                                    <div class="content">
                                        <p class="title is-5">クレジットカード</p>
                                    </div>
                                    <hr>
                                    <div class="content">
                                        <% @stripe_customer.sources.each do |payment| %>
                                            <div class="control">
                                                <%= radio_button_tag 'payment', payment.id, checked: true %>
                                                <span class="m-l-10">
                                                    <%= payment.brand %><%= " **** **** **** " + payment.last4 %>
                                                </span>
                                            </div>
                                        <% end %>
                                    </div>
                                </div>
                                
                            </div>
                        </div>
                    </div>
                </div>


                <!-- 右側 -->
                <div class="column">
                    <div class="columns is-multiline">
                        <div class="column is-full">
                            <div class="card">
                                <div class="card-content">
                                    <div class="content">
                                        <p class="title is-5">内容</p>
                                    </div>
                                    <hr>
                                    <article class="media">
                                        <div class="media-content">
                                            <figure class="image is-4by3">
                                                <%= image_tag gig_cover(@gig) %>
                                            </figure>
                                        </div>
                                        <div class="media-right">
                                            <strong><%= @gig.title %> </strong>
                                        </div>
                                    </article>

                                    <article class="media">
                                        <div class="media-content">
                                            小計
                                        </div>
                                        <div class="media-right">
                                            <%= number_to_currency(@pricing.price) %>
                                        </div>
                                    </article>

                                    <article class="media">
                                        <div class="media-content">
                                            サービス料(10%)
                                        </div>
                                        <div class="media-right">
                                            <%= number_to_currency(@pricing.price * 0.1) %>
                                        </div>
                                    </article>

                                    <article class="media">
                                        <div class="media-content">
                                            合計
                                        </div>
                                        <div class="media-right">
                                            <%= number_to_currency(@pricing.price * 1.1) %>
                                        </div>
                                    </article>

                                    <article class="media">
                                        <div class="media-content">
                                            期日
                                        </div>
                                        <div class="media-right">
                                            <%= @pricing.delivery_time %></div>
                                    </article>
                                    
                                    <%= f.submit "購入する", class: "button is-fullwidth is-danger", data: {confirm: "本当によろしいですか?"} %>

                                </div>
                            </div>
                        
                        </div>
                    </div>
                </div>
            </div>
        <% end %>
    </div>
</section>



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


記述追加 app\controllers\orders_controller.rb
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



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


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


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

  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
    @categories = Category.all
  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, :description, :active, :category_id, :has_single_pricing, 
                                pricings_attributes: [:id, :title, :description, :delivery_time, :price, :pricing_type])
  end
  
end



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

merchant_id
merchant_id



ブラウザ確認
http://localhost:3000/gigs/4


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


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

購入する
購入する



内容を確認して購入ボタンを押します。

内容を確認して購入
内容を確認して購入



仕事を購入できました。

仕事購入
仕事購入



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

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



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

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



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


[39]Stripeコネクト << [ホームに戻る] >> [41]trestle