2

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?

Shiva
  • 11,485
  • 2
  • 67
  • 84
szier
  • 1,427
  • 3
  • 19
  • 32

2 Answers2

6

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

Ywain
  • 16,854
  • 4
  • 51
  • 67
2

For background info see Ywain's answer and
In ruby,

  # @return [Boolean]
  # #
  def is_valid?(coupon)
    return false unless coupon.present?

    coupon_retrieved = Stripe::Coupon.retrieve(coupon)
    coupon_retrieved.valid == true

  rescue => error
    puts "#{error.class} :: #{error.message}"
    false
  end
Community
  • 1
  • 1
Shiva
  • 11,485
  • 2
  • 67
  • 84