Prezes Łukasz
Prezes Łukasz

Reputation: 968

Integrate Stripe payments with create method

I want to properly integrate stripe charges with my create method in controller.

   def create
    @individual_training = IndividualTraining.new(individual_training_params)
    Stripe.api_key = ENV['STRIPE_SECRET_KEY']
    token = params[:stripeToken]
    begin
      charge = Stripe::Charge.create(
        amount: (@individual_training.training_cost.cost * 100).floor,
        currency: 'pln',
        card: token
      )
    rescue Stripe::CardError => e
      flash[:danger] = e.message
      render :new
    end

    if @individual_training.save
      redirect_to :back, notice: 'Pomyślnie dodano.'
    else
      render :new
    end
  end

The issue is with properly validation whole form. Beside Stripe fields I have also fields designed for @individual_training. When Stripe doesn't have any error, but @individual_training has, stripe registered payment. I want record stripe charges when @individual_training.save is true and conversely.

If data are correct in first part(stripe fields) and second part of the form(@individual_training fields), then a payment should be registered and @individual_training.save.

I hope that clearly explain the problem.

Upvotes: 0

Views: 185

Answers (1)

Pavel Bulanov
Pavel Bulanov

Reputation: 953

Based on what you wrote in comments, following should do the thing for you

 def create
    @individual_training = IndividualTraining.new(individual_training_params)
    ..
    if @individual_training.valid? # run validation, ensure it's ok, but not yet save
      begin
        charge = Stripe::Charge.create(..) # if there is exception rescue block is called
        ...
        # unless you modified individual_training following save will be positive
        if !charge.errors? && @individual_training.save # save should be true as you checked valid? before
          redirect_to :back, notice: 'error'
        else
          render :new # this is if charge has errors
        end          
      rescue Stripe::CardError => e
        flash[:danger] = e.message
        render :new
      end     
    else # this happens if individual_training  is not valid
      render :new
    end
  end

The code for charge.errors? should be changed to actual check of Stripe operation result.

Upvotes: 1

Related Questions