充电失败时检索 Stripe 充电 ID

Retrieve Stripe charge id upon failed charge

我正在尝试在充电失败时检索 Stripe 充电 ID,因此当 charge.failed 挂钩被触发时,我可以通过该 ID 检索我的记录。我尝试检查触发的异常,但找不到任何方法来获取它。这是我的代码:

  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

我终于使用元数据来存储我的记录 ID 和费用。所以我可以使用此元数据检索它。

charge = Stripe::Charge.create(
    {
        amount: 2000,
        currency: 'eur',
        source: token,
        description: 'Test',
        metadata: { record_id: 23 }
    }, { stripe_account: 'xxxxx' })

我遇到了同样的问题。在失败的充电尝试中检索充电 ID 的正确方法非常简单,但没有很好的记录。 Stripe 在错误中向您发送收费 ID:

这是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....