1
2

More than 3 years have passed since last update.

[rails]gem 'payjp'の実装手順

Last updated at Posted at 2020-09-08

1.gem 'payjp'をインストールする

2.orderコントローラー作成記述する

  def index
    @order = Order.new
  end

  def create
    @order = Order.new(price: order_params[:price])
    #@orderにprice="1000"値段が入る
    if @order.valid?
      # 保存するための条件(空欄じゃない)をクリアすれば支払、データー保存される
      pay_item#支払をする
      @order.save#データーを保存する
      return redirect_to root_path
    else
      render 'index'
    end
  end

  private
  def order_params
    params.permit(:price, :token)#データー保存を許可したカラム
  end
  def pay_item
    Payjp.api_key = ENV["PAYJP_SECRET_KEY"]  # PAY.JPテスト秘密鍵
    Payjp::Charge.create(
      amount: order_params[:price],  # 商品の値段
      card: order_params[:token],    # カードトークン
      currency:'jpy'                 # 通貨の種類(日本円)
    )
  end
end

・token(カード情報)はorderテーブルに保存しない。
なので@orderにはprice: order_params[:price]で
ユーザーが入力したprice値段の情報が代入される

・pay_itemにより支払完了し
@order.saveでprice:1000、値段の情報をテーブルに保存する

3モデルにバリデーションの情報を記述する

class Order < ApplicationRecord
validates :price, presence: true
end

・バリデーションとは?データーをテーブルに保存する際の条件

・今回はpriceの入力欄が空の状態で送信すると
データーを保存させないようにしている。

・token(クレジットカード情報)はテーブルに保存しないので、バリデーション
保存の条件を記述しない。

1
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
2