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

Stripe结算会话异常:items属性未定义且显示全部商品

问题修复方案

1. 解决TypeError: Cannot read properties of undefined (reading 'items')报错

这个错误的核心原因是Express服务器没配置JSON请求体解析中间件,导致req.body是undefined,自然读不到items字段。

直接在server.js里加一行中间件配置,放在app.use(express.static('public'));后面:

app.use(express.static('public'));
// 新增:解析JSON格式的请求体
app.use(express.json());

2. 修复Stripe会话显示全部商品的问题

当前checkout.js里硬写了所有商品的固定数组,每次请求都会把全部商品发过去,肯定显示所有商品。得改成读取用户实际选中的购物车数据。

假设你的页面里有购物车元素,比如每个商品项带data-item-id属性和数量输入框,修改checkout.js的请求体部分:

button.addEventListener("click", () => {
  // 动态获取用户选中的购物车商品(示例逻辑,可根据你的实际页面结构调整)
  const cartItems = Array.from(document.querySelectorAll('.cart-item')).map(item => {
    const id = parseInt(item.dataset.itemId);
    const quantity = parseInt(item.querySelector('.quantity-input').value);
    return { id, quantity };
  }).filter(item => item.quantity > 0); // 过滤掉数量为0的商品

  fetch('/create-checkout-session', {
    method: 'POST',
    headers: {
      "Content-Type": "application/json",
    },
    body: JSON.stringify({ items: cartItems }), // 用实际购物车数据替换硬编码数组
  })
  // 后续逻辑保持不变
  .then(res => {
    if (res.ok) return res.json()
    return res.json().then(json => Promise.reject(json))
  })
  .then(({ url }) => {
    window.location = url
  })
  .catch(e => {
    console.error(e.error)
  })
})

3. 修复Stripe价格配置的错误

server.js里的line_items配置有问题:你把Stripe的priceId填到了unit_amount字段,但unit_amount需要的是以分为单位的金额数值,而priceId是Stripe后台创建的价格对象ID。正确用法是直接引用这个priceId,不用自己构建price_data。

修改server.js里的line_items部分:

line_items: req.body.items.map(item => {
  const storeItem = itemToPriceMap.get(item.id);
  return {
    price: storeItem.priceId, // 直接用Stripe的priceId
    quantity: item.quantity,
  };
}),

如果确实要自定义价格(不用Stripe后台的price对象),那unit_amount得填正确的分数值,比如2999代表29.99美元,结构改成这样:

price_data: {
  currency: 'usd',
  product_data: {
    name: storeItem.name
  },
  unit_amount: 2999, // 以分为单位的金额
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.13 20:25:25