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

如何在Flutter新闻应用中实现WhatsApp消息自动推送?

实现新闻创建后自动推送至WhatsApp的方案

核心思路

在新闻后台创建完成的成功回调节点直接触发WhatsApp推送逻辑,无需额外确认,流程为:新闻创建入库成功 → 整理推送内容 → 调用WhatsApp发送API → 推送至预设的群组/联系人。


具体实现步骤

1. 接入WhatsApp消息发送能力

个人WhatsApp账号不支持自动/批量发送消息(易被风控封禁),必须使用官方合规的服务:

  • 选择WhatsApp Business Platform(Meta官方提供),或第三方服务商的WhatsApp API服务
  • 完成商家账号注册、API凭证(Access Token、Phone Number ID)获取,确保接口调用权限正常

2. 嵌入推送触发逻辑

在你的后台新闻创建接口的成功处理分支中,直接调用推送函数,无需额外确认步骤:

  • 比如在后端createNews接口的数据库写入成功后,立即执行pushNewsToWhatsApp(newsData)

3. 构建合规的推送内容

按照WhatsApp消息规范整理新闻内容,避免触发风控:

  • 内容结构建议:【新闻推送】\n标题: ${news.title}\n摘要: ${news.summary}\n查看详情: ${news.detailUrl}
  • 注意文本长度限制(单条消息建议不超1000字符),避免使用敏感词汇

4. 管理推送目标列表

提前在后台维护需要推送的群组ID和联系人号码:

  • 将目标信息存储在数据库中(如whatsapp_targets表,包含type(group/contact)、target_id(群组ID/手机号)字段)
  • 推送时从数据库读取列表,循环调用发送接口

5. 错误处理与日志

推送过程中必须记录状态,避免丢失推送记录:

  • 发送失败时记录错误日志(如目标ID、错误原因、新闻ID),便于后续排查
  • 可添加重试机制(如针对网络波动导致的失败,重试2-3次)

伪代码示例(Node.js)

// 新闻创建成功后的触发函数
async function handleNewsCreated(news) {
  // 1. 整理推送内容
  const pushContent = `【最新新闻发布】\n标题: ${news.title}\n摘要: ${news.summary}\n详情链接: ${news.detailUrl}`;

  // 2. 从数据库获取推送目标
  const pushTargets = await db.query('SELECT type, target_id FROM whatsapp_targets WHERE is_active = 1');

  // 3. 批量推送
  for (const target of pushTargets) {
    try {
      await sendWhatsAppMessage(target.target_id, pushContent);
      console.log(`推送成功:${target.type === 'group' ? '群组' : '联系人'} ${target.target_id}`);
    } catch (err) {
      console.error(`推送失败:${target.type === 'group' ? '群组' : '联系人'} ${target.target_id},错误:${err.message}`);
      // 写入错误日志表
      await db.query('INSERT INTO push_errors (news_id, target_type, target_id, error_msg) VALUES (?, ?, ?, ?)', 
        [news.id, target.type, target.target_id, err.message]);
    }
  }
}

// 封装WhatsApp API调用
async function sendWhatsAppMessage(recipient, content) {
  const apiUrl = `https://graph.facebook.com/v18.0/${process.env.WHATSAPP_PHONE_ID}/messages`;
  const response = await fetch(apiUrl, {
    method: 'POST',
    headers: {
      'Authorization': `Bearer ${process.env.WHATSAPP_ACCESS_TOKEN}`,
      'Content-Type': 'application/json'
    },
    body: JSON.stringify({
      messaging_product: 'whatsapp',
      to: recipient,
      text: { body: content }
    })
  });

  if (!response.ok) {
    throw new Error(`API请求失败:${await response.text()}`);
  }
}

注意事项

  • 严格遵守WhatsApp的商业消息政策,确保接收用户已同意接收推送,避免发送垃圾信息导致账号封禁
  • 测试阶段使用官方提供的测试号码/群组,验证流程正常后再切换至生产环境
  • 若推送量较大,可考虑使用消息队列(如Redis Queue)异步处理,避免阻塞新闻创建接口

内容的提问来源于stack exchange,提问作者Hemant Kumar Joshi

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.13 11:50:24