Allow using saved cards at checkout

This commit is contained in:
Matt-Yorkley
2022-01-24 22:28:45 +00:00
parent 8c9ca3b0c3
commit b5a1d9ebef
4 changed files with 45 additions and 5 deletions

View File

@@ -112,7 +112,7 @@ class SplitCheckoutController < ::BaseController
end
def order_params
@order_params ||= Checkout::Params.new(@order, params).call
@order_params ||= Checkout::Params.new(@order, params, spree_current_user).call
end
def redirect_to_step

View File

@@ -2,9 +2,10 @@
module Checkout
class Params
def initialize(order, params)
def initialize(order, params, current_user)
@params = params
@order = order
@current_user = current_user
end
def call
@@ -13,17 +14,18 @@ module Checkout
apply_strong_parameters
set_address_details
set_payment_amount
set_existing_card
@order_params
end
private
attr_reader :params, :order
attr_reader :params, :order, :current_user
def apply_strong_parameters
@order_params = params.require(:order).permit(
:email, :shipping_method_id, :special_instructions, :existing_card_id,
:email, :shipping_method_id, :special_instructions,
:save_bill_address, :save_ship_address,
bill_address_attributes: ::PermittedAttributes::Address.attributes,
ship_address_attributes: ::PermittedAttributes::Address.attributes,
@@ -50,6 +52,22 @@ module Checkout
@order_params[:payments_attributes].first[:amount] = order.total
end
def set_existing_card
return unless existing_card_selected?
card = Spree::CreditCard.find(params[:existing_card_id])
if card.user_id.blank? || card.user_id != current_user&.id
raise Spree::Core::GatewayError, I18n.t(:invalid_credit_card)
end
@order_params[:payments_attributes].first[:source] = card
end
def existing_card_selected?
@order_params[:payments_attributes] && params[:existing_card_id].present?
end
def addresses_present?
@order_params[:ship_address_attributes] && @order_params[:bill_address_attributes]
end

View File

@@ -3,7 +3,7 @@
.checkout-input
%label
= t('split_checkout.step2.form.stripe.use_saved_card')
= select_tag :existing_card,
= select_tag :existing_card_id,
options_for_select(stripe_card_options(@saved_credit_cards) + [[t('split_checkout.step2.form.stripe.create_new_card'), ""]], @selected_card),
{ "data-action": "change->stripe-cards#onSelectCard", "data-stripe-cards-target": "select" }

View File

@@ -141,6 +141,28 @@ describe SplitCheckoutController, type: :controller do
expect(order.reload.state).to eq "confirmation"
end
end
context "with a saved credit card" do
let!(:saved_card) { create(:stored_credit_card, user: user) }
let(:checkout_params) do
{
order: {
payments_attributes: [
{ payment_method_id: payment_method.id }
]
},
existing_card_id: saved_card.id
}
end
it "updates and redirects to payment step" do
put :update, params: params
expect(response).to redirect_to checkout_step_path(:summary)
expect(order.reload.state).to eq "confirmation"
expect(order.payments.first.source.id).to eq saved_card.id
end
end
end
context "summary step" do