YITH Live Push Notifications 的底层事件源与消息管线

发布于 2025-11-24 21:04:54

YITH Live Push Notifications 的底层事件源与消息管线

YITH Live Push Notifications for WooCommerce 的核心不是“弹个通知”这么简单,而是把 WooCommerce 的业务事件实时转成可投递的消息流。底层一般分三层:事件源(Hooks)→ 消息队列/存储(DB/Transient)→ 推送适配器(Web Push / OneSignal / Firebase 或自带通道)。
在事件源层,它会订阅多个关键钩子,比如下单、付款完成、订单状态变更、低库存、商品上新等。每触发一次,就会生成一个“通知对象”,包含 type、title、body、target、payload(order_id/product_id/user_id)以及过期时间。
消息管线的关键在于“异步化 + 去重”。如果订单状态在短时间内连续变化(processing→completed),插件必须避免连发两条相同通知;通常会用 meta 或 hash 做 idempotency。然后将通知写入自定义表(更稳)或 post_meta/transient(更轻),再由前端轮询/长连接或后台 cron 统一投递。对于 Web Push 场景,投递阶段需要维护订阅端点(endpoint、p256dh、auth),并按用户授权状态过滤。


关键钩子与代码骨架:生成通知、入库、推送

下面用简化骨架说明它的实现思路(与真实插件的 hook 设计一致):

// 1) 监听订单完成事件 -> 生成通知对象
add_action('woocommerce_order_status_completed', function($order_id){
  $order = wc_get_order($order_id);
  $data = [
    'type'    => 'order_completed',
    'title'   => 'New Order Completed',
    'body'    => sprintf('#%d - %s', $order_id, $order->get_formatted_billing_full_name()),
    'target'  => 'admin', // or user/vendor
    'payload' => ['order_id'=>$order_id],
    'hash'    => md5('order_completed_'.$order_id),
    'created' => time()
  ];
  yith_lpns_store_notification($data);
  yith_lpns_dispatch_async($data['hash']);
});

// 2) 入库(示例:写入自定义表 / option)
function yith_lpns_store_notification($data){
  global $wpdb;
  $table = $wpdb->prefix.'yith_lpns_notifications';
  $wpdb->insert($table, [
    'hash'    => $data['hash'],
    'type'    => $data['type'],
    'title'   => $data['title'],
    'body'    => $data['body'],
    'payload' => wp_json_encode($data['payload']),
    'status'  => 'pending',
    'created' => $data['created'],
  ]);
}

// 3) 异步投递(cron/队列)
function yith_lpns_dispatch_async($hash){
  if (wp_next_scheduled('yith_lpns_send_job', [$hash])) return; // 去重
  wp_schedule_single_event(time()+5, 'yith_lpns_send_job', [$hash]);
}

add_action('yith_lpns_send_job', function($hash){
  $notif = yith_lpns_get_notification($hash);
  if(!$notif || $notif->status!=='pending') return;

  $subs = yith_lpns_get_subscribers($notif->target);
  foreach($subs as $sub){
    // Web Push/Firebase 适配层
    yith_lpns_send_to_endpoint($sub, $notif);
  }
  yith_lpns_mark_sent($hash);
});

这个流程体现了插件的底层价值:

  • 用 WooCommerce 事件作为消息触发器,不侵入业务;
  • 通知对象结构化,便于扩展不同类型推送;
  • 异步队列 + hash 去重,保证高并发下不炸通知;
  • 推送通道可插拔,Web Push/第三方服务只是一层适配。

如果你要二开这类插件,重点就是维护好事件订阅的边界、通知对象 schema 的稳定性,以及投递层的幂等与失败重试策略。

0 条评论

发布
问题