Context:
I am using Stripe checkout to accept one-time payment in rails. I have a charges controller as shown below. I was initially using stripe webhook to listen to charge.succeeded, but running into some issues due to the async nature of webhooks. My I have moved the business logic to the controller. If the customer charge is a success, then I save the customer and some other details to the db.
My question:
Is this check enough to ensure that a charge is successful ?
if charge["paid"] == true
The Stripe documentation for Stripe::Charge.create states, " Returns a charge object if the charge succeeded. Raises an error if something goes wrong. A common source of error is an invalid or expired card, or a valid card with insufficient available balance."
My ChargesController:
class ChargesController < ApplicationController
def new
end
def create
# Amount in cents
@amount = 100
temp_job_id = cookies[:temp_job_id]
customer_email = TempJobPost.find_by(id: temp_job_id).company[:email]
customer = Stripe::Customer.create(
:email => customer_email,
:card => params[:stripeToken]
)
charge = Stripe::Charge.create(
:customer => customer.id,
:amount => @amount,
:description => 'Rails Stripe customer',
:currency => 'usd',
:metadata => {"job_id"=> temp_job_id}
)
# TODO: charge.paid or charge["paid"]
if charge["paid"] == true
#Save customer to the db
end
# need to test this and refactor this using begin-->rescue--->end
rescue Stripe::CardError => e
flash[:error] = e.message
redirect_to charges_path
end
end
Stripe sends the payment_intent. succeeded event when payment is successful and the payment_intent. payment_failed event when payment isn't successful. When payment is unsuccessful, you can find more details by inspecting the PaymentIntent's last_payment_error property.
Stripe categorizes a transaction as "incomplete" when a "payment intent" was created, but your user never completed the payment. In other words, an incomplete transaction means the user went to the payment page, but never took action. When it comes to an incomplete transaction, the sale was simply not made.
Yes, that's all you need to do. If the charge succeeded, Stripe will return a Charge object, and you can check its paid
parameter. If the charge failed, we'd throw an exception.
Cheers, Larry
PS I work on Support at Stripe.
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