4

I am trying to retrieve the Stripe charge id upon a failed charge, so I can retrieve my record thanks to that id when the charge.failed hook is fired. I tried inspect the exception fired but I cannot find any way to get it. Here is my code :

  def charge
    token = params[:stripeToken]
    type = params[:stripeTokenType]
    metadata = {}
    record = Record.new(amount: Random.rand(2000), valid: false)
    charge = nil
    begin
      charge = Stripe::Charge.create(
          {
              amount: 2000,
              currency: 'eur',
              source: token,
              description: 'Test',
              metadata: metadata
          }, { stripe_account: 'xxxxx' })
      record.stripe_charge_id
      flash[:notice] = 'Transaction validée'
    rescue Exception => e
      record.error = e.code
      flash[:error] = 'Erreur de paiement'
    end
    flash[:error] = 'Erreur de paiement' unless record.save || flash[:error]
    redirect_to :stripe_test
  end
Aeradriel
  • 1,224
  • 14
  • 36

2 Answers2

0

I finally used the meta data to store my record id with the charge. So I am able to retrieve it using this metadata.

charge = Stripe::Charge.create(
    {
        amount: 2000,
        currency: 'eur',
        source: token,
        description: 'Test',
        metadata: { record_id: 23 }
    }, { stripe_account: 'xxxxx' })
Aeradriel
  • 1,224
  • 14
  • 36
0

I had the same issue. The proper way to retrieve the charge id upon failed charge attempt is quit simple but not exactly well documented. Stripe sends you the charge id within the error:

this is python!

try:
    # make the charge
except stripe.error.CardError as e:
    # Since it's a decline, stripe.error.CardError will be caught
    body = e.json_body
    err = body.get('error', {})
    charge_id = err.get('charge') # this will return ch_1EPVmxKT>DPET....
Fanckush
  • 143
  • 3
  • 10
  • This doesn't appear to be the case for Ruby unfortunately. e.json_body[:error] # => {:code=>"card_declined", :decline_code=>"insufficient_funds", :doc_url=>"https://stripe.com/docs/error-codes/card-declined", :message=>"Your card has insufficient funds.", :param=>"", :type=>"card_error"} – daveharris Feb 16 '21 at 02:30