Search code examples
ruby-on-railsrubystripe-paymentscoupon

Checking if a Stripe Coupon is invalid


I am using the stripe gem for rails and I am trying to check if a user's coupon code is invalid. If the code is invalid, then the user is redirected to users/show.html.haml

Here is my code

if Stripe::Coupon.retrieve(current_user.coupon_code) == nil
  redirect_to user_path(current_user)
end

I thought that retrieving the code from Stripe and checking whether or not the value is nil would work but the error message I get is:

Stripe::InvalidRequestError in SubscribersController#new
No such coupon: *Whatever the invalid coupon name is (ex. "ASDF")*

Any idea as to what is going on here? I looked through the Stripe documentation for Ruby and didn't see any info on how to check if a code is invalid. Is there another way to check if a code is equal or not equal to nil?


Solution

  • If the coupon ID you pass to Stripe::Coupon.retrieve(...) does not exist, the request will fail and a Stripe::InvalidRequestError exception will be raised.

    Therefore, instead of comparing the result to nil, you need to place the call to Stripe::Coupon.retrieve(...) in a begin/rescue/end block to catch the Stripe::InvalidRequestError exception.

    You can find out more about error handling with Stripe's API here: https://stripe.com/docs/api#errors