共用方式為


適用於 JavaScript 的 Azure 通知中樞 SDK

Azure 通知中樞提供向外延展推播引擎,可讓您從任何後端 (雲端或內部部署) 將通知傳送至任何平台 (Apple、Amazon Kindle、Firebase、百度、小米、Web、Windows 等)。 通知中樞適用於企業和取用者案例。 以下是一些範例案例:

  • 以低延遲向數百萬人發送突發新聞通知。
  • 向感興趣的用戶群發送基於位置的優惠券。
  • 向媒體/體育/金融/遊戲應用程序的用戶或組發送與事件相關的通知。
  • 將促銷內容推送到應用程序,以吸引客戶並向客戶進行營銷。
  • 通知使用者企業事件,例如新訊息和工作專案。
  • 傳送多重要素驗證的代碼。

主要連結:

注意:如果您來自使用該 azure-sb 套件,請參閱 migration guide to move from azure-sb to @azure/notification-hubs

入門指南

目前支援的環境

如需詳細資訊,請參閱我們的支援原則

安裝套件

npm install @azure/notification-hubs

先決條件

建立 Azure 通知中樞資源

您可以使用下列方法建立 Azure 通知中樞:

  1. Azure 入口網站
  2. Azure CLI
  3. 肱二頭肌
  4. ARM 範本

建立之後,您可以使用 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 - 用戶端 via 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>");

使用模組化方法,可以透過子路徑匯"@azure/notification-hubs/api"入。createClientContext

import { createClientContext } from "@azure/notification-hubs/api";

const context = createClientContext("<connection string>", "<hub name>");

重要概念

初始化之後 NotificationHubClient ,可以探索下列概念。

  • 透過安裝和註冊進行裝置管理說明
  • 傳送通知至裝置

裝置管理

裝置管理是通知中樞的核心概念,能夠儲存原生平台通知服務 (PNS) 的唯一識別碼,例如 APN 或 Firebase,以及相關聯的中繼資料,例如用來將推播通知傳送給物件的標籤。 這是透過兩個 API 完成的,安裝 API 是較新且偏好的機制,以及註冊。

安裝 API

安裝是裝置管理的較新原生JSON方法,其中包含其他屬性,例如安裝ID和使用者ID,可用於傳送給對象。 與現有的註冊 API 相比,安裝 API 在下列方面具有一些優點:

  • 完全冪等的 API,因此在安裝時呼叫 create,因此可以重試操作,而不必擔心重複。
  • 支援 userIdinstallationId 屬性,然後可用於標籤運算式,例如 $InstallationId:{myInstallId}$UserId:{bob@contoso.com}
  • 範本現在是安裝的一部分,而不是單獨的註冊,並且可以依名稱作為傳送的標籤進行參考。
  • 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 修補程式結構描述進行安裝更新,例如使用該 updateInstallation 方法新增標籤和使用者 ID。

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: "bob@contoso.com" },
];

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: "bob@contoso.com" },
];

const installation = await updateInstallation(context, installationId, updates);

若要擷取現有的安裝,請使用具有 getInstallation 您現有唯一安裝 ID 的方法。

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 中的唯一裝置識別碼和相關聯的標籤相關聯。 範本註冊是建立預先定義內文範本的一種方式,然後可以在傳送時使用屬性進行自訂,以填入訊息。 如需範本的詳細資訊,請參閱 範本文件

安裝可以透過兩種方式之一建立,首先是使用 和 createOrUpdateRegistrationgetInstallationId透過方法createRegistration從伺服器取得註冊 ID。

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);

與安裝不同,可以查詢註冊以取得所有註冊、將註冊與條件比對,或依標籤進行。 可以使用 和 listRegistrationsByChannellistRegistrationsByTag 方法查詢listRegistrations註冊。 所有方法都支援透過選項進行 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 和更新版本時, 排程傳送 可讓使用者最多提前 7 天排程通知。 所有傳送作業都會傳回追蹤識別碼和相互關聯識別碼,以用於通知中樞支援案例。 使用標準 SKU 和更新版本時,也會傳回通知識別碼,可用來透過方法 getNotificationOutcomeDetails 取得通知遙測。

為了偵錯目的, enableTestSend 可以設定選項, true 以從方法的 sendNotification PNS 立即取得意見反應,不過,生產案例不支援。 排程的傳送方法不支援此功能。

原始 JSON 或 XML 字串可以傳送至傳送或排程傳送方法,也可以使用通知產生器來協助建構每個 PNS 的訊息,例如 APNs、Firebase、百度、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}`);
}

排程傳送

推播通知最多可提前七天排程,使用標準SKU命名空間及更新版本,使用方法 scheduleNotification 傳送至具有標籤的裝置,或使用 scheduleBroadcastNotification。 這會傳回通知識別碼,然後可在必要時透過方法 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 原生支持

React Native 目前不支援 Azure 通知中樞 SDK 所使用的 [URLSearchParams]。 為了在 React Native 中使用 SDK,您需要在使用 SDK 之前安裝 url-search-params-polyfill 套件並匯入它。

我們還需要為 API 和非同步迭代器 API 提供 TextEncoder polyfill。 請參閱我們的 React Native 範例與 Expo 以取得更多詳細資訊。

診斷丟棄的通知

Azure 通知中樞在診斷 Azure 通知中樞中捨棄的通知指南中,有針對卸除通知問題進行疑難排解的完整指南。

支援測試傳送,並在 和 sendNotificationsendBroadcastNotification 方法中支援,並具有選項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/記錄器套件檔。

後續步驟

下列範例示範與 Azure 通知中樞互動的各種方式:

設備管理:

發送操作:

管理作業:

Contributing

如果您想要參與此連結庫,請閱讀 參與指南 ,以深入瞭解如何建置和測試程序代碼。

本課程模組的測試是即時測試和單元測試的混合,這需要您擁有 Azure 通知中樞執行個體。 若要執行測試,您需要執行:

  1. pnpm install
  2. pnpm build --filter @azure/notification-hubs...
  3. 在資料夾中 sdk\notificationhubs\notification-hubs 建立包含下列內容的 .env 檔案: NOTIFICATIONHUBS_CONNECTION_STRING=connection string for your Notification Hubs instanceNOTIFICATION_HUB_NAME=Notification Hub name
  4. cd sdk\notificationhubs\notification-hubs
  5. npm run test

查看我們的 測試 文件夾以了解更多詳細信息。