1
votes

I am successfully charging a card with Stripe gem and the (mostly) boilerplate Stripe code (below). Upon successful charge, I am attempting to retrieve the charge ID so that I can inject it into a form and save it for later but am running into an error:

ActionView::Template::Error (undefined method `id' for #<Charge:0x000001065ab458>):

Which seems strange. Upon inspection of the charge object returned from my controller (and ostensibly the Stripe gem), there does not appear to be an 'id', just the token, amount and an empty errors array.

Any thoughts out there?

CONTROLLER CODE

class ChargesController < ApplicationController

  respond_to :js

  def create
    @charge = Charge.create(charge_params)
    respond_with(@charge)
  end

  private

  def charge_params
    params.require(:charge).permit(:stripeToken, :id)
  end
end

===============================

MODEL CODE

require 'active_model'

class Charge
  include ActiveModel::Model
  include CurrentCart

  class << self
    def create(params)
      new(params).tap(&:save)
    end
  end

  attr_reader :amount, :token, :id, :line_items_list

  def initialize(params)
    @amount = params[:amount].to_i
    @token = params[:stripeToken]
    Stripe.api_key = "sk_test_srlCaebNKtVDT7OPZIIb5jxV"

  end

  def save
    begin
      stripe_charge = Stripe::Charge.create(
        :amount => amount,
        :currency => "usd",
        :card => token,
        :description => 'Ties for all!'
      )

    rescue Stripe::CardError => e
      errors.add(:base, e.message)
    rescue => e
      errors.add(:base, "An error occurred with the payment processing: #{e.inspect}")
    end

    errors.empty?
  end

=============

1

1 Answers

1
votes

Your Charge service object isn't returning the stripe charge object.

In fact the method within which you create the Stripe charge only returns a boolean errors.empty?

The charge object you're examining is just an instance of your own charge class.

As an alternative save the Stripe charge in an instance variable...

@stripe_charge = Stripe::Charge.create(

And then write an accessor to retrieve it from your own Charge object.

def id 
  @stripe_charge.id
end