Reputation: 12072
I cannot seem to charge a card then create a customer on the fly in Rails 4.
def charge
token = params[:stripeToken] # can only be used once.
begin
charge = Stripe::Charge.create(
:amount => 5000,
:currency => "gbp",
:source => token,
:description => "Example charge"
)
rescue Stripe::CardError => e
# The card has been declined
end
if current_user.stripeid == nil
customer = Stripe::Customer.create(card: token, ...)
current_user.stripeid = customer.id
current_user.save
end
end
I have looked at this but there is no such thing as token.id
as token
is just a String
.
Upvotes: 1
Views: 3965
Reputation: 11235
It looks like you're using the token in two locations:
charge = Stripe::Charge.create(
:amount => 5000,
:currency => "gbp",
:source => token,
:description => "Example charge"
)
And also here:
customer = Stripe::Customer.create(card: token, ...)
In fact, creating a Stripe charge from a token should also create a customer along with the card, if it didn't already exist. Your step of creating a customer is unnecessary. Therefore, just fetch the Stripe customer from the source:
current_user.update_attribute(:stripeid, charge.source.customer)
Relevant Stripe documentation: https://stripe.com/docs/api/ruby#create_charge
EDIT
If you want to have more control over the charge process, create each object independently:
customer = Stripe::Customer.create(
description: "Example customer",
email: current_user.email
)
card = customer.sources.create(
source: "<stripe token>"
customer: customer.id
)
Stripe::Charge.create(
amount: 5000,
currency: "gbp",
source: card.id,
customer: customer.id
)
Upvotes: 0