Posted at

Rails5でクレジットカード決済サービス pay.jpのgemを使ってみた(定期課金)

More than 1 year has passed since last update.

サンプル: https://github.com/eccentricyan/payjp-ruby-sample

間違いがありましたら、ご指摘ください。mm

https://gyazo.com/eaebb328e473f2cf453f3c232455b2ca


sampleコードについて

支払いボタンの表示, userにcustomer_id(顧客ID)がある場合、再度支払い情報を入力しない


app/views/items/show.html.erb

<%= form_for(Order.new, url: item_orders_path(@item)) do |f| %>

<% if @user.customer_id %>
<%= f.submit "購読する" %>
<% else %>
<script src="https://checkout.pay.jp/" class="payjp-button" data-key="pk_test_0383a1b8f91e8a6e3ea0e2a9"></script>
<% end %>
<% end %>

顧客情報取得


app/controllers/orders_controller.rb

if customer_id = @user.customer_id

customer = Payjp::Customer.retrieve(id: customer_id)
else
customer = Payjp::Customer.create(card:payjp_token)
@user.customer_id = customer.id
@user.save!
end

プラン情報取得(プランIDはアイテムIDと購読期間(毎月month、毎年yearなど)で作成)

plans = customer.subscriptions.data.collect(&:plan).collect(&:id)

plan_id = "#{@item.id}_#{@item.interval}"
if plans.include?(plan_id)
plan = Payjp::Plan.retrieve(id: "#{@item.id}_#{@item.interval}")
else
plan = Payjp::Plan.create(id: "#{@item.id}_#{@item.interval}", amount: "#{@item.price}", interval: "#{@item.interval}", currency: "jpy")
end

定期課金

subscription = Payjp::Subscription.create(customer:customer.id, plan: plan.id)

ユーザー情報更新

update_role(subscription)

def update_role(subscription)
if subscription.status == "active"
@user.role << "#{@item.interval}_subscribed"
@user.role = @user.role.uniq
@user.save!
else
@user.role.delete("#{@item.interval}_subscribed")
@user.save!
end
end

ユーザー情報更新rake(whenever gem で毎日実行する)


lib/admin.rake

namespace :admin do

desc 'refresh user admin'
task :refresh => :environment do
Order.gt(current_period_end: Time.now).each do |order|
subscription = Payjp::Subscription.retrieve(id: order.subscription)
if subscription.status == "active"
order.current_period_end = Time.at(subscription.current_period_end)
order.save!
else
user = order.user
user.role.delete("#{order.item.id}_#{order.item.interval}")
user.save!
end
end
end
end

参考:

https://pay.jp/docs/api/#subscription-定期課金

http://blog.pay.jp/entry/2016/11/14/181023

https://github.com/payjp/payjp-ruby