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

使用WooCommerce API实现Python添加商品至购物车的问题排查

解决WooCommerce API调用cart/items返回404的问题

核心问题原因

你调用的cart/items路由不属于WooCommerce标准REST API的端点:

  • WooCommerce的Admin REST API(wp-json/wc/v3/前缀)主要用于后台管理操作(如商品、订单管理),不支持前端购物车的直接操作。
  • 前端用户购物车的交互需要用专门的Store API,它是WooCommerce为前端场景设计的API,路径前缀为wp-json/wc/store/v1/。

解决方案:改用Store API添加商品到购物车

前端JavaScript实现(直接在网页中调用)

// 点击预约按钮时触发的函数
function reserveImage() {
  fetch('/wp-json/wc/store/v1/cart/add-item', {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json',
    },
    body: JSON.stringify({
      id: 17,       // 目标商品ID
      quantity: 1   // 购买数量
    })
  })
  .then(response => response.json())
  .then(data => {
    if (data.error) {
      console.error('添加失败:', data.error.message);
      alert('预约失败,请稍后重试');
    } else {
      console.log('商品已加入购物车:', data);
      // 可跳转到结算页,或显示支付引导
      window.location.href = '/checkout/';
    }
  })
  .catch(error => {
    console.error('请求错误:', error);
    alert('网络异常,请检查连接');
  });
}

后端PHP实现(如果是在WordPress主题/插件中调用)

function add_to_cart_programmatically() {
  // 传递会话Cookie,确保购物车关联当前用户
  $cookies = $_COOKIE;
  
  $response = wp_remote_post( home_url('/wp-json/wc/store/v1/cart/add-item'), array(
    'headers' => array(
      'Content-Type' => 'application/json',
    ),
    'body' => json_encode(array(
      'id' => 17,
      'quantity' => 1
    )),
    'cookies' => $cookies
  ));

  if (is_wp_error($response)) {
    return $response->get_error_message();
  }

  $data = json_decode(wp_remote_retrieve_body($response), true);
  return $data;
}

后续开发建议

1. 支付完成后标记图片为已预约

通过WooCommerce的订单完成钩子,自动更新图片状态:

add_action('woocommerce_order_status_completed', 'mark_image_reserved_after_payment');
function mark_image_reserved_after_payment($order_id) {
  $order = wc_get_order($order_id);
  
  // 遍历订单商品,检查是否包含目标商品ID=17
  foreach ($order->get_items() as $item) {
    if ($item->get_product_id() === 17) {
      // 这里根据你的图片存储逻辑,更新对应图片的预约状态
      // 示例:假设图片的ID存在订单自定义字段'image_id'中
      $image_id = $order->get_meta('image_id');
      update_post_meta($image_id, 'is_reserved', 'yes');
      break;
    }
  }
}

2. 已预约后显示图片上传入口

在图片详情页或用户账户页面,通过判断图片的is_reserved元字段,动态显示上传表单:

// 示例:在模板中判断并显示上传按钮
$image_id = get_the_ID();
if (get_post_meta($image_id, 'is_reserved', true) === 'yes') {
  echo '<form action="' . esc_url(admin_url('admin-post.php')) . '" method="post" enctype="multipart/form-data">';
  echo '<input type="file" name="uploaded_image" required>';
  echo '<input type="hidden" name="action" value="handle_image_upload">';
  echo '<input type="hidden" name="image_id" value="' . $image_id . '">';
  echo '<button type="submit">上传图片</button>';
  echo '</form>';
}

注意事项

  • Store API要求WooCommerce版本≥5.0,建议使用最新稳定版。
  • 未登录用户的购物车依赖WordPress会话Cookie,确保网站Cookie功能正常。
  • 调用API时需处理错误场景(如商品库存不足、商品不存在等)。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.17 15:55:26