Reputation: 135
I want Stripe to check if the customer already exists and if yes associate it to the checkout session.
class OrdersController < ApplicationController
@session = Stripe::Checkout::Session.create(
payment_method_types: ['card'],
shipping_address_collection: {
allowed_countries: ['GB']
},
customer_email: current_user.email,
line_items: line_items_order,
success_url: new_order_message_url(@order),
cancel_url: order_url(@order)
)
if @user.stripe_id != nil
Stripe::Customer.retrieve(@user.stripe_id)
@session.customer = customer.id
@session.customer_email =customer.email
else
customer = Stripe::Customer.create({
email: current_user.email,
name: current_user.username,
metadata: {
},
})
@user.stripe_id = customer.id
@user.save
end
@order.checkout_session_id = @session.id
@order.save
end
I checked with byebug and saw that Stripe::Customer.retrieve(@user.stripe_id) is working, Stripe API is able to find te right customer, but still create a new customer for each checkout session. I have read the documentation about the sessions objetc and found that about the customer attribute:
customer attribute: The ID of the customer for this Session. For Checkout Sessions in payment or subscription mode, Checkout will create a new customer object based on information provided during the payment flow unless an existing customer was provided when the Session was created.
What do I miss here?
Upvotes: 0
Views: 210
Reputation: 1193
The issue is that you are calling Stripe::Checkout::Session.create
without passing in the customer. As mentioned in the doc for customer, it should be passed when creating the session if you want to use an existing customer
customer string EXPANDABLE
The ID of the customer for this Session. For Checkout Sessions in payment or subscription mode, Checkout will create a new customer object based on information provided during the payment flow unless an existing customer was provided when the Session was created.
So just make sure you have the customer in the create method
@session = Stripe::Checkout::Session.create(
customer: customer.id
...
)
Upvotes: 1