Home > database >  use conditional to pass one or the other parameter to Stripe
use conditional to pass one or the other parameter to Stripe

Time:12-02

I am working on the CheckOutSession in Ruby on Rails, and now that I have the Checkout flow working, I'm working on it recognizing my users.

So a user has to be logged in via Devise before they can initiate a checkout session to Stripe. I had this part:

customer_email: current_user.email

in the code. Then once the user is successful in making a payment, I can capture the JSON from the success action and obtain the Customer ID that Stripe created, and store it as current_user.stripe_ip (I accidentally named the field ip in my dummy app here, it should be id)

customer: current_user.stripe_ip

The problem is: Stripe only allows you to pass customer_email, or customer to the checkout session. If it's a new user on my side, they don't have a Customer ID on the stripe side yet.

How can I do a conditional for that parameter? This is what I tried:

def create_checkout_session
        session = Stripe::Checkout::Session.create({
            [if current_user.stripe_ip.nil?
              customer_email: current_user.email
            else
              customer: current_user.stripe_ip
            end],
            line_items: [{
                price_data: {
                    currency: 'usd',
                    product_data: {
                    name: 'T-shirt S Black',
                },
                unit_amount: 2000
                },
                adjustable_quantity: {
                    enabled: true, 
                    maximum: 10
                },
                quantity: 1,
            }, 
            mode: 'payment',
            # These placeholder URLs will be replaced in a following step.
            success_url: "http://localhost:3000/success?session_id={CHECKOUT_SESSION_ID}",
            cancel_url: "http://localhost:3000/"
        })


        redirect_to session.url
    end

CodePudding user response:

You need to extract everything you send to .create and manipulate it before passing it back.

def create_checkout_session
  data = {
    line_items: [{
      price_data: {
        currency: 'usd',
        product_data: {
        name: 'T-shirt S Black',
      },
      unit_amount: 2000
      },
      adjustable_quantity: {
        enabled: true,
        maximum: 10
      },
      quantity: 1,
    }],
    mode: 'payment',
    # These placeholder URLs will be replaced in a following step.
    success_url: "http://localhost:3000/success?session_id={CHECKOUT_SESSION_ID}",
    cancel_url: "http://localhost:3000/"
  }

  if current_user.stripe_ip.nil?
    data[:customer_email] = current_user.email
  else
    data[:customer] = current_user.stripe_ip
  end

  session = Stripe::Checkout::Session.create(data)

  redirect_to session.url
end
  • Related