javascript - 在请求中仅指定两个参数之一
问题描述
我正在我的网站上集成 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
}
解决方案
您可以将值转换为 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 })
});
推荐阅读
- javascript - 如何使用“您确定要继续”模式在 Rails 中使用“是”和“否”按钮完成或停止保存按钮操作?
- angular - 数据 URL 很大时图像未呈现:net::ERR_CONNECTION_RESET
- python - 在 az 大小数组中随机将 x 值更改为 y
- django - 在单应用程序 Django 项目中使用 Celery
- uipath - 如何使用 ui path studio 抓取动态网页
- java - 避免初始化变量以使代码仍然有效
- android - **D/NetworkSecurityConfig:未指定网络安全配置,使用平台默认值**
- vue.js - 部署到生产 Netlify 的 Vue CLI 3 PWA 会出现 Workbox Error: bad-precaching-response ..._redirects?__WB_REVISION__...404
- mysql - 如何在 mysql 数据库中存储具有多个产品和每个产品数量的订单?
- jquery - 用户向上/向下滚动后添加类