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

PrestaShop 8.0.2 API创建购物车及添加商品失败求助

PrestaShop 8.0.2 API 创建购物车失败问题解决方案

问题场景

将WooCommerce店铺迁移至PrestaShop 8.0.2,本地环境为WampServer+VSCode,通过全权限API实现商品添加到购物车功能时,出现创建订单无选中商品、控制台报错的问题,具体错误:

  1. GET http://localhost/easy-dalles2/api/carts/undefined?ws_key=... 404 (未找到)
  2. 创建购物车时出错:Error: 创建购物车时API响应无效
  3. Error: 创建购物车时API响应无效

错误根源

  1. API响应解析错误:PrestaShop API返回XML格式,但代码未指定解析类型,导致无法正确提取购物车ID
  2. XML结构错误:添加商品时的<association>标签应为复数<associations>,不符合API规范
  3. 参数缺失:调用getCart时未传入cartId,导致请求URL出现undefined

修复方案

1. 修复购物车创建接口的响应解析

修改createPrestashopCart函数,指定XML解析并手动提取购物车ID:

async function createPrestashopCart() {
  try {
    const response = await $.ajax({
      url: `${prestashopApiBaseUrl}/carts?ws_key=${apiKey}`,
      method: "POST",
      processData: false,
      contentType: "application/xml; charset=UTF-8",
      data: `<prestashop><cart><id_customer>2</id_customer><id_currency>1</id_currency><id_lang>1</id_lang></cart></prestashop>`,
      dataType: 'xml' // 明确指定返回格式为XML
    });
    
    // 解析XML获取购物车ID
    const xmlDoc = new DOMParser().parseFromString(response, "text/xml");
    const cartId = xmlDoc.querySelector('cart > id').textContent;
    
    if (!cartId) {
      throw new Error("Réponse de l'API invalide lors de la création du panier");
    }
    return cartId;
  } catch (error) {
    console.error("Erreur lors de la création du panier : ", error);
    throw error;
  }
}

2. 修正添加商品的XML标签

修改addProductToPrestashopCart函数中的XML结构,将<association>改为<associations>:

async function addProductToPrestashopCart(cartId, productId, quantity) {
  try {
    await $.ajax({
      url: `${prestashopApiBaseUrl}/carts/${cartId}?ws_key=${apiKey}`,
      method: "PUT",
      processData: false,
      contentType: "application/xml; charset=UTF-8",
      data: `<prestashop><cart><id>${cartId}</id><associations><cart_rows><cart_row><id_product>${productId}</id_product><quantity>${quantity}</quantity></cart_row></cart_rows></associations></cart></prestashop>`,
      dataType: 'xml'
    });
  } catch (error) {
    console.error("Erreur lors de l'ajout du produit au panier : ", error);
    throw error;
  }
}

3. 修复getCart的参数传递

在调用getCart时传入创建好的cartId:

// 原代码 await getCart(); 替换为:
await getCart(cartId);

4. 基础配置验证

  • 确认prestashopApiBaseUrl和apiKey配置正确,API密钥拥有carts、products模块的全权限
  • 直接访问http://localhost/easy-dalles2/api/carts?ws_key=你的密钥,验证API路由可正常返回XML数据
  • 检查id_customer=2的用户在PrestaShop后台存在且状态正常

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.30 22:06:01