[Rails]PAY.JP로 등록된 신용카드로 상품 구매 기능 구현

17641 단어 RubyRails

개시하다


개인 앱, 신용카드 결제를 위해 PAY.JP를 가져왔습니다.
기능 실시에 관하여 비망록으로 기재되어 있다.
저번 보도
PAY.JP로 신용카드 등록/삭제 가능

전제 조건

  • Rails 5.2.4.2
  • Ruby 2.5.1
  • devise 사용
  • haml 사용
  • VScode 사용
  • 지난번까지 카드 정보 등록을 위해 카드 모형과 카드 컨트롤러를 제작했다.
    이번에 새로운 구매용 모델과 컨트롤러를 제작하여 구매 처리를 진행하였다.

    절차.

  • 모형의 제작
  • 표 작성
  • 컨트롤러 제작
  • 모델 생성하기


    이번에는 오더 모형을 제작한다.
    class Order < ApplicationRecord
      belongs_to :user
      has_many :products, through: :order_details
      has_many :order_details, dependent: :destroy
      belongs_to :card
      belongs_to :address
    
      enum postage: {burden: 0, free: 1}
      enum status: {支払済み: 0, 配送準備中: 1, 配送済み: 2}
    
      def add_items(cart)
        cart.line_items.target.each do |item|
          item.cart_id = nil
          line_items << item
        end
      end
    end
    
    전자상거래 사이트를 만들었기 때문에 카트 기능 등을 시행하는 관계에서 실례적인 방법 등을 정의했지만, 이번에는 구매 기능에 집중하다 보니 사랑을 끊었다.
    그래서to:카드의 한 줄은 사용하고 싶은 부분입니다.

    테이블 작성


    마이그레이션 파일은 다음과 같습니다.
    
    class CreateOrders < ActiveRecord::Migration[5.2]
      def change
        create_table :orders do |t|
          t.references :user, foreign_key: true
          t.references :address, foreign_key: true
          t.references :card, foreign_key: true
          t.references :product, foreign_key: true
          t.integer :quantity, null: false
          t.integer :status, default: 0, null: false
          t.integer :postage, default: 0, null: false
          t.integer :price, null: false
          t.timestamps
        end
      end
    end
    
    카드를 외부 열쇠로 설치하고 있습니다.

    컨트롤러 생성


    Order 컨트롤러를 만듭니다.
    이번에는 new와create 두 동작을 사용합니다.
    
    class OrdersController < ApplicationController
      before_action :set_cart
      before_action :user_signed_in
      before_action :set_user
      before_action :set_card
      before_action :set_address
    
      require "payjp"
    
      #注文入力画面
      def new
        @line_items = current_cart.line_items
        @cart = current_cart
        if @cart.line_items.empty?
          redirect_to current_cart, notice: "カートは空です"
          return
        end
        if @card.present?
          customer = Payjp::Customer.retrieve(@card.customer_id)
          default_card_information = customer.cards.retrieve(@card.card_id)
          @card_info = customer.cards.retrieve(@card.card_id)
          @exp_month = default_card_information.exp_month.to_s
          @exp_year = default_card_information.exp_year.to_s.slice(2,3)
          customer_card = customer.cards.retrieve(@card.card_id)
          @card_brand = customer_card.brand
          case @card_brand
          when "Visa"
            @card_src = "icon_visa.png"
          when "JCB"
            @card_src = "icon_jcb.png"
          when "MasterCard"
            @card_src = "icon_mastercard.png"
          when "American Express"
            @card_src = "icon_amex.png"
          when "Diners Club"
            @card_src = "icon_diners.png"
          when "Discover"
            @card_src = "icon_discover.png"
          end
          @order = Order.new
        end
      end
    
      #注文の登録
      def create
        unless user_signed_in?
          redirect_to cart_path(@current_cart), notice: "ログインしてください"
          return
        end
        @purchaseByCard = Payjp::Charge.create(
        amount: @cart.total_price,
        customer: @card.customer_id,
        currency: 'jpy',
        card: params['payjpToken']
        )
        @order = Order.new(order_params)
        @order.add_items(current_cart)
        if @purchaseByCard.save && @order.save!
          OrderDetail.create_items(@order, @cart.line_items)
          flash[:notice] = '注文が完了しました。マイページにて注文履歴の確認ができます。'
          redirect_to root_path
        else
          flash[:alert] = "注文の登録ができませんでした"
          redirect_to action: :new
        end
      end
    
      private
      def order_params
        params.permit(:user_id, :address_id, :card_id, :quantity, :price)
      end
    
      def set_user
        @user = current_user
      end
    
      def set_cart
        @cart = current_cart
      end
    
      def set_card
        @card = Card.find_by(user_id: current_user.id)
      end
    
      def set_address
        @address = Address.find_by(user_id: current_user.id)
      end
    
      def user_signed_in
        unless user_signed_in?
          redirect_to cart_path(@cart.id), alert: "レジに進むにはログインが必要です"
        end
      end
    end
    
    
    new 액션에서는 구매 확인 페이지 형식이 적용됐다.
    사용자가 로그인하지 않으면 원래 구매 확인 페이지에 접근할 수 없다.
    그리고 사용자는 내 페이지에 카드를 등록할 수 있다.
    구매 확인 페이지에서 처음으로 카드 등록을 하는 방법이라면 기사에서 제작된 카드 컨트롤러의 new 동작 실례 변수를 휴대할 수 있다.
    create 동작에는 다음과 같은 내용이 필요합니다.
    보기 쉽게 내용을 뽑고 있습니다.
    
    def create
      @purchaseByCard = Payjp::Charge.create(
      amount: @cart.total_price,
      customer: @card.customer_id,
      currency: 'jpy',
      card: params['payjpToken']
      )
      if @purchaseByCard.save
        flash[:notice] = '注文が完了しました。'
        redirect_to root_path
      else
        flash[:alert] = "注文の登録ができませんでした"
        redirect_to action: :new
      end
    end
    
    위 구매가 완료되면 PAYJP도 매출을 등록했다.

    좋은 웹페이지 즐겨찾기