cecileRx
cecileRx

Reputation: 135

How to update STRIPE CHECKOUT SESSION attributes RAILS

In rails 5, I create a stripe session in the show action of the order controller. I have also an update action which handles if the user chooses a delivery or a pick and collect for that order. In the update method, I try to update the stripe session by adding a shipping_address_collection attribute, so that the stripe checkout page displays a delivery address area. I manage to modify correctly the stripe session object, but not to save it. I have a :

NoMethodError (undefined method `save' for #<Stripe::Checkout::Session:0x00007fb60fe5f138>

Order controller:

def show
 @session = Stripe::Checkout::Session.create(
      payment_method_types: ['card'],

      customer: customer.id,

      line_items: line_items_order,

      success_url: order_messages_url(@order),
      cancel_url:  order_failure_message_url(@order)
      )

       @user.stripe_id = customer.id
       @user.save


   @order.checkout_session_id = @session.id
   @order.save
end

def update
 @order = Order.find(params[:id])
 @session = Stripe::Checkout::Session.retrieve("#{@order.checkout_session_id}")
 
    if @order.collect_address == nil && @order.shipping_zone != nil

    allowed_countries_item = {:allowed_countries => ['GB', 'BE', 'CZ', 'FR', 'DK', 'DE', 'EE', 'IE', 'HR', 'IT', 'CY', 'LV', 'LT', 'LU', 'HU', 'MT', 'NL', 'AT', 'PL', 'RO', 'SI', 'SK', 'FI', 'SE', 'IS', 'LI', 'NO', 'CH', 'PT', 'ES', 'ME', 'MK', 'AL', 'RS', 'TR', 'DZ', 'MA', 'IL']}
    @session[:shipping_address_collection] = allowed_countries_item
    @session.shipping_address_collection.save
    end

    @order.save
    redirect_to order_path(@order)
  end

Is there a way to do it or should I create 2 different sessions depending on the attributes I want ?

Upvotes: 1

Views: 2765

Answers (2)

costomato
costomato

Reputation: 112

In older versions of the Stripe API, updating a Checkout Session wasn't supported. However, with the newer versions, it is now possible to update an existing session.

To update a Checkout Session in Ruby, you can use the following code snippet:

Stripe::Checkout::Session.update(
  'cs_test_session_id',
  {metadata: {order_id: '6735'}},
)

This example updates the session with a new metadata field for the order_id. For more details on the parameters you can update and how to use the method, refer to the official Stripe documentation.

https://docs.stripe.com/api/checkout/sessions/update?lang=ruby

Make sure your Stripe gem is updated to the latest version to take advantage of this feature!

Upvotes: 0

Justin Michael
Justin Michael

Reputation: 6520

Stripe Checkout Sessions cannot be updated. The API only allows you to create, retrieve, and list them. You'll need to create a new Session instead of trying to update an existing one.

Upvotes: 6

Related Questions