meinert
meinert

Reputation: 80

NoMethodError `sources' for #<Stripe::Customer with Rails

When I try to receive data from Stripe customers I get the error undefined method 'sources'.

This is the code that I use:

    def update_payment 
    
    if !current_user.stripe_id
      customer = Stripe::Customer.create(
        email: current_user.email,
        source: params[:stripeToken]
      )
    else
      customer = Stripe::Customer.update(
        current_user.stripe_id,
        source: params[:stripeToken]
      )
    end


    if current_user.update(stripe_id: customer.id, stripe_last_4: customer.sources.data.first["last4"])
      flash[:notice] = "New card is saved"
    else
      flash[:alert] = "Invalid card"
    end
    redirect_to request.referrer
  rescue Stripe::CardError => e
    flash[:alert] = e.message
    redirect_to request.referrer
  end

The output from the customer variable isn't empty, so I don't understand how this error is possible.

Upvotes: 0

Views: 256

Answers (2)

Mira Py
Mira Py

Reputation: 161

The sources attribute is now optional. And for you to include sources as part of the response, you need to expand it. Add the sources field to Stripe Create Customer.

Example:

customer = Stripe::Customer.create(
 email: current_user.email,
 source: params[:stripeToken],
 expand: ['sources']
)

Upvotes: 0

Paul Asjes
Paul Asjes

Reputation: 5847

sources is no longer provided by default in the Stripe API since it's a deprecated integration path: https://stripe.com/docs/api/customers/object?lang=ruby#customer_object-sources

You need to explicitly state that you want the sources parameter to be returned by expanding it. E.g.

cust = Stripe::Customer.create({
  email: '[email protected]',
  source: 'tok_visa',
  expand: ['sources']
})

// cust.sources is now populated
puts cust.sources

Upvotes: 1

Related Questions