使用条件将一个或另一个参数传递给 Stripe

use conditional to pass one or the other parameter to Stripe

我正在 Rails 的 Ruby 中处理 CheckOutSession,现在我的结帐流程正在运行,我正在努力识别我的用户。

因此,用户必须先通过 Devise 登录,然后才能向 Stripe 发起结帐会话。我有这个部分:

customer_email: current_user.email

在代码中。然后一旦用户付款成功,我可以从成功操作中捕获 JSON 并获取 Stripe 创建的客户 ID,并将其存储为 current_user.stripe_ip (我不小心将字段命名为 ip我的虚拟应用程序在这里,它应该是 id)

customer: current_user.stripe_ip

问题是:Stripe 只允许您将 customer_emailcustomer 传递给结帐会话。如果是我这边的新用户,他们还没有 Customer ID 条带。

如何为该参数做一个条件?这是我试过的:

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

您需要提取发送给 .create 的所有内容,并在传回之前对其进行处理。

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