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

基于Socket.io实现WooCommerce下单后管理员通知问题排查

问题与解决方案

现有问题

已开发出可正常运行的Node.js服务端脚本,对接Contact Form 7时,提交联系请求后管理员可收到通知且通知计数器更新正常。但将相同逻辑应用到WooCommerce下单后的感谢页面时,通知功能失效。需解决两个问题:

  1. 实现WooCommerce收到订单时向管理员推送通知
  2. 能否实现跨站点接收通知?

现有代码

WooCommerce相关代码

感谢页面加载时的script.js:

jQuery( document ).ready(function() {
 var socketIO = io("http://localhost:3000");

 var userId = 10;
 socketIO.emit("connected", userId);
 socketIO.emit("newNotification", userId);
 // console.log("Emit executed");
});

后台的admin-script.js:

// connect with Node JS server
 var socketIO = io("http://localhost:3000");
 
 // connect user with Node JS server
 var userId = 10;
 socketIO.emit("connected", userId);


 // when a new notification is received
 socketIO.on("newNotification", function (data) {
     var counter = jQuery('span.notificationcounter').val() + data;
    jQuery('span.notificationcounter').val(counter );
 });

NodeJS服务端代码

// initialize express server
var express = require("express");
var app = express();
 
// create http server from express instance
var http = require("http").createServer(app);
 
// include socket IO
var socketIO = require("socket.io")(http, {
    allowEIO3: true,
    cors: {
        origin: ["http://localhost"]
    }
});

app.get('/', function(req, res){
    res.render("Vasim Shaik");
  });

// start the HTTP server at port 3000
http.listen(process.env.PORT || 3000, function () {
    // console.log("Server started running...");
 
    // an array to save all connected users IDs
    var users = [];
 
    // called when the io() is called from client
    socketIO.on("connection", function (socket) {
        
        // called manually from client to connect the user with server
        socket.on("connected", function (id) {

            users[id] = socket.id;
            socketIO.to(users[id]).emit("connected", id);

            
        });
        // when a new notification is received
        socket.on("newNotification", function (userId) {
         
            // send notification to the selected user
            socketIO.to(users[userId]).emit("newNotification", {message:"new contact request",count:1});

        });

        // when a new notification is received
        socket.on("readNotification", function (userId) {
         
            // send notification to the selected user
            socketIO.to(users[userId]).emit("readNotification", userId);
        });
    });
});

已更新的实现代码截图

  • WooCommerce相关截图:
    WooCommerce相关代码截图
  • WordPress后台脚本截图:
    WordPress后台脚本截图
  • Express服务端截图:
    Express服务端截图

问题解决思路与方案

1. 修复WooCommerce下单通知推送问题

当前方案存在两个核心问题:socket连接未稳定就发送事件、页面加载触发的时机不合理(不代表订单创建成功),以下是两种修复方案:

方案一:后端触发通知(推荐)

通过WooCommerce的订单创建钩子,在订单真正生成时主动通知Node.js服务,再由服务推送通知:

  1. 在WordPress主题的functions.php中添加钩子:
add_action('woocommerce_new_order', 'send_order_notification_to_node', 10, 1);
function send_order_notification_to_node($order_id) {
    $order = wc_get_order($order_id);
    if (!$order) return;

    wp_remote_post('http://localhost:3000/new-order', array(
        'method' => 'POST',
        'body' => json_encode(array('userId' => 10)),
        'headers' => array('Content-Type' => 'application/json'),
    ));
}
  1. 修改Node.js服务,新增接口接收通知并推送:
app.use(express.json());

app.post('/new-order', function(req, res) {
    const userId = req.body.userId;
    if (users[userId]) {
        socketIO.to(users[userId]).emit("newNotification", {message:"新订单通知",count:1});
    }
    res.sendStatus(200);
});

方案二:前端逻辑修正(备选)

等待socket连接成功后再发送事件,同时修正计数器逻辑:

// 感谢页面script.js
jQuery(document).ready(function() {
    var socketIO = io("http://localhost:3000");
    var userId = 10;

    socketIO.on('connect', function() {
        socketIO.emit("connected", userId);
        socketIO.emit("newNotification", userId);
    });
});
// 后台admin-script.js
socketIO.on("newNotification", function (data) {
    var currentCount = parseInt(jQuery('span.notificationcounter').text()) || 0;
    var newCount = currentCount + data.count;
    jQuery('span.notificationcounter').text(newCount);
});

2. 实现跨站点接收通知

可以实现,需要调整以下配置:

  1. CORS权限开放:修改Node.js服务的CORS配置,允许目标站点域名:
cors: {
    origin: ["http://localhost", "http://site-a.com", "http://site-b.com"]
}
  1. 统一用户标识:跨站点使用相同的管理员用户ID或唯一标识(如邮箱)关联socket连接。
  2. 持久化连接存储:生产环境建议用Redis等缓存替代数组存储用户socket ID,避免服务重启后连接丢失。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.25 08:06:29