Vue调用WooCommerce API获商品列表遇401,能否无需授权?
WooCommerce产品API无授权访问问题解答
- WordPress默认的
wp/v2/post接口能直接访问,是因为公开状态的文章默认允许匿名获取,这是WP的原生设置。 - WooCommerce的
wc/v2/products(或wc/v3/products)接口默认必须授权调用,这是电商数据安全的默认限制——避免产品库存、内部定价等敏感信息被随意获取,哪怕产品是公开在售状态。
无需授权获取公开商品数据的两种方法:
使用第三方公开产品API插件
部分第三方插件可以生成无需授权的公开产品接口,只返回标题、价格、图片等公开信息,适合前端直接调用。自定义WP REST API端点
自己写代码创建一个公开的自定义接口,只返回非敏感的公开产品数据。示例代码(添加到主题functions.php或自定义插件中):add_action('rest_api_init', function () { register_rest_route('custom/v1', '/products', array( 'methods' => 'GET', 'callback' => 'get_public_products', 'permission_callback' => '__return_true', // 允许匿名访问 )); }); function get_public_products() { $args = array( 'post_type' => 'product', 'posts_per_page' => -1, 'post_status' => 'publish', ); $products = get_posts($args); $public_products = array(); foreach ($products as $post) { $product = wc_get_product($post->ID); $public_products[] = array( 'id' => $post->ID, 'title' => $post->post_title, 'permalink' => get_permalink($post->ID), 'price' => $product->get_price(), 'image' => wp_get_attachment_url(get_post_thumbnail_id($post->ID)) ); } return $public_products; }前端调用时使用新接口地址:
https://some-example-website.org/wp-json/custom/v1/products,不需要任何授权就能获取整理后的公开产品数据。
注意:自定义接口时只返回必要的公开信息,不要泄露库存、成本价等敏感数据,避免安全风险。
内容的提问来源于stack exchange,提问作者Вадим radosvit
相关产品推荐
相关产品推荐

