Catatan
Akses ke halaman ini memerlukan otorisasi. Anda dapat mencoba masuk atau mengubah direktori.
Akses ke halaman ini memerlukan otorisasi. Anda dapat mencoba mengubah direktori.
Azure Notification Hubs menyediakan mesin push yang diskalakan yang memungkinkan Anda mengirim pemberitahuan ke platform apa pun (Apple, Amazon Kindle, Firebase, Baidu, Xiaomi, Web, Windows, dll.) dari back-end apa pun (cloud atau lokal). Pusat Pemberitahuan berfungsi dengan baik untuk skenario perusahaan dan konsumen. Berikut adalah beberapa contoh skenario:
- Kirim pemberitahuan berita terkini ke jutaan orang dengan latensi rendah.
- Kirim kupon berbasis lokasi ke segmen pengguna yang tertarik.
- Kirim notifikasi terkait acara ke pengguna atau grup untuk aplikasi media/olahraga/keuangan/game.
- Dorong konten promosi ke aplikasi untuk melibatkan dan memasarkan kepada pelanggan.
- Beri tahu pengguna tentang peristiwa perusahaan seperti pesan baru dan item kerja.
- Kirim kode untuk autentikasi multifaktor.
Tautan kunci:
CATATAN: Jika Anda berasal dari menggunakan azure-sb paket, lihat migration guide to move from azure-sb to @azure/notification-hubs
Memulai Langkah Pertama
Lingkungan yang didukung saat ini
- Versi LTS dari Node.js
- Versi terbaru Safari, Chrome, Edge, dan Firefox.
Lihat kebijakan dukungan kami untuk detail selengkapnya.
Pasang paketnya
npm install @azure/notification-hubs
Prasyarat
- Langganan Azure
- Sumber daya App Notification Hubs .
Membuat sumber daya Azure Notification Hubs
Azure Notification Hub dapat dibuat menggunakan metode berikut:
Setelah dibuat, Pusat Pemberitahuan dapat dikonfigurasi menggunakan Portal Portal Azure atau Azure CLI.
Mengimpor Klien
SDK untuk JavaScript ini menawarkan dua cara untuk berinteraksi dengan Azure Notification Hubs, baik melalui pendekatan berbasis kelas, atau dengan pendekatan desain modular. Pendekatan berbasis kelas konsisten di semua paket untuk membuat klien dan kemudian berinteraksi dengan metode pada klien.
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);
Pendekatan modular memungkinkan pengembang untuk memilih dan memilih fungsi mana yang akan diimpor karena setiap metode diekspos satu per satu. Pendekatan ini menggunakan subpath-exports dengan ES-Modules untuk mengekspos metode melalui impor langsung. Dengan ekspor individual, ini menciptakan pengalaman mengguncang pohon yang lebih baik dan ukuran bundel yang lebih kecil yang dapat dimanfaatkan oleh pengembang.
Perhatikan bahwa membuat klien diekspos melalui "@azure/notification-hubs/api" subpath dan semua metode klien diekspos melalui "@azure/notification-hubs/api" subjalur. Setiap fungsi yang diekspor mengambil client parameter pertama dan parameter lainnya tetap tidak berubah.
Subjalur berikut diekspos:
-
@azure/notification-hubs/api- Titik masuk utama untuk klien melaluicreateClientContextdan metode klien sepertigetInstallationatausendNotification -
@azure/notification-hubs/models- Model Hub Pemberitahuan dan metode pabrik.
Cuplikan kode di atas kemudian menjadi sebagai berikut:
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);
Mengautentikasi klien
Interaksi dengan Azure Notification Hub dimulai dengan yang NotificationHubsClient mendukung string koneksi Tanda Tangan Akses Bersama. Ini termasuk tingkat izin berikut: Dengarkan, Kelola, Kirim.
Dengarkan memungkinkan klien untuk mendaftarkan dirinya sendiri melalui API Pendaftaran dan Penginstalan. Send memungkinkan klien mengirim notifikasi ke perangkat menggunakan API pengiriman. Terakhir, Kelola memungkinkan pengguna untuk melakukan manajemen Pendaftaran dan Instalasi, seperti kueri.
Klien baru NotificationHubsClient dapat dibuat menggunakan konstruktor dengan string koneksi dan nama Notification Hub.
import { NotificationHubsClient } from "@azure/notification-hubs";
const client = new NotificationHubsClient("<connection string>", "<hub name>");
Dengan menggunakan pendekatan modular, dapat createClientContext diimpor melalui "@azure/notification-hubs/api" subpath.
import { createClientContext } from "@azure/notification-hubs/api";
const context = createClientContext("<connection string>", "<hub name>");
Konsep utama
Setelah NotificationHubClient diinisialisasi, konsep berikut dapat dieksplorasi.
- Manajemen Perangkat melalui Instalasi dan PendaftaranDeskripsi
- Mengirim Notifikasi ke Perangkat
Pengelolaan Perangkat
Pengelolaan perangkat adalah konsep inti dari Notification Hubs untuk dapat menyimpan ID unik dari Platform Notification Service (PNS) native seperti APN atau Firebase, dan metadata terkait seperti tag yang digunakan untuk mengirim notifikasi push ke audiens. Ini dilakukan dengan dua API, Installation API yang merupakan mekanisme yang lebih baru dan lebih disukai, dan Registrations.
API Instalasi
Penginstalan adalah pendekatan JSON yang lebih baru dan asli untuk manajemen perangkat yang berisi properti tambahan seperti ID penginstalan dan ID pengguna yang dapat digunakan untuk mengirim ke audiens. API penginstalan memiliki beberapa keunggulan dibandingkan API Pendaftaran yang ada dengan cara berikut:
- API sepenuhnya idempoten sehingga memanggil create pada instalasi, sehingga operasi dapat dicoba kembali tanpa khawatir tentang duplikasi.
- Dukungan untuk
userIddaninstallationIdproperti yang kemudian dapat digunakan dalam ekspresi tag seperti$InstallationId:{myInstallId}dan$UserId:{bob@contoso.com}. - Templat sekarang menjadi bagian dari instalasi, bukan pendaftaran terpisah dan dapat direferensikan berdasarkan nama sebagai tag untuk pengiriman.
- Pembaruan parsial didukung melalui Standar Patch JSON, yang memungkinkan untuk menambahkan tag dan mengubah data lain tanpa harus terlebih dahulu mengkueri penginstalan.
Instalasi dapat dibuat melalui createOrUpdateInstallation metode seperti berikut:
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);
Dengan menggunakan pendekatan modular, kodenya adalah sebagai berikut:
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);
Pembaruan penginstalan dapat dilakukan melalui skema JSON Patch seperti menambahkan tag dan ID pengguna menggunakan metode tersebut 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: "bob@contoso.com" },
];
const installation = await client.updateInstallation(installationId, updates);
Dengan menggunakan pendekatan modular, kodenya adalah sebagai berikut:
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);
Untuk mengambil penginstalan yang ada, gunakan metode dengan getInstallation ID penginstalan unik yang ada.
import { NotificationHubsClient } from "@azure/notification-hubs";
const client = new NotificationHubsClient("<connection string>", "<hub name>");
const installationId = "<unique installation ID>";
const installation = client.getInstallation(installationId);
Dengan menggunakan pendekatan modular, kodenya adalah sebagai berikut:
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 Pendaftaran
Pendaftaran dikaitkan dengan PNS seperti penginstalan di atas, dengan pengidentifikasi perangkat unik dari PNS, dan tag terkait. Pendaftaran templat adalah cara membuat templat isi yang telah ditentukan sebelumnya yang kemudian dapat disesuaikan pada waktu pengiriman dengan properti untuk diisi pesan. Untuk informasi selengkapnya tentang templat, lihat Dokumentasi templat.
Instalasi dapat dibuat dengan salah satu dari dua cara, pertama dengan mendapatkan ID pendaftaran dari server menggunakan getInstallationId dan kemudian createOrUpdateRegistration atau melalui metode tersebut 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);
Dengan menggunakan pendekatan modular, kodenya adalah sebagai berikut:
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);
Pembaruan dapat dilakukan melalui metode tetapi updateRegistration tidak seperti instalasi, tidak mendukung pembaruan bertahap. Permintaan untuk pendaftaran yang ada dapat dilakukan dengan metode ini 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);
Dengan menggunakan pendekatan modular, kodenya adalah sebagai berikut:
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);
Pendaftaran, tidak seperti penginstalan, dapat dikueri untuk mendapatkan semua pendaftaran, mencocokkan pendaftaran dengan suatu kondisi, atau dengan tag. Pendaftaran dapat dikueri menggunakan listRegistrationsmetode , listRegistrationsByChannel dan listRegistrationsByTag . Semua metode mendukung pembatasan melalui top opsi dan mendukung paging asinkron.
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));
}
}
Dengan menggunakan pendekatan modular, kodenya adalah sebagai berikut:
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));
}
}
Kirim Operasi
Notification Hubs mendukung pengiriman notifikasi ke perangkat baik secara langsung menggunakan ID unik yang disediakan PNS, menggunakan tag untuk pengiriman audiens, atau siaran umum ke semua perangkat. Dengan menggunakan SKU Standar dan yang lebih baru, pengiriman terjadwal memungkinkan pengguna menjadwalkan notifikasi hingga tujuh hari sebelumnya. Semua operasi pengiriman mengembalikan ID Pelacakan dan ID Korelasi yang dapat digunakan untuk kasus dukungan Notification Hubs. Dengan SKU Standar dan di atasnya, ID Pemberitahuan juga ditampilkan yang dapat digunakan untuk mendapatkan telemetri pemberitahuan melalui getNotificationOutcomeDetails metode.
Untuk tujuan penelusuran kesalahan, enableTestSend opsi dapat diatur untuk true mendapatkan umpan balik langsung dari PNS tentang metode tersebut sendNotification , namun, tidak didukung dalam skenario produksi. Ini tidak didukung pada metode pengiriman terjadwal.
String JSON atau XML mentah dapat dikirim ke metode pengiriman atau pengiriman terjadwal, atau pembuat notifikasi dapat digunakan yang membantu membuat pesan per PNS seperti APN, Firebase, Baidu, ADM, dan WNS. Pembuat ini akan membangun format pesan asli sehingga tidak ada yang menebak bidang mana yang tersedia untuk setiap 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,
});
Kirim Siaran
Hub Pemberitahuan dapat digunakan untuk mengirim pemberitahuan ke semua perangkat terdaftar per platform menggunakan siaran pengiriman melalui metode tersebut 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}`);
}
Dengan menggunakan pendekatan modular, kodenya adalah sebagai berikut:
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}`);
}
Kirim Langsung
Untuk mengirim perangkat secara langsung, pengguna dapat mengirim menggunakan pengidentifikasi unik yang disediakan platform seperti token perangkat APN dengan memanggil metode dengan sendNotification parameter 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}`);
}
Dengan menggunakan pendekatan modular, kodenya adalah sebagai berikut:
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}`);
}
Pengiriman Audiens
Selain menargetkan satu perangkat, pengguna dapat menargetkan beberapa perangkat menggunakan tag. Tag ini dapat disediakan sebagai daftar tag, yang kemudian membuat ekspresi tag agar sesuai dengan perangkat terdaftar, atau melalui ekspresi tag yang kemudian dapat menggunakan logika Boolean untuk menargetkan audiens yang tepat. Untuk informasi selengkapnya tentang tag dan ekspresi tag, lihat Perutean dan Ekspresi Tag.
Jika Anda ingin membuat ekspresi tag dari array tag, ada Pembuat Ekspresi Tag yang tersedia dengan createTagExpression metode yang diekspos pada impor tingkat atas atau @azure/notification-hubs/models/tagExpressionBuilder impor modular yang membuat "atau ekspresi tag" dari tag.
import { createTagExpression } from "@azure/notification-hubs";
const tags = ["likes_football", "likes_hockey"];
const tagExpression = createTagExpression(tags);
console.log(tagExpression);
Pesan ekspresi tag dapat dikirim menggunakan kode berikut:
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}`);
}
Dengan menggunakan pendekatan modular, kodenya adalah sebagai berikut:
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}`);
}
Pengiriman Terjadwal
Pemberitahuan push dapat dijadwalkan hingga tujuh hari sebelumnya dengan namespace SKU Standar dan yang lebih tinggi menggunakan scheduleNotification metode untuk mengirim ke perangkat dengan tag atau siaran umum dengan scheduleBroadcastNotification. Ini mengembalikan ID pemberitahuan yang kemudian dapat digunakan untuk membatalkan jika perlu melalui cancelScheduledNotification metode.
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}`);
Dengan menggunakan pendekatan modular, kodenya adalah sebagai berikut:
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}`);
Troubleshooting
Dukungan React Native
React Native saat ini tidak memiliki dukungan untuk [URLSearchParams] yang digunakan oleh Azure Notification Hubs SDK. Untuk menggunakan SDK di React Native, Anda harus menginstal url-search-params-polyfill paket dan mengimpornya sebelum menggunakan SDK.
Kita juga perlu menyediakan polyfill untuk TextEncoder API dan API iterator asinkron. Silakan lihat sampel React Native kami dengan Expo untuk detail lebih lanjut.
Mendiagnosis Notifikasi yang Terputus
Azure Notification Hubs memiliki panduan lengkap untuk memecahkan masalah dengan pemberitahuan yang terputus di Panduan Diagnosis pemberitahuan terputus di Azure Notification Hubs.
Pengiriman pengujian didukung dalam sendNotification metode dan sendBroadcastNotification dengan enableTestSend opsi:
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,
});
Penebangan kayu
Mengaktifkan pengelogan dapat membantu menemukan informasi yang berguna tentang kegagalan. Untuk melihat log permintaan dan respons HTTP, atur variabel lingkungan AZURE_LOG_LEVEL ke info. Atau, pengelogan dapat diaktifkan saat runtime dengan memanggil setLogLevel di @azure/logger:
import { setLogLevel } from "@azure/logger";
setLogLevel("info");
Untuk instruksi lebih rinci tentang cara mengaktifkan log, Anda dapat melihat dokumen paket @azure/logger.
Langkah selanjutnya
Contoh berikut menunjukkan kepada Anda berbagai cara Anda dapat berinteraksi dengan Azure Notification Hubs:
Manajemen Perangkat:
- API Instalasi
- API Pendaftaran
Kirim Operasi:
- Kirim Siaran
- Kirim Langsung
- Daftar Audiens Kirim Dengan Tag
- Audiens Kirim Dengan Ekspresi Tag
- Pengiriman Siaran Terjadwal
- Pengiriman Terjadwal
Operasi Manajemen:
Contributing
Jika Anda ingin berkontribusi pada pustaka ini, baca panduan berkontribusi untuk mempelajari selengkapnya tentang cara membuat dan menguji kode.
Pengujian modul ini adalah campuran pengujian langsung dan unit, yang mengharuskan Anda memiliki instans Azure Notification Hubs. Untuk menjalankan pengujian, Anda harus menjalankan:
pnpm installpnpm build --filter @azure/notification-hubs...- Buat file .env dengan konten ini di
sdk\notificationhubs\notification-hubsfolder:NOTIFICATIONHUBS_CONNECTION_STRING=connection string for your Notification Hubs instanceNOTIFICATION_HUB_NAME=Notification Hub name cd sdk\notificationhubs\notification-hubs-
npm run test.
Lihat folder pengujian kami untuk detail selengkapnya.
Proyek terkait
Azure SDK for JavaScript