So my Plan says Stripe::InvalidRequestError at /orders/26/payments
No such plan: The title of my plan.
This code should check if the the plan already exists and if not create it and subscribe the user to it. I thought this worked because it was working for the case where I already had a plan with the same ID and it said "Plan already exists". How can I prevent this Error from happening?
This is my code:
class PaymentsController < ApplicationController
before_action :set_order
def new
end
def create
@user = current_user
customer = Stripe::Customer.create(
source: params[:stripeToken],
email: params[:stripeEmail],
)
# Storing the customer.id in the customer_id field of user
@user.customer_id = customer.id
@plan = Stripe::Plan.retrieve(@order.service.title)
unless @plan
plan = Stripe::Plan.create(
:name => @order.service.title,
:id => @order.service.title,
:interval => "month",
:currency => @order.amount.currency,
:amount => @order.amount_pennies,
)
else
subscription = Stripe::Subscription.create(
:customer => @user.customer_id,
:plan => @order.service.title
)
end
@order.update(payment: plan.to_json, state: 'paid')
redirect_to order_path(@order)
rescue Stripe::CardError => e
flash[:error] = e.message
redirect_to new_order_payment_path(@order)
end
private
def set_order
@order = Order.where(state: 'pending').find(params[:order_id])
end
end
The documentation says that if you try to retrieve a plan that does not exist, it will raise an error. So you just need to catch the error:
begin
@plan = Stripe::Plan.retrieve(@order.service.title)
rescue
@plan = Stripe::Plan.create(...)
end
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With