You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

适配Stripe新Price API更新checkout_session的问题求助

解决Stripe Checkout Session创建时的Price API迁移问题

错误原因

Stripe API版本更新后,不再允许在line_items中直接传入amount、currency、name等字段,必须通过price或price_data来定义商品的价格信息,这两个参数的适用场景不同:


1. 使用price参数(推荐生产环境使用)

这个参数适用于已经在Stripe后台创建好的商品/价格。你需要先在Stripe Dashboard中为每个商品创建对应的Price对象,获取其ID后直接传入即可。

代码修改示例

替换原有的validateCartItems逻辑,生成符合新API格式的line_items:

// 假设你的products数组中每个产品都存储了Stripe后台生成的Price ID(字段名比如stripePriceId)
const line_items = cartItems.map(item => {
  const matchedProduct = products.find(p => p.id === item.id);
  if (!matchedProduct?.stripePriceId) {
    throw new Error(`商品${item.id}未配置Stripe Price ID`);
  }
  return {
    price: matchedProduct.stripePriceId,
    quantity: item.quantity
  };
});

2. 使用price_data参数(适合动态定价/临时商品)

如果需要在代码中动态定义商品名称、价格、描述,可以用这个参数。它需要你传入商品基础信息和定价细节:

代码修改示例

const line_items = cartItems.map(item => {
  const matchedProduct = products.find(p => p.id === item.id);
  return {
    price_data: {
      currency: 'myr', // 根据业务需求修改货币代码(比如USD、CNY)
      product_data: {
        name: matchedProduct.name,
        description: matchedProduct.description,
        images: [matchedProduct.imageUrl] // 可选:商品图片URL
      },
      unit_amount: matchedProduct.price * 100, // 注意:必须传入最小货币单位(比如马币分、美元美分)
    },
    quantity: item.quantity
  };
});

完整修改后的函数示例(以price参数为例)

async function createCheckoutSession(req, res) {
  try {
    const cartItems = req.body;
    // 生成符合新API要求的line_items
    const line_items = cartItems.map(item => {
      const matchedProduct = products.find(p => p.id === item.id);
      if (!matchedProduct?.stripePriceId) {
        throw new Error(`商品${item.id}未配置Stripe Price ID`);
      }
      return {
        price: matchedProduct.stripePriceId,
        quantity: item.quantity
      };
    });

    const origin = process.env.NODE_ENV === 'production' ? req.headers.origin : 'http://localhost:3000'

    const params = {
      submit_type: "pay",
      payment_method_types: ['card'],
      billing_address_collection: 'auto',
      shipping_address_collection: {
        allowed_countries: ["MY", "US", "CA"]
      },
      line_items,
      success_url: `${origin}/result?session_id={CHECKOUT_SESSION_ID}`,
      cancel_url: origin,
      mode: 'payment'
    }

    const checkoutSession = await stripe.checkout.sessions.create(params);

    res.status(200).json(checkoutSession)
  } catch (error) {
    res.status(500).json({ statusCode: 500, message: error.message });
  }
}

注意事项

  • 使用price_data时,unit_amount必须是最小货币单位(例如10马币要传入1000,代表1000分)。
  • 优先使用price参数,便于在Stripe后台统一管理商品价格、查看订单关联的商品信息,后续调整价格也无需修改代码。
  • 确保你的Stripe Node.js SDK是最新版本,避免因版本兼容导致的其他问题。

内容的提问来源于stack exchange,提问作者Rachel

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.10 15:05:33