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

如何在Node.js中借助OneSignal包实现推送通知功能?

在Node.js中使用OneSignal实现推送通知功能

1. 安装OneSignal Node.js包

首先通过包管理器安装官方SDK:

npm install onesignal-node
# 或使用yarn
yarn add onesignal-node

2. 初始化OneSignal客户端

从OneSignal控制台获取APP ID和REST API密钥,用这两个信息初始化客户端:

const OneSignal = require('onesignal-node');

const client = new OneSignal.Client({
  app: {
    appId: '你的OneSignal APP ID',
    apiKey: '你的OneSignal REST API密钥'
  }
});

3. 发送推送通知的常用场景

给所有订阅用户发送通知

基础批量推送示例,支持多语言内容:

async function sendToAllUsers() {
  try {
    const response = await client.createNotification({
      contents: {
        en: 'Hello from OneSignal!',
        zh: '来自OneSignal的推送消息!'
      },
      headings: {
        en: '新通知',
        zh: '新通知'
      }
    });
    console.log('通知发送成功:', response.body);
  } catch (error) {
    console.error('发送失败:', error.response?.data || error.message);
  }
}

sendToAllUsers();

给指定用户发送(通过Player ID)

针对单个或多个特定用户推送,需提前获取用户的Player ID:

async function sendToSpecificUsers() {
  try {
    const response = await client.createNotification({
      contents: { en: '这是你的专属通知' },
      include_player_ids: ['用户Player ID 1', '用户Player ID 2']
    });
    console.log('通知发送成功:', response.body);
  } catch (error) {
    console.error('发送失败:', error.response?.data || error.message);
  }
}

给带标签的用户分组推送

根据用户标签筛选目标群体,比如给所有level:vip的用户发福利通知:

async function sendToTaggedUsers() {
  try {
    const response = await client.createNotification({
      contents: { en: 'VIP用户专属福利已到账' },
      filters: [
        { field: 'tag', key: 'level', relation: '=', value: 'vip' }
      ]
    });
    console.log('通知发送成功:', response.body);
  } catch (error) {
    console.error('发送失败:', error.response?.data || error.message);
  }
}

4. 自定义通知参数

添加更多配置实现个性化通知,比如跳转链接、附加数据、角标计数等:

async function sendCustomizedNotification() {
  try {
    const response = await client.createNotification({
      contents: { en: '点击查看订单详情' },
      headings: { en: '订单更新提醒' },
      url: 'https://your-app.com/order-detail', // 点击跳转链接
      data: { orderId: 'ORD-12345' }, // 客户端可解析的附加数据
      ios_badgeType: 'Increase',
      ios_badgeCount: 1,
      big_picture: 'https://your-app.com/notification-banner.jpg' // 通知大图
    });
    console.log('通知发送成功:', response.body);
  } catch (error) {
    console.error('发送失败:', error.response?.data || error.message);
  }
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.09 06:30:59