0

I use gem stripe_event with stripe webhook.

My initial code is:

config/initializers/stripe.rb

StripeEvent.configure do |events|
  events.subscribe 'checkout.session.completed', StripeCheckoutSessionService.new
end

app/services/stripe_checkout_session_service.rb

class StripeCheckoutSessionService
  def call(event)
    order = Order.find_by(checkout_session_id: event.data.object.id)
    order.update(state: "paid")
  end
end

My problem is that if order is nil, I have a 500 error, and I want to have a 422 error instead.

I try that :

app/services/stripe_checkout_session_service.rb

class StripeCheckoutSessionService
  def call(event)
    order = Order.find_by(checkout_session_id: event.data.object.id)
    if order
      order.update(state: "paid")
      head :accepted
    else
      head :unprocessable_entity
    end
  end
end

head is not recognize by the service, I try to return a string instead and return head directly in the block but I'm locked now...

Does anybody have any idea for me ?

Thibault
  • 131
  • 1
  • 5
  • When you say you want a different error code, do you mean you want your code to raise a 422 when it catches a 500? If so, something [like this](https://stackoverflow.com/a/38851247/100328) would work. – taintedzodiac Jan 14 '20 at 15:05
  • For now, if my code doesn't find order, I have a 500, but I want to improve my code to answer with a 422, which is more logic than a 500 – Thibault Jan 15 '20 at 08:53

1 Answers1

0

If you want to return a string, probably you can do this:

class StripeCheckoutSessionService
  def call(event)
    order = Order.find_by(checkout_session_id: event.data.object.id)
    if order
      order.update(state: "paid")
      "Successfully updated!" # or do this { status: 400, msg: 'success' }
    else
      "Error occurred!" # or do this { status: 422, msg: 'unprocessable_entity' }
    end
  end
end

Haven't tried this but should work.

Lalu
  • 732
  • 3
  • 8
  • 20