JavaScript 的 Azure 通知枢纽 SDK
Azure Notication Hubs提供一个缩放的推放引擎,使您能够从任何后端(云或地上)向任何平台(Apple, Amazon Kindle, Firebase, Baidu, Xiaomi, Web, Windows等)发送通知. 通知中心对企业和消费者都行之有效。 以下是几个实例:
- 发送即时新闻通知 数百万与低纬度.
- 将基于位置的优惠券发送给感兴趣的用户区段.
- 向用户或团体发送与事件有关的通知,用于媒体/体育/金融/采集应用程序.
- 将促销内容推向应用,以招商和向客户推销.
- 通知新消息和工作项目等企业活动的用户.
- 发送多要素认证代码 .
密钥链接 :
页:1: 如果你来自使用 azure-sb 软件包,参见 向@azure/ notification-hubs移动的移民指南
开始
目前得到支持的环境
- 节点.js的LTS版本
- Safari,Chrome,Edge,和Firefox的最新版本.
看我们的 支助政策 更多细节.
安装软件包
npm install @azure/notification-hubs
先决条件
创建 Azure 通知枢纽资源
可以使用下列方法创建Azure通知枢纽:
一旦创建,便可以使用 Azure 门户网站或 Azure CLI。 。 。 .
导入客户端
这个用于JavaScript的SDK提供了两种与Azure通知枢纽进行互动的方法,要么通过基于类的方法,要么采用模块化设计方法. 基于类的方法在所有软件包中一致地创建客户端,然后在客户端上与方法交互.
import { NotificationHubsClient, createAppleInstallation } from "@azure/notification-hubs";
const client = new NotificationHubsClient("<connection string>", "<hub name>");
const installation = createAppleInstallation({
installationId: "<installation-id>",
pushChannel: "<push-channel>",
tags: ["likes_javascript"],
});
const result = await client.createOrUpdateInstallation(installation);
模块化方法允许开发者在每种方法单独被曝光时选择要导入的函数. 这种方法使用带有ES-Modules的子路径出口,通过直接进口暴露出方法. 随着个别出口,这创造了更好的摇树体验和更小的捆绑尺寸,开发商可以利用.
请注意,创建客户端是通过 "@azure/notification-hubs/api" 子路径和所有客户端方法通过 "@azure/notification-hubs/api" 子路径。 导出的每一函数都取 client 作为第一个参数和其余参数保持不变.
以下子路径被曝光:
@azure/notification-hubs/api- 客户通过createClientContext和客户方法,例如getInstallation或者说sendNotification@azure/notification-hubs/models- 通知中心模型和工厂方法.
上面的代码片段然后变成如下:
import { createClientContext, createOrUpdateInstallation } from "@azure/notification-hubs/api";
import { createAppleInstallation } from "@azure/notification-hubs";
const context = createClientContext("<connection string>", "<hub name>");
const installation = createAppleInstallation({
installationId: "<installation-id>",
pushChannel: "<push-channel>",
tags: ["likes_javascript"],
});
const result = await createOrUpdateInstallation(context, installation);
认证客户端
与 Azure 通知中心的互动始于 NotificationHubsClient 用于支持 共享访问签名连接字符串。这包括以下许可级别: 听着, (中文(简体) ), 管理, (中文(简体) ), 发送。 。 。 .
倾听允许客户端通过注册和安装API自行注册. 发送允许客户端使用发送API向设备发送通知. 最后,"管理"允许用户进行注册和安装管理,如查询.
一个新的 NotificationHubsClient 可以使用连接字符串和通知枢纽名称的构造器创建客户端.
import { NotificationHubsClient } from "@azure/notification-hubs";
const client = new NotificationHubsClient("<connection string>", "<hub name>");
采用模块化方法 createClientContext 可以通过 "@azure/notification-hubs/api" 子路径.
import { createClientContext } from "@azure/notification-hubs/api";
const context = createClientContext("<connection string>", "<hub name>");
关键概念
一旦 NotificationHubClient 现已初步确定,可探讨以下概念.
- 通过安装和登记进行设备管理
- 向设备发送通知
设备管理
设备管理是通知枢纽的一个核心概念,能够存储本地平台通知服务(PNS)中独特的标识符,如APN或Firebase,以及用于向受众发送推力通知的标记等相关元数据. 使用两个API即安装API(较新的首选机制)和注册.
安装 API
安装是一种较新而本土的JSON设备管理方法,它包含额外的属性,如安装ID和用户ID,可用于发送给受众. 与现有的登记辅助设施相比,这些设施具有以下一些优势:
- Fully idempotent API因此呼叫在安装上创建,所以一个操作可以重审而不担心重复.
- 支助
userId财务报告和审定财务报表installationId属性,然后可用于标记表达式,例如$InstallationId:{myInstallId}财务报告和审定财务报表$UserId:{[email protected]}。 。 。 . - 模板现在成为安装的一部分,而不是单独的注册,可以作为发送标记的名称参考.
- 部分更新通过 JSON 补丁标准,它允许添加标签并更改其他数据,而无需首先查询安装.
安装可以通过 createOrUpdateInstallation 方法,例如:
import { NotificationHubsClient, createAppleInstallation } from "@azure/notification-hubs";
const client = new NotificationHubsClient("<connection string>", "<hub name>");
// Create an installation for APNs
const installation = createAppleInstallation({
installationId: "0d8ab095-c449-493f-9195-17e4917806c4", // Must be unique
pushChannel: "00fc13adff785122b4ad28809a3420982341241421348097878e577c991de8f0", // PNS specific handle
tags: ["likes_hockey", "likes_football"],
});
const response = await client.createOrUpdateInstallation(installation);
采用模块化方法,编码如下:
import { createClientContext, createOrUpdateInstallation } from "@azure/notification-hubs/api";
import { createAppleInstallation } from "@azure/notification-hubs";
const context = createClientContext("<connection string>", "<hub name>");
// Create an installation for APNs
const installation = createAppleInstallation({
installationId: "0d8ab095-c449-493f-9195-17e4917806c4", // Must be unique
pushChannel: "00fc13adff785122b4ad28809a3420982341241421348097878e577c991de8f0", // PNS specific handle
tags: ["likes_hockey", "likes_football"],
});
const response = await createOrUpdateInstallation(context, installation);
对安装的更新可以通过 JSON 补丁计划进行,例如添加标签和用户ID updateInstallation 方法.
import { NotificationHubsClient, JsonPatch } from "@azure/notification-hubs";
const client = new NotificationHubsClient("<connection string>", "<hub name>");
const installationId = "<unique installation ID>";
const updates: JsonPatch[] = [
{ op: "add", path: "/tags", value: "likes_baseball" },
{ op: "add", path: "/userId", value: "[email protected]" },
];
const installation = await client.updateInstallation(installationId, updates);
采用模块化方法,编码如下:
import { createClientContext, updateInstallation } from "@azure/notification-hubs/api";
import { JsonPatch } from "@azure/notification-hubs";
const context = createClientContext("<connection string>", "<hub name>");
const installationId = "<unique installation ID>";
const updates: JsonPatch[] = [
{ op: "add", path: "/tags", value: "likes_baseball" },
{ op: "add", path: "/userId", value: "[email protected]" },
];
const installation = await updateInstallation(context, installationId, updates);
要获取已有的安装, 请使用 getInstallation 方法与您现有的唯一安装标识.
import { NotificationHubsClient } from "@azure/notification-hubs";
const client = new NotificationHubsClient("<connection string>", "<hub name>");
const installationId = "<unique installation ID>";
const installation = client.getInstallation(installationId);
采用模块化方法,编码如下:
import { createClientContext, getInstallation } from "@azure/notification-hubs/api";
const context = createClientContext("<connection string>", "<hub name>");
const installationId = "<unique installation ID>";
const installation = getInstallation(context, installationId);
登记 API
登记与上面的安装一样与PNS有关,并带有PNS中唯一的设备标识符和相关标记. 模板注册是创建预定义的机身模板的一种方式,然后可以在发送时根据属性进行定制以填充消息. 关于模板的更多信息,请参见: 模板文档。 。 。 .
安装可以采用两种方式之一,首先从服务器获取注册ID getInstallationId 接下来 createOrUpdateRegistration 或通过 createRegistration 方法.
import {
NotificationHubsClient,
createAppleRegistrationDescription,
} from "@azure/notification-hubs";
const client = new NotificationHubsClient("<connection string>", "<hub name>");
const registration = createAppleRegistrationDescription({
deviceToken: "00fc13adff785122b4ad28809a3420982341241421348097878e577c991de8f0",
tags: ["likes_hockey", "likes_football"],
});
const updatedRegistration = await client.createRegistration(registration);
采用模块化方法,编码如下:
import { createClientContext, createRegistration } from "@azure/notification-hubs/api";
import { createAppleRegistrationDescription } from "@azure/notification-hubs";
const context = createClientContext("<connection string>", "<hub name>");
const registration = createAppleRegistrationDescription({
deviceToken: "00fc13adff785122b4ad28809a3420982341241421348097878e577c991de8f0",
tags: ["likes_hockey", "likes_football"],
});
const updatedRegistration = await createRegistration(context, registration);
可通过 updateRegistration 方法,但与安装不同,不支持递增更新。 查询现有登记可使用 getRegistration 方法.
import { NotificationHubsClient } from "@azure/notification-hubs";
const client = new NotificationHubsClient("<connection string>", "<hub name>");
const registrationId = "<unique Registration ID>";
const registration = await client.getRegistration(registrationId);
if (registration.tags) {
registration.tags.push("likes_sports");
} else {
registration.tags = ["likes_sports"];
}
const updatedRegistration = await client.updateRegistration(registration);
采用模块化方法,编码如下:
import {
createClientContext,
getRegistration,
updateRegistration,
} from "@azure/notification-hubs/api";
const context = createClientContext("<connection string>", "<hub name>");
const registrationId = "<unique Registration ID>";
const registration = await getRegistration(context, registrationId);
if (registration.tags) {
registration.tags.push("likes_sports");
} else {
registration.tags = ["likes_sports"];
}
const updatedRegistration = await updateRegistration(context, registration);
与设施不同的是,可以查询登记,以便获得所有登记,将登记与条件相匹配,或者通过标记。 登记可使用 listRegistrations, (中文(简体) ), listRegistrationsByChannel 财务报告和审定财务报表 listRegistrationsByTag 方法。 所有方法都支持通过 top 选项,并支持同步调用.
import { NotificationHubsClient } from "@azure/notification-hubs";
const client = new NotificationHubsClient("<connection string>", "<hub name>");
const registrations = client.listRegistrationsByTag("likes_hockey");
let page = 0;
for await (const pages of registrations.byPage()) {
console.log(`Page number ${page++}`);
for (const item of pages) {
console.log(JSON.stringify(item, null, 2));
}
}
采用模块化方法,编码如下:
import { createClientContext, listRegistrationsByTag } from "@azure/notification-hubs/api";
const context = createClientContext("<connection string>", "<hub name>");
const registrations = await listRegistrationsByTag(context, "likes_hockey");
let page = 0;
for await (const pages of registrations.byPage()) {
console.log(`Page number ${page++}`);
for (const item of pages) {
console.log(JSON.stringify(item, null, 2));
}
}
发送操作
通知中心支持向设备发送通知,要么直接使用唯一提供的PNS标识符,使用标记给观众发送,要么向所有设备发送一般广播. 使用标准SKU及以上, 预定发送 允许用户最多提前七天安排通知。 所有发送操作都返回可用于通知中心支持案件的跟踪ID和关联ID。 使用标准SKU及以上,也可返回通知ID,该ID可用于通过 getNotificationOutcomeDetails 方法.
为调试目的 enableTestSend 选项可设定为 true 立即从PNS获得关于 sendNotification 但是,在生产设想中,不支持方法。 计划发送方法不支持此选项 .
Raw JSON 或 XML 字符串可以发送到发送或预定的发送方法,或者可以使用通知构建器来帮助每个PNS构造消息,如APNs,Firebase,Baidu,ADM和WNS. 这些构建者将构建本地信件格式, 因此无法猜测每个 PNS 可用的字段 .
import { createAppleNotificationBody, createAppleNotification } from "@azure/notification-hubs";
const apnsBody = createAppleNotificationBody({
alert: {
title: "Notification Title",
subtitle: "Notification Subtitle",
body: "Notification body goes here",
},
sound: "default",
interruptionLevel: "time-sensitive",
});
// Send the message using the modular approach
const notification = createAppleNotification({
body: apnsBody,
});
广播发送
通知中心可用于向每个平台的所有已登记设备发送通知,通过广播发送 sendBroadcastNotification 方法.
import { NotificationHubsClient, createAppleNotification } from "@azure/notification-hubs";
const client = new NotificationHubsClient("<connection string>", "<hub name>");
const messageBody = `{ "aps" : { "alert" : "Hello" } }`;
const message = createAppleNotification({
body: messageBody,
headers: {
"apns-priority": "10",
"apns-push-type": "alert",
},
});
const result = await client.sendBroadcastNotification(message);
console.log(`Tracking ID: ${result.trackingId}`);
console.log(`Correlation ID: ${result.correlationId}`);
// Only available in Standard SKU and above
if (result.notificationId) {
console.log(`Notification ID: ${result.notificationId}`);
}
采用模块化方法,编码如下:
import { createClientContext, sendBroadcastNotification } from "@azure/notification-hubs/api";
import { createAppleNotification } from "@azure/notification-hubs";
const context = createClientContext("<connection string>", "<hub name>");
const messageBody = `{ "aps" : { "alert" : "Hello" } }`;
const message = createAppleNotification({
body: messageBody,
headers: {
"apns-priority": "10",
"apns-push-type": "alert",
},
});
const result = await sendBroadcastNotification(context, message);
console.log(`Tracking ID: ${result.trackingId}`);
console.log(`Correlation ID: ${result.correlationId}`);
// Only available in Standard SKU and above
if (result.notificationId) {
console.log(`Notification ID: ${result.notificationId}`);
}
直接发送
要直接发送设备,用户可以通过调用 APNs 设备令牌等提供唯一标识符的平台发送 sendNotification 使用一个方法 deviceHandle 参数.
import { NotificationHubsClient, createAppleNotification } from "@azure/notification-hubs";
const client = new NotificationHubsClient("<connection string>", "<hub name>");
const deviceHandle = "00fc13adff785122b4ad28809a3420982341241421348097878e577c991de8f0";
const messageBody = `{ "aps" : { "alert" : "Hello" } }`;
const message = createAppleNotification({
body: messageBody,
headers: {
"apns-priority": "10",
"apns-push-type": "alert",
},
});
const result = await client.sendNotification(message, { deviceHandle });
console.log(`Tracking ID: ${result.trackingId}`);
console.log(`Correlation ID: ${result.correlationId}`);
// Only available in Standard SKU and above
if (result.notificationId) {
console.log(`Notification ID: ${result.notificationId}`);
}
采用模块化方法,编码如下:
import { createClientContext, sendNotification } from "@azure/notification-hubs/api";
import { createAppleNotification } from "@azure/notification-hubs";
const context = createClientContext("<connection string>", "<hub name>");
const deviceHandle = "00fc13adff785122b4ad28809a3420982341241421348097878e577c991de8f0";
const messageBody = `{ "aps" : { "alert" : "Hello" } }`;
const message = createAppleNotification({
body: messageBody,
headers: {
"apns-priority": "10",
"apns-push-type": "alert",
},
});
const result = await sendNotification(context, message, { deviceHandle });
console.log(`Tracking ID: ${result.trackingId}`);
console.log(`Correlation ID: ${result.correlationId}`);
// Only available in Standard SKU and above
if (result.notificationId) {
console.log(`Notification ID: ${result.notificationId}`);
}
观众发送
除了针对单个设备,用户还可以使用标记瞄准多个设备. 这些标记可以作为标记列表提供,然后生成一个标记表达式来匹配已注册的设备,或者通过一个标记表达式,然后可以使用布尔逻辑来瞄准正确的受众. 关于标签和标签表达式的更多信息,参见 运行和标记表达式。 。 。 .
如果您想从一系列标签中创建标签表达式, 则有一个标签表达式构建器可用, 并带有 createTagExpression 在顶端导入时曝光的方法或 @azure/notification-hubs/models/tagExpressionBuilder 从标签中创建“ 或标签表达式” 的模块导入 .
import { createTagExpression } from "@azure/notification-hubs";
const tags = ["likes_football", "likes_hockey"];
const tagExpression = createTagExpression(tags);
console.log(tagExpression);
标记表达式消息可以使用以下代码发送:
import { NotificationHubsClient, createAppleNotification } from "@azure/notification-hubs";
const client = new NotificationHubsClient("<connection string>", "<hub name>");
const tagExpression = "likes_hockey && likes_football";
const messageBody = `{ "aps" : { "alert" : "Hello" } }`;
const notification = createAppleNotification({
body: messageBody,
headers: {
"apns-priority": "10",
"apns-push-type": "alert",
},
});
const result = await client.sendNotification(notification, { tagExpression });
console.log(`Tracking ID: ${result.trackingId}`);
console.log(`Correlation ID: ${result.correlationId}`);
// Only available in Standard SKU and above
if (result.notificationId) {
console.log(`Notification ID: ${result.notificationId}`);
}
采用模块化方法,编码如下:
import { createClientContext, sendNotification } from "@azure/notification-hubs/api";
import { createAppleNotification } from "@azure/notification-hubs";
const context = createClientContext("<connection string>", "<hub name>");
const tagExpression = "likes_hockey && likes_football";
const messageBody = `{ "aps" : { "alert" : "Hello" } }`;
const notification = createAppleNotification({
body: messageBody,
headers: {
"apns-priority": "10",
"apns-push-type": "alert",
},
});
const result = await sendNotification(context, notification, { tagExpression });
console.log(`Tracking ID: ${result.trackingId}`);
console.log(`Correlation ID: ${result.correlationId}`);
// Only available in Standard SKU and above
if (result.notificationId) {
console.log(`Notification ID: ${result.notificationId}`);
}
预定发送
Push 通知可提前七天使用标准 SKU 命名空间及以上 scheduleNotification 用标签或一般广播发送设备的方法 scheduleBroadcastNotification。返回一个通知ID,必要时可通过 cancelScheduledNotification 方法.
import { NotificationHubsClient, createAppleNotification } from "@azure/notification-hubs";
const client = new NotificationHubsClient("<connection string>", "<hub name>");
const tagExpression = "likes_hockey && likes_football";
const messageBody = `{ "aps" : { "alert" : "Hello" } }`;
// Schedule 8 hours from now
const scheduledTime = new Date(Date.now() + 8 * 60 * 60 * 1000);
const message = createAppleNotification({
body: messageBody,
headers: {
"apns-priority": "10",
"apns-push-type": "alert",
},
});
const result = await client.scheduleNotification(scheduledTime, message, { tagExpression });
console.log(`Tracking ID: ${result.trackingId}`);
console.log(`Correlation ID: ${result.correlationId}`);
// Can be used to cancel via the cancelScheduledSend method
console.log(`Notification ID: ${result.notificationId}`);
采用模块化方法,编码如下:
import { createClientContext, scheduleNotification } from "@azure/notification-hubs/api";
import { createAppleNotification } from "@azure/notification-hubs";
const context = createClientContext("<connection string>", "<hub name>");
const tagExpression = "likes_hockey && likes_football";
const messageBody = `{ "aps" : { "alert" : "Hello" } }`;
// Schedule 8 hours from now
const scheduledTime = new Date(Date.now() + 8 * 60 * 60 * 1000);
const message = createAppleNotification({
body: messageBody,
headers: {
"apns-priority": "10",
"apns-push-type": "alert",
},
});
const result = await scheduleNotification(context, scheduledTime, message, { tagExpression });
console.log(`Tracking ID: ${result.trackingId}`);
console.log(`Correlation ID: ${result.correlationId}`);
// Can be used to cancel via the cancelScheduledSend method
console.log(`Notification ID: ${result.notificationId}`);
解决问题
反应原生支持
React Industrial 目前不支持 [URLSearchParams由Azure通知中心SDK使用 为了在 React Industrial 中使用 SDK, 您需要安装 url-search-params-polyfill 软件包,并在使用 SDK 之前导入.
我们还需要提供多元填充 TextEncoder API 和 Aync 执行器 API. 请看我们的 以 Expo 反应原生样本 更多细节.
已丢弃通知
Azure 通知中心有一个完整的指南, 用于解答已丢弃的通知的故障 在 Azure 通知中心指南中解开通知。 。 。 .
测试发送 支持在 sendNotification 财务报告和审定财务报表 sendBroadcastNotification 方法与方法 enableTestSend 选项 :
import { NotificationHubsClient, createAppleNotification } from "@azure/notification-hubs";
const client = new NotificationHubsClient("<connection string>", "<hub name>");
const tagExpression = "likes_hockey && likes_football";
const messageBody = `{ "aps" : { "alert" : "Hello" } }`;
const notification = createAppleNotification({
body: messageBody,
headers: {
"apns-priority": "10",
"apns-push-type": "alert",
},
});
const result = await client.sendNotification(notification, {
tagExpression,
enableTestSend: true,
});
import { createClientContext, sendNotification } from "@azure/notification-hubs/api";
import { createAppleNotification } from "@azure/notification-hubs";
const context = createClientContext("<connection string>", "<hub name>");
const tagExpression = "likes_hockey && likes_football";
const messageBody = `{ "aps" : { "alert" : "Hello" } }`;
const notification = createAppleNotification({
body: messageBody,
headers: {
"apns-priority": "10",
"apns-push-type": "alert",
},
});
const result = await sendNotification(context, notification, {
tagExpression,
enableTestSend: true,
});
日志
允许伐木可能有助于发现有关失败的有用信息。 为了查看 HTTP 请求和回复的日志,设置 AZURE_LOG_LEVEL 环境变量改为 info。或者,可以在运行时拨打 setLogLevel 输入 @azure/logger数字 :
import { setLogLevel } from "@azure/logger";
setLogLevel("info");
关于如何启用日志的更详细指示,您可以查看 @ azure/ logger 包文件。 。 。 .
今后的步骤
以下样本显示您与 Azure 通知中心互动的各种方式:
设备管理 :
发送操作 :
管理业务:
捐款
如果您想为图书馆捐钱 请读一下 贡献指南 学习如何构建和测试密码.
这个模块的测试是现场测试和单位测试的混合,这需要您有一个Azure通知枢纽的例子. 执行测试需要运行:
pnpm installpnpm build --filter @azure/notification-hubs...- 创建 .env 文件,其中包含这些内容
sdk\notificationhubs\notification-hubs文件夹 :NOTIFICATIONHUBS_CONNECTION_STRING=connection string for your Notification Hubs instanceNOTIFICATION_HUB_NAME=Notification Hub name cd sdk\notificationhubs\notification-hubsnpm run test。 。 。 .
查看我们的 测试 详细文件夹.