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

Vue3+WooCommerce项目:如何在PHP文件中隐藏API密钥?

解决方案:后端代理隐藏WooCommerce API密钥

1. 正确在wp-config.php中定义密钥

先确认常量定义格式,放在全局作用域(和JWT定义位置一致即可):

// wp-config.php 中添加
define('WC_CONSUMER_KEY', '你的consumer_key');
define('WC_CONSUMER_SECRET', '你的secret_key');

注意:PHP常量仅在服务器端生效,前端无法直接读取,必须通过后端接口中转使用。

2. 搭建后端代理接口

方式一:自定义PHP代理文件

在WordPress主题目录(如wp-content/themes/你的主题/)新建wc-api-proxy.php,代码如下:

<?php
require_once('../../../wp-load.php');

// 限制请求方法(按需调整)
if (!in_array($_SERVER['REQUEST_METHOD'], ['GET', 'POST', 'DELETE'])) {
    wp_send_json_error(['msg' => '不支持该请求方法'], 405);
}

// 获取前端传递的API路径和参数
$api_path = isset($_REQUEST['api_path']) ? sanitize_text_field($_REQUEST['api_path']) : '';
$api_params = $_REQUEST;
unset($api_params['api_path']);

if (empty($api_path)) {
    wp_send_json_error(['msg' => '缺少API路径'], 400);
}

// 构造WooCommerce API请求
$wc_api_url = get_site_url() . '/wp-json/wc/v3/' . ltrim($api_path, '/');
$args = [
    'headers' => [
        'Authorization' => 'Basic ' . base64_encode(WC_CONSUMER_KEY . ':' . WC_CONSUMER_SECRET),
        'Content-Type' => 'application/json',
    ],
    'method' => $_SERVER['REQUEST_METHOD'],
];

// 根据请求方法处理参数
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $args['body'] = json_encode($api_params);
} elseif ($_SERVER['REQUEST_METHOD'] === 'GET') {
    $wc_api_url .= '?' . http_build_query($api_params);
}

// 发送请求并返回响应
$response = wp_remote_request($wc_api_url, $args);
if (is_wp_error($response)) {
    wp_send_json_error(['msg' => $response->get_error_message()], 500);
}

wp_send_json(
    json_decode(wp_remote_retrieve_body($response), true),
    wp_remote_retrieve_response_code($response)
);

方式二:注册WordPress REST路由(更规范安全)

在主题的functions.php中添加以下代码,用官方REST API体系实现代理:

add_action('rest_api_init', function () {
    register_rest_route(
        'wc-proxy/v1',
        '/(?P<api_path>.+)',
        [
            'methods' => ['GET', 'POST', 'DELETE'],
            'callback' => 'wc_proxy_handler',
            'permission_callback' => function () {
                // 按需添加权限验证,比如仅允许登录用户
                // return current_user_can('manage_woocommerce');
                return true; // 测试阶段临时放开,上线后替换为真实权限逻辑
            },
        ]
    );
});

function wc_proxy_handler($request) {
    $api_path = $request->get_param('api_path');
    $api_params = $request->get_params();
    unset($api_params['api_path']);

    $wc_api_url = get_site_url() . '/wp-json/wc/v3/' . ltrim($api_path, '/');
    $args = [
        'headers' => [
            'Authorization' => 'Basic ' . base64_encode(WC_CONSUMER_KEY . ':' . WC_CONSUMER_SECRET),
            'Content-Type' => 'application/json',
        ],
        'method' => $request->get_method(),
    ];

    if ($request->get_method() === 'POST') {
        $args['body'] = json_encode($api_params);
    } elseif ($request->get_method() === 'GET') {
        $wc_api_url .= '?' . http_build_query($api_params);
    }

    $response = wp_remote_request($wc_api_url, $args);
    if (is_wp_error($response)) {
        return new WP_Error('proxy_error', $response->get_error_message(), ['status' => 500]);
    }

    return new WP_REST_Response(
        json_decode(wp_remote_retrieve_body($response), true),
        wp_remote_retrieve_response_code($response)
    );
}

3. Vue3中修改请求逻辑

不再直接请求WooCommerce API,转而调用自己的代理接口:

// 基于自定义PHP文件的请求示例
async function callWcApi(apiPath, params = {}, method = 'GET') {
  try {
    const options = { method };
    if (method === 'POST') {
      options.headers = { 'Content-Type': 'application/x-www-form-urlencoded' };
      options.body = new URLSearchParams({ api_path: apiPath, ...params });
    } else {
      const url = new URL('/wp-content/themes/你的主题/wc-api-proxy.php', window.location.origin);
      url.searchParams.append('api_path', apiPath);
      Object.entries(params).forEach(([k, v]) => url.searchParams.append(k, v));
      return await fetch(url).then(res => res.json());
    }
    return await fetch('/wp-content/themes/你的主题/wc-api-proxy.php', options).then(res => res.json());
  } catch (err) {
    console.error('请求失败:', err);
    throw err;
  }
}

// 基于REST路由的请求示例(更简洁)
async function callWcApiRest(apiPath, params = {}, method = 'GET') {
  try {
    const url = new URL(`/wp-json/wc-proxy/v1/${apiPath}`, window.location.origin);
    const options = { method };
    if (method === 'POST') {
      options.headers = { 'Content-Type': 'application/json' };
      options.body = JSON.stringify(params);
    } else {
      Object.entries(params).forEach(([k, v]) => url.searchParams.append(k, v));
    }
    return await fetch(method === 'GET' ? url : '/wp-json/wc-proxy/v1/' + apiPath, options).then(res => res.json());
  } catch (err) {
    console.error('请求失败:', err);
    throw err;
  }
}

// 调用示例:获取订单列表
callWcApi('orders', { per_page: 10 }).then(res => console.log('订单数据:', res));

4. 安全优化建议

  • 给代理接口添加权限验证,比如只允许登录用户或特定角色访问
  • 限制允许代理的API路径,避免全量暴露WooCommerce接口
  • 开启HTTPS,防止请求过程中数据被劫持

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.19 08:17:53