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

Flutter对接WooCommerce:新增产品推送失效,求排查及替代方案

问题排查与替代实现方案

一、现有代码问题排查

  1. Payload格式错误
    直接用{...}.toString()把Map转成字符串,生成的是{to: token, notification: {...}}这类非标准格式,Firebase根本解析不了。必须用jsonEncode()将Map序列化为标准JSON字符串。

  2. Firebase初始化重复执行
    await Firebase.initializeApp()应该放在App启动的初始化阶段(比如main()函数里),不要每次调用sendNotification()都执行,重复初始化容易引发异常。

  3. 参数需提前验证

    • 确认authenticationKey和rapidApiKey是否有效,有没有过期或权限不足的情况。
    • fcmToken可能为空,必须先判断非空再使用,避免空指针错误。

修正后的代码示例:

import 'dart:convert';

void sendNotification()async{
  String? fcmToken = await FirebaseMessaging.instance.getToken();
  if(fcmToken == null){
    print("FCM Token为空,无法发送通知");
    return;
  }
  print(fcmToken);
  
  final FirebaseNotificationScheduler firebaseNotificationScheduler =
  FirebaseNotificationScheduler(
      authenticationKey: 'NTQ5YzA0MjYtZGRjMS00NTliLTllYjYtMDk4YzZhNzliOTgwOktJMDZMTEVpSGNRWjB2Qlk2RXJaazNKclpRZC9IOUc=',
      rapidApiKey: '4e30d77a63msh5302f3fec95c880p1548e5jsn43509ee88c2d');
  
  final payloadMap = {
    "to": fcmToken,
    "notification": {
      "title": "你的通知标题",
      "body": "你的通知内容"
    },
    "data": {"key_1": "key1的值", "key_2": "key2的值"}
  };
  final _payload = jsonEncode(payloadMap); // 生成标准JSON格式
  
  final _now = DateTime.now().toUtc();
  final _dateTimeInUtc = _now.add(const Duration(minutes: 1));
  final response = await firebaseNotificationScheduler.scheduleNotification(
      payload: _payload, dateTimeInUtc: _dateTimeInUtc);
  print("response = $response");
}

二、更适配场景的替代实现方案

你需要的是站点新增产品时触发推送,定时推送并非最优解,用WooCommerce WebHook联动Firebase Cloud Messaging才是更高效的事件驱动方案:

步骤1:配置WooCommerce WebHook

在WordPress后台的「WooCommerce > 设置 > 高级 > Webhooks」中新增WebHook:

  • 触发事件:选择「产品创建」
  • 交付URL:填写你部署的云函数(如Firebase Functions)地址
  • 内容类型:选择JSON
  • 密钥:设置一个签名密钥,用于验证请求合法性

步骤2:编写云函数处理WebHook并发通知

以Firebase Functions(Node.js)为例:

const functions = require("firebase-functions");
const admin = require("firebase-admin");
admin.initializeApp();

// 处理WooCommerce新品创建的WebHook请求
exports.sendNewProductNotification = functions.https.onRequest(async (req, res) => {
  // 验证WebHook签名,确保请求来自你的站点(参照WooCommerce文档实现签名验证逻辑)
  const signature = req.headers['x-wc-webhook-signature'];
  // 此处补充签名验证代码,拦截恶意请求
  
  // 解析新品数据
  const product = req.body;
  const notificationTitle = "新品上架!";
  const notificationBody = `快来看看新品:${product.name}`;
  
  // 向订阅主题的所有设备发送通知
  const message = {
    notification: {
      title: notificationTitle,
      body: notificationBody
    },
    topic: "new_products" // 所有订阅该主题的设备都会收到通知
    // 若需定向发送,可替换为tokens: [目标设备FCM Token列表]
  };
  
  try {
    const response = await admin.messaging().send(message);
    console.log("通知发送成功:", response);
    res.status(200).send("通知已发送");
  } catch (error) {
    console.error("通知发送失败:", error);
    res.status(500).send("发送失败");
  }
});

步骤3:Flutter端订阅主题

在App初始化阶段,让设备订阅new_products主题,即可实时接收新品通知:

await FirebaseMessaging.instance.subscribeToTopic("new_products");

这种事件驱动的方式比定时推送更实时、高效,完全匹配你“站点新增产品时接收推送”的核心需求。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.19 02:55:25