Shopware 6.6.10前端API获取购物车内容为空及令牌问题求助
解决Shopware购物车API返回lineItems为空及检查指定分类商品的方案
一、获取正确的sw-context-token
Shopware的购物车上下文与用户的sw-context-token绑定,硬写测试值无法获取有效购物车数据,正确获取方式有两种:
- 从浏览器Cookie读取:当前用户的有效token存储在名为
sw-context-token的Cookie中,直接读取该Cookie的值即可。 - 通过Storefront全局对象获取:在Shopware前端主题的JS代码里,调用
Shopware.Context.api.contextToken就能拿到当前生效的token,将其作为请求头的sw-context-token参数传入。
调用/checkout/cart接口时,确保请求头格式正确(注意键值对间的逗号分隔):
headers: { "Accept": "application/json", "sw-context-token": Shopware.Context.api.contextToken, "sw-access-key": "ENKJDSKFDNSJKFNEJ0815" }
二、排查lineItems为空的其他可能
若token正确但仍返回空数组,检查以下几点:
- 确认当前用户购物车中确实添加了商品(手动在前端页面添加后再测试接口)
- 检查请求域名与Shopware后台域名一致,避免跨域导致上下文丢失
- 验证
sw-access-key权限:该密钥需在Shopware后台「设置>系统>API访问」生成,确保拥有购物车相关接口的访问权限
三、检查购物车是否包含指定分类商品的方案
方案1:通过/checkout/cart接口处理
调用接口拿到lineItems后,遍历每个商品的分类信息进行判断:
// 假设接口返回数据为response const targetCategoryId = "你的目标分类ID"; const hasTargetCategory = response.lineItems.some(item => { return item.product?.categories?.some(category => category.id === targetCategoryId); }); // hasTargetCategory为true则表示购物车包含目标分类商品
方案2:使用Shopware内置购物车服务(推荐)
如果是在Storefront主题开发,直接用Shopware封装好的服务,无需手动编写Ajax请求:
async function checkCartHasTargetCategory() { const cart = await Shopware.Service('cartService').getCart(); const targetCategoryId = "你的目标分类ID"; return cart.lineItems.some(item => { return item.product.categories.some(category => category.id === targetCategoryId); }); }
方案3:自定义后端API端点
如果需要更高效的判断逻辑,可以在Shopware插件中创建自定义API路由,直接在后端查询购物车商品的分类关联,返回布尔结果,前端调用该自定义接口即可。
内容的提问来源于stack exchange,提问作者Shao Khan
相关产品推荐
相关产品推荐

