跳转到主要内容
所有 OneSignal 服务器 SDK 均由同一 OpenAPI 规范生成,因此无论使用哪种语言,它们都具有一致的接口。每个 SDK 封装了 OneSignal REST API 并提供请求和响应的类型化模型。

可用 SDK


安装

npm install @onesignal/node-onesignal

配置

每个 SDK 都需要通过 API 密钥进行身份验证。有两种密钥类型:
  • REST API 密钥 — 大多数端点(发送通知、管理用户等)都需要。在您应用的设置 > 密钥和 ID 中找到。
  • 组织 API 密钥 — 仅用于组织级端点,如创建或列出应用程序。在组织设置中找到。
const OneSignal = require('@onesignal/node-onesignal');

const configuration = OneSignal.createConfiguration({
  restApiKey: 'YOUR_REST_API_KEY',
  organizationApiKey: 'YOUR_ORGANIZATION_API_KEY',
});

const client = new OneSignal.DefaultApi(configuration);
将 API 密钥存储在环境变量或密钥管理器中。切勿将它们提交到源代码控制中。

发送推送通知

通过定向至分段,向网页和移动端订阅发送推送通知。
const notification = new OneSignal.Notification();
notification.app_id = 'YOUR_APP_ID';
notification.contents = { en: 'Hello from OneSignal!' };
notification.headings = { en: 'Push Notification' };
notification.included_segments = ['Subscribed Users'];

const response = await client.createNotification(notification);
console.log('Notification ID:', response.id);

发送电子邮件

通过 email 渠道向订阅发送电子邮件。
const notification = new OneSignal.Notification();
notification.app_id = 'YOUR_APP_ID';
notification.email_subject = 'Important Update';
notification.email_body = '<h1>Hello!</h1><p>This is an HTML email.</p>';
notification.included_segments = ['Subscribed Users'];
notification.channel_for_external_user_ids = 'email';

const response = await client.createNotification(notification);

发送短信

通过 sms 渠道向订阅发送短信。
const notification = new OneSignal.Notification();
notification.app_id = 'YOUR_APP_ID';
notification.contents = { en: 'Your SMS message content here' };
notification.included_segments = ['Subscribed Users'];
notification.channel_for_external_user_ids = 'sms';
notification.sms_from = '+15551234567';

const response = await client.createNotification(notification);

完整 API 参考

每个服务器 SDK 支持相同的 API 端点集。请参阅 SDK 的 API 文档获取完整方法列表,包括用户、订阅、分段、模板等。 有关底层 REST API,请参阅完整 API 参考

常见问题

我应该选择哪个服务器 SDK?

使用与您后端语言匹配的 SDK。所有服务器 SDK 均由同一 OpenAPI 规范生成并支持相同的端点,因此各语言的功能完全相同。

REST API 密钥和组织 API 密钥有什么区别?

REST API 密钥作用范围为单个应用,大多数操作(如发送通知和管理用户)都需要它。组织 API 密钥作用范围为您的组织,仅用于创建或列出应用程序。大多数集成只需要 REST API 密钥。

我可以直接使用 REST API 而不使用 SDK 吗?

可以。服务器 SDK 是 OneSignal REST API 的便捷封装。您可以使用任何支持 Bearer 令牌身份验证的 HTTP 客户端直接调用 API。

这些 SDK 是自动生成的吗?

是的。所有服务器 SDK 均使用 OpenAPI Generator 从 OneSignal OpenAPI 规范生成。这确保了所有语言的 API 覆盖一致性。