Notitie
Voor toegang tot deze pagina is autorisatie vereist. U kunt proberen u aan te melden of de directory te wijzigen.
Voor toegang tot deze pagina is autorisatie vereist. U kunt proberen de mappen te wijzigen.
Azure Notification Hubs bieden een uitgeschaalde push-engine waarmee u meldingen kunt verzenden naar elk platform (Apple, Amazon Kindle, Firebase, Baidu, Xiaomi, Web, Windows, enz.) vanuit elke back-end (cloud of on-premises). Notification Hubs werkt goed voor zowel bedrijfs- als consumentenscenario's. Hier volgen enkele voorbeeldscenario's:
- Stuur het laatste nieuws naar miljoenen mensen met een lage latentie.
- Stuur locatiegebaseerde kortingsbonnen naar geïnteresseerde gebruikerssegmenten.
- Stuur gebeurtenisgerelateerde meldingen naar gebruikers of groepen voor media-/sport-/financiële/gamingtoepassingen.
- Push promotionele inhoud naar applicaties om klanten te betrekken en op de markt te brengen.
- Breng gebruikers op de hoogte van bedrijfsgebeurtenissen, zoals nieuwe berichten en werkitems.
- Verstuur codes voor multi-factor authenticatie.
Sleutelkoppelingen:
OPMERKING: Als u het pakket komt gebruiken azure-sb , raadpleegt u de migration guide to move from azure-sb to @azure/notification-hubs
Aan de slag
Momenteel ondersteunde omgevingen
- LTS-versies van Node.js
- Nieuwste versies van Safari, Chrome, Edge en Firefox.
Zie ons ondersteuningsbeleid voor meer informatie.
Installeer het pakket
npm install @azure/notification-hubs
Vereiste voorwaarden
Een Azure Notification Hubs-resource maken
Een Azure Notification Hub kan op de volgende manieren worden gemaakt:
Nadat de Notification Hub is gemaakt, kan deze worden geconfigureerd met behulp van de Azure Portal of Azure CLI.
De client importeren
Deze SDK voor JavaScript biedt twee manieren voor interactie met Azure Notification Hubs, via de op klassen gebaseerde benadering of met een modulaire ontwerpbenadering. De op klassen gebaseerde benadering is consistent in alle pakketten om een client te maken en vervolgens te communiceren met de methoden op de client.
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);
De modulaire aanpak stelt de ontwikkelaar in staat om te kiezen welke functies moeten worden geïmporteerd, aangezien elke methode afzonderlijk wordt weergegeven. Deze aanpak maakt gebruik van subpath-exports met ES-Modules om de methoden bloot te leggen via directe import. Met de individuele exports zorgt dit voor een betere boomschudervaring en kleinere bundelgroottes waar de ontwikkelaar van kan profiteren.
Houd er rekening mee dat het maken van een client wordt weergegeven via het "@azure/notification-hubs/api" subpad en dat alle clientmethoden worden weergegeven via het "@azure/notification-hubs/api" subpad. Elke geëxporteerde functie neemt de client als eerste parameter en de rest van de parameters blijft ongewijzigd.
De volgende subpaden worden weergegeven:
-
@azure/notification-hubs/api- Het belangrijkste toegangspunt voor de cliënt viacreateClientContexten cliëntmethoden zoalsgetInstallationofsendNotification -
@azure/notification-hubs/models- De modellen en fabrieksmethoden van Notification Hubs.
Het bovenstaande codefragment wordt dan het volgende:
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);
De client verifiëren
Interactie met een Azure Notification Hub begint met de NotificationHubsClient die ondersteuning biedt voor verbindingsreeksen voor Shared Access Signature. Dit omvat de volgende machtigingsniveaus: Luisteren, Beheren, Verzenden.
Met Listen kan een client zichzelf registreren via de Registration and Installations API. Met Verzenden kan de client meldingen verzenden naar apparaten met behulp van de verzend-API's. Ten slotte stelt Manage de gebruiker in staat om registratie- en installatiebeheer uit te voeren, zoals query's.
Een nieuwe NotificationHubsClient client kan worden gemaakt met behulp van de constructor met de connection string en de naam van Notification Hub.
import { NotificationHubsClient } from "@azure/notification-hubs";
const client = new NotificationHubsClient("<connection string>", "<hub name>");
Met behulp van de modulaire aanpak kan het createClientContext via het "@azure/notification-hubs/api" subpad worden geïmporteerd.
import { createClientContext } from "@azure/notification-hubs/api";
const context = createClientContext("<connection string>", "<hub name>");
Belangrijke concepten
Nadat de NotificationHubClient is geïnitialiseerd, kunnen de volgende concepten worden verkend.
- Apparaatbeheer via installaties en registratieBeschrijvingen
- Meldingen naar apparaten sturen
Apparaatbeheer
Apparaatbeheer is een kernconcept voor Notification Hubs om de unieke id van de native Platform Notification Service (PNS), zoals APN's of Firebase, en bijbehorende metagegevens zoals tags die worden gebruikt voor het verzenden van pushmeldingen naar doelgroepen, op te slaan. Dit wordt gedaan met twee API's, de installatie-API, het nieuwere en geprefereerde mechanisme, en registraties.
API voor installaties
Installaties zijn een nieuwere en native JSON-benadering van apparaatbeheer die aanvullende eigenschappen bevat, zoals een installatie-id en gebruikers-ID die kunnen worden gebruikt voor het verzenden naar doelgroepen. De installatie-API heeft op de volgende manieren een aantal voordelen ten opzichte van de bestaande registratie-API's:
- Volledig idempotente API die dus wordt aangeroepen, wordt op de installatie aangemaakt, zodat een bewerking opnieuw kan worden geprobeerd zonder dat u zich zorgen hoeft te maken over duplicaties.
- Ondersteuning voor
userIdeninstallationIdeigenschappen die vervolgens kunnen worden gebruikt in tag-expressies zoals$InstallationId:{myInstallId}en$UserId:{bob@contoso.com}. - Sjablonen maken nu deel uit van de installatie in plaats van een aparte registratie en kunnen op naam worden genoemd als een tag voor verzending.
- Gedeeltelijke updates worden ondersteund via de JSON Patch Standard, waarmee tags kunnen worden toegevoegd en andere gegevens kunnen worden gewijzigd zonder dat u eerst een query op de installatie hoeft uit te voeren.
Installaties kunnen worden gemaakt via de createOrUpdateInstallation volgende methode:
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);
Met behulp van de modulaire aanpak zou de code als volgt zijn:
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);
Een update van een installatie kan worden uitgevoerd via het JSON Patch-schema, zoals het toevoegen van een tag en een gebruikers-ID met behulp van de updateInstallation methode.
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);
Met behulp van de modulaire aanpak zou de code als volgt zijn:
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);
Als u een bestaande installatie wilt ophalen, gebruikt u de getInstallation methode met uw bestaande unieke installatie-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);
Met behulp van de modulaire aanpak zou de code als volgt zijn:
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 voor registraties
Een registratie is gekoppeld aan een PNS, net als de installatie hierboven, met de unieke apparaat-ID van de PNS en bijbehorende tags. Sjablonenregistraties zijn een manier om vooraf gedefinieerde body-sjablonen te maken die vervolgens op het moment van verzenden kunnen worden aangepast met eigenschappen om in te vullen voor het bericht. Zie Documentatie bij sjablonen voor meer informatie over sjablonen.
Een installatie kan op twee manieren worden gemaakt: eerst door een registratie-ID van de server op te halen met behulp getInstallationId van en vervolgens createOrUpdateRegistration of via de createRegistration methode.
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);
Met behulp van de modulaire aanpak zou de code als volgt zijn:
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);
Updates kunnen via de updateRegistration methode worden uitgevoerd, maar in tegenstelling tot installaties worden geen incrementele updates ondersteund. Het opvragen van een bestaande registratie kan met de getRegistration methode.
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);
Met behulp van de modulaire aanpak zou de code als volgt zijn:
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);
Registraties kunnen, in tegenstelling tot installaties, worden opgevraagd om alle registraties op te halen, registraties te koppelen aan een voorwaarde of door tags. Registraties kunnen worden opgevraagd met behulp van de listRegistrations, listRegistrationsByChannel en listRegistrationsByTag methode. Alle methoden ondersteunen begrenzing via de top optie en ondersteunen asynchrone paging.
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));
}
}
Met behulp van de modulaire aanpak zou de code als volgt zijn:
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));
}
}
Verzendbewerkingen
Notification Hubs ondersteunt het verzenden van meldingen naar apparaten, hetzij rechtstreeks met behulp van de unieke PNS-id, met behulp van tags voor het verzenden van het publiek of een algemene uitzending naar alle apparaten. Met behulp van de standaard-SKU en hoger kan de gebruiker met geplande verzending meldingen tot zeven dagen van tevoren plannen. Alle verzendbewerkingen retourneren een tracking-id en correlatie-id die kunnen worden gebruikt voor ondersteuningsaanvragen van Notification Hubs. Met de standaard-SKU en hoger wordt ook een meldings-ID geretourneerd die kan worden gebruikt om meldingstelemetrie via de getNotificationOutcomeDetails methode te krijgen.
Voor foutopsporingsdoeleinden kunnen de enableTestSend opties worden ingesteld op true die onmiddellijke feedback van het PNS over de sendNotification methode krijgt, maar wordt niet ondersteund in productiescenario's. Dit wordt niet ondersteund op de geplande verzendmethoden.
Onbewerkte JSON- of XML-tekenreeksen kunnen worden verzonden naar de verzend- of geplande verzendmethoden, of de meldingsbouwers kunnen worden gebruikt die helpen bij het maken van berichten per PNS, zoals APN's, Firebase, Baidu, ADM en WNS. Deze bouwers bouwen het native berichtformaat, zodat er geen gok is naar welke velden beschikbaar zijn voor elke 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,
});
Uitzending Verzenden
Notification Hubs kunnen worden gebruikt om meldingen te verzenden naar alle geregistreerde apparaten per platform met behulp van broadcast send via de sendBroadcastNotification methode.
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}`);
}
Met behulp van de modulaire aanpak zou de code als volgt zijn:
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}`);
}
Direct Verzenden
Om een apparaat rechtstreeks te verzenden, kan de gebruiker verzenden met behulp van de door het platform verstrekte unieke identificatiecode, zoals APN's apparaattoken, door de sendNotification methode aan te roepen met een deviceHandle parameter.
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}`);
}
Met behulp van de modulaire aanpak zou de code als volgt zijn:
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}`);
}
Publiek Verzenden
Een gebruiker kan niet alleen één apparaat targeten, maar ook meerdere apparaten targeten met behulp van tags. Deze tags kunnen worden geleverd als een lijst met tags, die vervolgens een tag-expressie maakt die overeenkomt met geregistreerde apparaten, of via een tag-expressie die vervolgens Booleaanse logica kan gebruiken om de juiste doelgroep te targeten. Zie Routing en tagexpressies voor meer informatie over tags en tagexpressies.
Als u een tag-expressie wilt maken van een reeks tags, is er een Tag Expression Builder beschikbaar met de createTagExpression methode die wordt weergegeven bij het importeren op het hoogste niveau of @azure/notification-hubs/models/tagExpressionBuilder modulaire import die een "of tag-expressie" van de tags maakt.
import { createTagExpression } from "@azure/notification-hubs";
const tags = ["likes_football", "likes_hockey"];
const tagExpression = createTagExpression(tags);
console.log(tagExpression);
Berichten met tagexpressies kunnen worden verzonden met de volgende code:
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}`);
}
Met behulp van de modulaire aanpak zou de code als volgt zijn:
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}`);
}
Gepland verzenden
Pushmeldingen kunnen tot zeven dagen van tevoren worden gepland met standaard SKU-naamruimten en hoger met behulp van de scheduleNotification methode om naar apparaten met tags of een algemene uitzending met scheduleBroadcastNotification. Dit retourneert een meldings-ID die vervolgens kan worden gebruikt om indien nodig via de cancelScheduledNotification methode te annuleren.
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}`);
Met behulp van de modulaire aanpak zou de code als volgt zijn:
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}`);
Probleemoplossingsproces
React Native-ondersteuning
React Native biedt momenteel geen ondersteuning voor [URLSearchParams], dat wordt gebruikt door de Azure Notification Hubs SDK. Om de SDK in React Native te gebruiken, moet je het url-search-params-polyfill pakket installeren en importeren voordat je de SDK gebruikt.
We moeten ook polyfill leveren voor TextEncoder API en asynchrone iterator-API. Bekijk ons React Native-voorbeeld met Expo voor meer details.
Diagnose van verwijderde meldingen
Azure Notification Hubs heeft een volledige handleiding voor het oplossen van problemen met verwijderde meldingen in de handleiding Ingetrokken meldingen diagnosticeren in Azure Notification Hubs.
Testverzending wordt ondersteund ondersteund in de sendNotification en sendBroadcastNotification methoden met de enableTestSend optie:
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,
});
Loggen
Het inschakelen van logboekregistratie kan helpen nuttige informatie over fouten te ontdekken. Als u een logboek met HTTP-aanvragen en -antwoorden wilt zien, stelt u de omgevingsvariabele AZURE_LOG_LEVEL in op info. U kunt logboekregistratie ook tijdens runtime inschakelen door setLogLevel aan te roepen in de @azure/logger:
import { setLogLevel } from "@azure/logger";
setLogLevel("info");
Voor gedetailleerdere instructies over het inschakelen van logboeken, kunt u de documentatie over het @azure/logger-pakket bekijken.
Volgende stappen
In de volgende voorbeelden ziet u de verschillende manieren waarop u kunt communiceren met Azure Notification Hubs:
Apparaat beheer:
- API voor installaties
- Registratie API
Bewerkingen verzenden:
- Uitzending Verzenden
- Direct Verzenden
- Publiek Verzenden met tags Lijst
- Publiek verzenden met tag-expressie
- Geplande uitzending verzenden
- Gepland verzenden
Beheer operaties:
Contributing
Als u een bijdrage wilt leveren aan deze bibliotheek, leest u de gids voor bijdragen voor meer informatie over het bouwen en testen van de code.
De tests van deze module zijn een combinatie van live- en eenheidstests, waarvoor u een Azure Notification Hubs-exemplaar moet hebben. Om de tests uit te voeren, moet u het volgende uitvoeren:
pnpm installpnpm build --filter @azure/notification-hubs...- Maak een .env-bestand met de volgende inhoud in de
sdk\notificationhubs\notification-hubsmap:NOTIFICATIONHUBS_CONNECTION_STRING=connection string for your Notification Hubs instanceNOTIFICATION_HUB_NAME=Notification Hub name cd sdk\notificationhubs\notification-hubs-
npm run test.
Bekijk onze testmap voor meer details.
Verwante projecten
Azure SDK for JavaScript