WordPress使用AJAX调用外部API保护API Key的实现问题咨询
实现方案
你可以直接基于现有代码改造,用WordPress原生的admin-ajax.php处理AJAX请求即可,不需要引入WP Rest API,API密钥全程仅在服务端使用,不会暴露给前端,具体修改如下:
步骤1:新增AJAX请求处理钩子与业务逻辑
在现有代码的初始化部分新增AJAX钩子,同时编写请求处理函数,外部API调用逻辑直接写在这个函数里:
// 原有初始化代码 defined('ABSPATH') or die('Unauthorized access.'); add_shortcode('page-feedback', 'page_feedback_shortcode'); add_action('wp_footer', 'load_scripts'); // 新增:注册AJAX处理钩子(登录用户/未登录用户都支持) add_action('wp_ajax_submit_feedback', 'handle_feedback_submit'); add_action('wp_ajax_nopriv_submit_feedback', 'handle_feedback_submit'); // 新增:AJAX请求处理函数 function handle_feedback_submit() { // 安全校验:验证nonce防止CSRF攻击 if (!isset($_POST['feedback_nonce']) || !wp_verify_nonce($_POST['feedback_nonce'], 'feedback_nonce')) { wp_send_json_error('非法请求'); } // 获取前端提交的参数 $page_url = urldecode($_POST['page']); $username = sanitize_text_field($_POST['username']); $helpful = sanitize_text_field($_POST['helpful']); // 调用外部API(API密钥直接用你在wp-config定义的常量即可) $api_response = wp_remote_post('你的外部API地址', [ 'headers' => [ 'Authorization' => 'Bearer ' . YOUR_DEFINED_API_KEY, // 替换成你在wp-config里定义的API Key常量名 'Content-Type' => 'application/json' ], 'body' => json_encode([ 'page' => $page_url, 'username' => $username, 'helpful' => $helpful ]) ]); // 处理API返回结果 if (is_wp_error($api_response)) { wp_send_json_error('提交失败,请稍后重试'); } $response_body = json_decode(wp_remote_retrieve_body($api_response), true); if (wp_remote_retrieve_response_code($api_response) === 200) { wp_send_json_success('反馈提交成功'); } else { wp_send_json_error($response_body['message'] ?? '提交失败'); } }
步骤2:修改短代码,加入安全校验字段
给表单新增nonce校验字段,同时给Yes/No按钮加点击事件,给hidden的helpful字段赋值:
function page_feedback_shortcode() { ?> <div class="page-feedback"> <form id="page-feedback-form__form"> <!-- 新增:nonce安全校验字段 --> <?php wp_nonce_field('feedback_nonce', 'feedback_nonce'); ?> <input name="page" type="hidden" value="<?php echo urlencode(get_the_permalink()) ?>" /> <input name="username" type="hidden" value="<?php echo wp_get_current_user()->user_login ?>" /> <input id="page-feedback-form-helpful" name="helpful" type="hidden" /> <p id="page-feedback-form-helpfulQuestion"> Was this page helpful? <button type="button" class="feedback-btn" data-value="yes">Yes</button> or <button type="button" class="feedback-btn" data-value="no">No</button> </p> <p id="feedback-result" style="display:none;"></p> </form> </div> <?php }
步骤3:修改前端脚本,补全AJAX配置
用WordPress内置的admin_url输出AJAX请求地址,完善提交逻辑:
function load_scripts() { ?> <script> jQuery(function($) { // 点击Yes/No按钮赋值 $('.feedback-btn').click(function() { $('#page-feedback-form-helpful').val($(this).data('value')); $('#page-feedback-form__form').submit(); }); $('#page-feedback-form__form').submit(function(event) { event.preventDefault(); const formData = $(this).serialize() + '&action=submit_feedback'; $.ajax({ method: 'post', url: '<?php echo admin_url('admin-ajax.php'); ?>', data: formData, success: function(res) { $('#page-feedback-form-helpfulQuestion').hide(); $('#feedback-result').show().text(res.data); if (res.success) { $('#feedback-result').css('color', 'green'); } else { $('#feedback-result').css('color', 'red'); } }, error: function() { $('#page-feedback-form-helpfulQuestion').hide(); $('#feedback-result').show().text('网络异常,请稍后重试').css('color', 'red'); } }) }); }); </script> <?php }
疑问说明
你提到的「直接用现有PHP文件处理请求」是不可行的:你文件开头定义了defined('ABSPATH') or die,直接访问该文件时WordPress核心未加载,ABSPATH不存在,会直接拦截请求。用上述admin-ajax的流程是WordPress的标准实现方案,不需要引入额外的WP功能,完全满足你的需求。
内容的提问来源于stack exchange,提问作者MCRXB
相关产品推荐
相关产品推荐

