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

WooCommerce REST API前端JS获取产品报401错误,求解决方案

问题分析与解决方案

你遇到的woocommerce_rest_cannot_view 401错误,核心原因有两个:一是前端直接用JWT方式调用WooCommerce API的配置逻辑不对,二是绝对不能在前端代码里硬写Consumer Key和Secret——这会直接泄露你的商店密钥,导致严重安全风险。

Postman和PHP调用正常是因为它们用的是OAuth1.0a认证(PHP的WooCommerce SDK会自动处理签名),但前端JS直接处理OAuth1.0a签名很麻烦,且同样存在密钥泄露问题。下面是两种可行的解决办法:


方法一:后端代理(推荐,安全可靠)

最稳妥的方式是在WordPress后端写一个自定义API端点,由后端去调用WooCommerce API,前端只需要调用这个自定义端点,完全避免密钥暴露。

步骤1:添加后端代理端点

在主题的functions.php或者自定义插件里添加以下代码:

add_action('rest_api_init', function () {
    register_rest_route('custom/v1', '/products', array(
        'methods' => 'GET',
        'callback' => 'custom_get_woocommerce_products',
        'permission_callback' => '__return_true', // 可根据需求调整权限,比如限制为登录用户
    ));
});

function custom_get_woocommerce_products($request) {
    // 引入WooCommerce API客户端
    require_once ABSPATH . 'wp-content/plugins/woocommerce/includes/class-wc-api-client.php';

    $consumer_key = '你的Consumer Key';
    $consumer_secret = '你的Consumer Secret';
    $store_url = get_site_url();

    $client = new WC_API_Client($store_url, $consumer_key, $consumer_secret, array(
        'wp_api' => true,
        'version' => 'wc/v3',
    ));

    try {
        $products = $client->products->get($request->get_params());
        return rest_ensure_response($products);
    } catch (WC_API_Client_Exception $e) {
        return new WP_Error('api_error', $e->getMessage(), array('status' => $e->getCode()));
    }
}

步骤2:前端调用自定义端点

把原来的JS代码改成调用这个后端代理:

<div id="products"></div>
<div id="error" class="error-message" style="display: none;">Erreur lors de la récupération des produits WooCommerce.</div>

<script>
    // 调用自定义后端端点
    fetch('/wp-json/custom/v1/products?per_page=5')
    .then(res => {
        if (!res.ok) {
            throw new Error('Erreur lors de la récupération des produits WooCommerce.');
        }
        return res.json();
    })
    .then(data => {
        data.forEach(product => {
            const html = `
                <div class="product">
                    <h3>${product.name}</h3>
                    <img src="${product.images[0].src}" />
                    <div>${product.price} €</div>
                </div>
            `;
            document.querySelector('#products').innerHTML += html;
        });
    })
    .catch(err => {
        console.log('Error:', err);
        document.querySelector('#error').style.display = 'block';
    });
</script>

方法二:修复JWT认证(不推荐,存在安全风险)

如果你坚持要用JWT方式,需要确保WooCommerce API能识别JWT Token,同时绝对不要在前端硬写密钥(可以通过登录用户的Token来获取权限,而不是用Consumer Key/Secret换JWT)。

步骤1:配置JWT插件

  • 安装并激活「JWT Authentication for WP REST API」插件
  • 在wp-config.php中添加JWT密钥:
define('JWT_AUTH_SECRET_KEY', '生成一个随机的安全密钥');
define('JWT_AUTH_CORS_ENABLE', true);

步骤2:让WooCommerce API接受JWT Token

添加钩子让WooCommerce REST API识别JWT认证:

add_filter('woocommerce_rest_check_permissions', function($permission, $context, $object_id, $post_type) {
    $user = wp_get_current_user();
    if ($user->exists() && current_user_can('view_woocommerce_reports')) { // 调整为合适的权限
        return true;
    }
    return $permission;
}, 10, 4);

步骤3:前端用登录用户的Token调用

前端需要用户登录后获取JWT Token(比如通过/wp-json/jwt-auth/v1/token用用户名密码登录),再用这个Token调用API,但这样只能获取该用户有权限查看的产品,且依然要注意Token的安全存储。


关键注意事项

  1. 绝对禁止在前端代码中硬编码Consumer Key和Secret,任何人都能通过浏览器开发者工具看到这些信息,进而完全控制你的WooCommerce商店。
  2. 确保你的网站启用了SSL(HTTPS),WooCommerce REST API要求必须用HTTPS(本地开发环境除外)。
  3. 检查权限:无论是用代理还是JWT,调用API的用户必须有view_woocommerce_products或者更高的权限。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.11 00:34:56