如何仅在customer_email存在时将其传入Stripe Checkout,不存在则不传该属性
解决方案
你当前的写法会在用户未登录时传递customer_email: null给Stripe,而非完全省略该属性,不符合需求。JavaScript完全支持动态给对象添加属性,下面是两种可行的实现方案:
方案1:对象展开运算符(最简洁)
利用ES6对象展开语法配合条件判断,仅在customerEmail有值时插入对应属性,同时已修正你原代码中locale: "auto"后多余的闭合大括号问题:
let customerEmail; const sessionConfig = { payment_method_types: ["card"], payment_method_options: { wechat_pay: { client: "web", }, }, line_items: [ { price: priceId, quantity: 1, description: priceName, }, ], mode: "payment", allow_promotion_codes: true, locale: "auto", // 仅在customerEmail存在时添加customer_email属性 ...(customerEmail && { customer_email: customerEmail }), success_url: "http://google.com/session_id={CHECKOUT_SESSION_ID}", cancel_url: "http://google.com/", }; const session = await stripe.checkout.sessions.create(sessionConfig); res.redirect(303, session.url);
原理说明:如果customerEmail为真值(存在有效邮箱),&&运算符会返回后面的{ customer_email: customerEmail }对象,展开后就会给配置对象添加对应属性;如果customerEmail为假值(未定义、空值等),&&返回假值,对象展开假值不会生成任何属性,相当于完全省略了customer_email字段。
方案2:显式条件判断(可读性更高)
适合不熟悉展开运算符的场景,先定义基础配置,再按需添加属性:
let customerEmail; // 先定义不带customer_email的基础配置 const sessionConfig = { payment_method_types: ["card"], payment_method_options: { wechat_pay: { client: "web", }, }, line_items: [ { price: priceId, quantity: 1, description: priceName, }, ], mode: "payment", allow_promotion_codes: true, locale: "auto", success_url: "http://google.com/session_id={CHECKOUT_SESSION_ID}", cancel_url: "http://google.com/", }; // 有值时才追加属性 if (customerEmail) { sessionConfig.customer_email = customerEmail; } const session = await stripe.checkout.sessions.create(sessionConfig); res.redirect(303, session.url);
两种方案都完全符合Stripe的接口规范,未登录时不会传递customer_email字段,Stripe会正常展示邮箱输入框给访客用户。
内容的提问来源于stack exchange,提问作者theruv
相关产品推荐
相关产品推荐

