首页 > 解决方案 > 在请求中仅指定两个参数之一

问题描述

我正在我的网站上集成 Stripe 订阅,我想在两种不同的情况下使用相同的功能:新客户或现有客户。如果是新客户,我将传递 customer_email 参数,如果是现有客户,则传递 customer 参数。我试图在我通过两者的实际代码中实现这个逻辑(这将导致错误)。我需要删除一个的键和值。

const session = await stripe.checkout.sessions.create({
    payment_method_types: ["card"],
    customer: customer, //remove this line if new customer
    customer_email: customerEmail, //remove this line if existing customer
    line_items: [{price: planId, quantity: 1}],
    subscription_data: { 
    trial_period_days: 15
    },
    metadata: {'planId': planId,'product': product},
    success_url: `${domainURL}/index.html?product=${product}&session_id={CHECKOUT_SESSION_ID}`,
    cancel_url: `${domainURL}/product=${product}&index.html?session_id=cancelled` ,
    mode: 'subscription',
});

解决方法是复制代码,但我更喜欢尽可能减少代码。如何有条件地删除键:值对?

条件很简单:

if(customer!=''){
    //i have a customer id, so remove the customer_email key:value
}else{
    //new customer, remove the customer key:value
}

标签: javascript

解决方案


您可以将值转换为 undefined 以省略它。

const session = await stripe.checkout.sessions.create({
    payment_method_types: ["card"],
    customer: customerEmail ? undefined : customer, //remove this line if new customer
    customer_email: customerEmail || undefined, //remove this line if existing customer
    line_items: [{price: planId, quantity: 1}],
    subscription_data: { 
    trial_period_days: 15
    },
    metadata: {'planId': planId,'product': product},
    success_url: `${domainURL}/index.html?product=${product}&session_id={CHECKOUT_SESSION_ID}`,
    cancel_url: `${domainURL}/product=${product}&index.html?session_id=cancelled` ,
    mode: 'subscription',
});

另一种解决方案是有条件地扩展对象。

const session = await stripe.checkout.sessions.create({
    payment_method_types: ["card"],
    line_items: [{price: planId, quantity: 1}],
    subscription_data: { 
    trial_period_days: 15
    },
    metadata: {'planId': planId,'product': product},
    success_url: `${domainURL}/index.html?product=${product}&session_id={CHECKOUT_SESSION_ID}`,
    cancel_url: `${domainURL}/product=${product}&index.html?session_id=cancelled` ,
    mode: 'subscription',
    ...(customerEmail ? { customer_email: customerEmail } : { customer })
});

推荐阅读