共有すること
開発環境
Ruby 2.4.1
Rails 5.1.4
コード例
command
rails new sample
cd sample
rails g controller home top
congfig/routes.rb
Rails.application.routes.draw do
get 'home/top'
post '/pay' => "home#pay"
end
home_controller.rb
class HomeController < ApplicationController
protect_from_forgery except: :pay
def top
end
def pay
Payjp.api_key = 'テスト用秘密鍵'
token =Payjp::Token.create(
:card => {
:number => params[:number],
:cvc => params[:cvc],
:exp_month => params[:exp_month],
:exp_year => params[:exp_year]
}
)
charge = Payjp::Charge.create(
:amount => 10000,
:card => token.id,
:currency => 'jpy',
)
redirect_to "/home/top"
flash[:notice] = "支払い完了"
end
end
views/home/top.html.erb
<h1>PAY.JPを利用したクレジットカード決済の実装</h1>
<% if flash[:notice] %>
<%= flash[:notice] %>
<% end %>
<%= form_tag("/pay",method:"post",datakey:"テスト用公開鍵") do %>
<input type="text" name="number" maxlength="16" placeholder="カード番号"><br>
<input type="text" name="cvc" maxlength="3" placeholder="CVC"><br>
<input type="text" name="exp_month" maxlength="2" placeholder="月">
<input type="text" name="exp_year" maxlength="4" placeholder="西暦(4桁)"><br>
<input type="submit">
<% end %>
実行結果
command
rails s
http://localhost:3000/home/top にアクセス
↓
PAY.JPで指定されたクレジットカード情報(ダミー)を入力
↓
「送信」ボタンを押す
↓
flash[:notice]が表示され、PAY.JPのダッシュボードに売り上げ情報が反映される。
参考資料
PAY.JP https://pay.jp/