There are many articles on Payjp payment methods, but I will write them because there was no default_card setting method. Others have written about tokenization, so I will omit the description of javascript.
ruby 2.6.5 Rails 6.0.3.3
Please make up for the lack of explanation here.
reference: https://pay.jp/docs/api/#customer-%E9%A1%A7%E5%AE%A2 https://pay.jp/docs/customer
In my case, I have saved the following columns in the Card model.
id | user_id | card_token | customer_token |
---|---|---|---|
integer | tok_~ | cus_~ |
Card_token (tok_ ~) is required to create Customer. Pass the token received by javascript to the controller and write the following.
cards_controller.rb
def create
# card_Check if the token is correct
if params[:card_token] == nil
redirect_to new_user_card_path
return
end
#User customer_If token exists
if Card.find_by(user_id: current_user.id)
card = current_user.card
customer = Payjp::Customer.retrieve(card[0][:customer_token])
customer.cards.create(
card: params[:card_token]
)
else
#User is customer_If token does not exist
customer = Payjp::Customer.create(
description: "test",
card: params[:card_token],)
end
#Save to card table
card = Card.new(
user_id: current_user.id,
card_token: params[:card_token],
customer_token: customer.id)
end
Define the array @ cards
and put the card information based on customer_token
ruby:card.controller.rb
cards = Card.where(user_id: current_user.id)
@cards = []
cards.each do |card|
@customer = Payjp::Customer.retrieve(card.customer_token)
@cards << @customer.cards
end
Create a form so that the user can select a card and receive the index selected by the argument "i".
In the view, you can display the card information for @ cards
with each_with_index by the following description.
ruby:select.html.erb
<%= form_with url: set_default_card_path, method: :post, local: true do |f| %>
<% @cards.each_with_index do |card, i| %>
<%=f.radio_button :selected, :"#{i}" ,id: "check_card", checked: (card.data[i] [:id] == @customer[:default_card]) %>
<%= "**** **** **** #{ + card.data[i][:last4]}" %>
<%= "#{card.data[i][:exp_year]}Year#{+ card.data[i][:exp_month]}Moon" %>
<% end %>
<%= f.submit "Proceed to the next" %>
<% end %>
I am using radio_button in form_with of select.html.erb and receiving the value of # {i} in params [: selected].
Assign to [: default_card] of @ customer
and complete with @ customer.save.
cards_controller
def set_default_card
cards = Card.where(user_id: current_user.id)
@cards = []
cards.each do |card|
@customer = Payjp::Customer.retrieve(card.customer_token)
@cards << @customer.cards
end
@customer = Payjp::Customer.retrieve(card.customer_token)
index = params[:selected].to_i
@customer[:default_card] = @cards[0].data[index][:id]
@customer.save
end
There may be a simpler description, but it can be implemented. After that, please arrange each one.