使用 Azure 通知中心和 Node.js 发送推送通知Sending push notifications with Azure Notification Hubs and Node.js

概述Overview

Important

要完成本教程,必须有一个有效的 Azure 帐户。To complete this tutorial, you must have an active Azure account. 如果没有帐户,可以创建一个试用帐户,只需几分钟即可完成。If you don't have an account, you can create a trial account in just a couple of minutes. 有关详细信息,请参阅 Azure 1 元试用For details, see Azure 1rmb-trial.

本指南介绍如何借助 Azure 通知中心,直接从 Node.js 应用程序发送推送通知。This guide shows you how to send push notifications with the help of Azure Notification Hubs directly from a Node.js application.

涵盖的方案包括在下列平台将推送通知发送到应用程序:The scenarios covered include sending push notifications to applications on the following platforms:

  • AndroidAndroid
  • iOSiOS
  • 通用 Windows 平台Universal Windows Platform
  • Windows PhoneWindows Phone

通知中心Notification Hubs

Azure 通知中心提供用于向移动设备发送推送通知的易于使用、多平台且可缩放的基础结构。Azure Notification Hubs provide an easy-to-use, multi-platform, scalable infrastructure for sending push notifications to mobile devices. 有关服务基础结构的详细信息,请参阅 Azure 通知中心 页。For details on the service infrastructure, see the Azure Notification Hubs page.

创建 Node.js 应用程序Create a Node.js Application

本教程的第一步是创建新的空白 Node.js 应用程序。The first step in this tutorial is creating a new blank Node.js application. 有关创建 Node.js 应用程序的说明,请参阅使用 Windows PowerShell 创建 Node.js 应用程序并将其部署到 Azure 网站, Node.js Cloud Service使用 WebMatrix 创建网站。For instructions on creating a Node.js application, see Create and deploy a Node.js application to Azure Web Site, Node.js Cloud Service using Windows PowerShell, or Web Site with WebMatrix.

将应用程序配置为使用通知中心Configure Your Application to Use Notification Hubs

若要使用 Azure 通知中心,请下载和使用 Node.js azure 包,其中包括一组可与推送通知 REST 服务通信的内置帮助程序库。To use Azure Notification Hubs, you need to download and use the Node.js azure package, which includes a built-in set of helper libraries that communicate with the push notification REST services.

使用 Node 包管理器 (NPM) 可获取该程序包Use Node Package Manager (NPM) to obtain the package

  1. 使用 PowerShell (Windows)、Terminal (Mac) 或 Bash (Linux) 等命令行接口导航到在其中创建了空白应用程序的文件夹 。Use a command-line interface such as PowerShell (Windows), Terminal (Mac), or Bash (Linux) and navigate to the folder where you created your blank application.
  2. 在命令窗口中执行 npm install azure-sbExecute npm install azure-sb in the command window.
  3. 可以手动运行 lsdir 命令来验证是否创建了 node_modules 文件夹。You can manually run the ls or dir command to verify that a node_modules folder was created.
  4. 在该文件夹中,找到 azure 包,其中包含访问通知中心所需的库。Inside that folder, find the azure package, which contains the libraries you need to access the Notification Hub.

Note

可以在官方 NPM 博客中了解有关安装 NPM 的详细信息。You can learn more about installing NPM on the official NPM blog.

导入模块Import the module

使用文本编辑器将以下内容添加到应用程序的 server.js 文件的顶部:Using a text editor, add the following to the top of the server.js file of the application:

var azure = require('azure-sb');

设置 Azure 通知中心连接Set up an Azure Notification Hub connection

可以通过 NotificationHubService 对象使用通知中心。The NotificationHubService object lets you work with notification hubs. 以下代码为名为 hubname 的通知中心创建 NotificationHubService 对象。The following code creates a NotificationHubService object for the notification hub named hubname. 将它添加到靠近 server.js 文件顶部、用于导入 Azure 模块的语句之后的位置:Add it near the top of the server.js file, after the statement to import the azure module:

var notificationHubService = azure.createNotificationHubService('hubname','connectionstring');

通过执行以下步骤从 Azure 门户 获取连接 connectionstring 值:Obtain the connection connectionstring value from the Azure portal by performing the following steps:

  1. 在左侧导航窗格中,单击“浏览” 。In the left navigation pane, click Browse.
  2. 选择“通知中心” ,并找到要用于示例的中心。Select Notification Hubs, and then find the hub you wish to use for the sample. 如果在创建新通知中心时需要帮助,可以参阅 Windows 应用商店入门教程You can refer to the Windows Store Getting Started tutorial if you need help with creating a new Notification Hub.
  3. Select Settings.
  4. 单击“访问策略” 。Click on Access Policies. 会看到共享连接字符串和完全访问连接字符串。You see both shared and full access connection strings.

Azure 门户 — 通知中心

Note

还可以使用 Azure PowerShell 提供的 Get-AzureSbNamespace cmdlet 或者在 Azure 命令行接口 (Azure CLI) 中使用 azure sb namespace show 命令检索连接字符串 。You can also retrieve the connection string using the Get-AzureSbNamespace cmdlet provided by Azure PowerShell or the azure sb namespace show command with the Azure Command-Line Interface (Azure CLI).

一般体系结构General architecture

NotificationHubService 对象公开以下对象实例,以便向特定设备和应用程序发送推送通知:The NotificationHubService object exposes the following object instances for sending push notifications to specific devices and applications:

  • iOS - 使用可在 notificationHubService.apns 访问的 ApnsService 对象iOS - use the ApnsService object, which is accessible at notificationHubService.apns
  • Windows Phone - 使用可在 notificationHubService.mpns 获得的 MpnsService 对象Windows Phone - use the MpnsService object, which is available at notificationHubService.mpns
  • 通用 Windows 平台 - 使用可在 notificationHubService.wns 获得的 WnsService 对象Universal Windows Platform - use the WnsService object, which is available at notificationHubService.wns

如何:向 iOS 应用程序发送推送通知How to: Send push notifications to iOS applications

与上述 Android 应用程序一样,ApnsService 对象提供可用于将推送通知发送到 iOS 应用程序的 send 方法。Same as with Android applications described above, the ApnsService object provides a send method that can be used to send push notifications to iOS applications. send 方法接受以下参数:The send method accepts the following parameters:

  • Tags - 标记标识符。Tags - the tag identifier. 如果没有提供任何标记,通知会发送给所有客户端。If no tag is provided, the notification is sent to all clients.
  • Payload - 消息的 JSON 或字符串的有效负载。Payload - the message's JSON or string payload.
  • Callback - 回调函数。Callback - the callback function.

有关有效负载格式的详细信息,请参阅 Local and Push Notification Programming Guide(本地通知和推送通知编程指南)文档中的通知有效负载部分 。For more information the payload format, see The Notification Payload section of the Local and Push Notification Programming Guide document.

以下代码使用由 NotificationHubService 公开的 ApnsService 实例将警报消息发送给所有客户端:The following code uses the ApnsService instance exposed by the NotificationHubService to send an alert message to all clients:

var payload={
    alert: 'Hello!'
  };
 notificationHubService.apns.send(null, payload, function(error){
   if(!error){
      // notification sent
    }
  });

如何:向 Windows Phone 应用程序发送推送通知How to: Send push notifications to Windows Phone applications

MpnsService 对象提供可用于将推送通知发送到 Windows Phone 应用程序的 send 方法。The MpnsService object provides a send method that can be used to send push notifications to Windows Phone applications. send 方法接受以下参数:The send method accepts the following parameters:

  • Tags - 标记标识符。Tags - the tag identifier. 如果没有提供任何标记,通知会发送给所有客户端。If no tag is provided, the notification is sent to all clients.
  • Payload - 消息的 XML 有效负载。Payload - the message's XML payload.
  • TargetName - toast 用于 toast 通知 。TargetName - toast for toast notifications. token 表示磁贴通知。token for tile notifications.
  • NotificationClass - 通知的优先级。NotificationClass - The priority of the notification. 有关该参数的有效值,请参阅 Push notifications from a server(从服务器推送通知)文档中的 HTTP Header Elements(HTTP 标头元素)部分 。See the HTTP Header Elements section of the Push notifications from a server document for valid values.
  • Options - 可选的请求标头。Options - optional request headers.
  • Callback - 回调函数。Callback - the callback function.

有关有效的 TargetNameNotificationClass 和标头选项的列表,请查看从服务器推送通知页面。For a list of valid TargetName, NotificationClass and header options, check out the Push notifications from a server page.

以下示例代码使用由 NotificationHubService 公开的 MpnsService 实例发送 toast 推送通知:The following sample code uses the MpnsService instance exposed by the NotificationHubService to send a toast push notification:

var payload = '<?xml version="1.0" encoding="utf-8"?><wp:Notification xmlns:wp="WPNotification"><wp:Toast><wp:Text1>string</wp:Text1><wp:Text2>string</wp:Text2></wp:Toast></wp:Notification>';
notificationHubService.mpns.send(null, payload, 'toast', 22, function(error){
  if(!error){
    //notification sent
   }
  });

如何:向通用 Windows 平台 (UWP) 应用程序发送推送通知How to: Send push notifications to Universal Windows Platform (UWP) applications

WnsService 对象提供可用于将推送通知发送到通用 Windows 平台应用程序的 send 方法。The WnsService object provides a send method that can be used to send push notifications to Universal Windows Platform applications. send 方法接受以下参数:The send method accepts the following parameters:

  • Tags - 标记标识符。Tags - the tag identifier. 如果没有提供任何标记,通知会发送给所有已注册的客户端。If no tag is provided, the notification is sent to all registered clients.
  • Payload - XML 消息有效负载。Payload - the XML message payload.
  • Type - 通知类型。Type - the notification type.
  • Options - 可选的请求标头。Options - optional request headers.
  • Callback — 回调函数。Callback - the callback function.

若要了解有效的类型和请求标头的列表,请参阅 推送通知服务请求和响应头For a list of valid types and request headers, see Push notification service request and response headers.

以下示例代码使用由 NotificationHubService 公开的 WnsService 实例将 toast 推送通知发送给 UWP 应用:The following code uses the WnsService instance exposed by the NotificationHubService to send a toast push notification to a UWP app:

var payload = '<toast><visual><binding template="ToastText01"><text id="1">Hello!</text></binding></visual></toast>';
notificationHubService.wns.send(null, payload , 'wns/toast', function(error){
   if(!error){
       // notification sent
     }
   });

后续步骤Next Steps

使用上述示例代码段,可以轻松地构建服务基础结构,将推送通知传递到各种设备。The sample snippets above allow you to easily build service infrastructure to deliver push notifications to a wide variety of devices. 了解使用通知中心和 node.js 的基础知识之后,请参考下列链接以了解有关如何进一步扩展这些功能的详细信息。Now that you've learned the basics of using Notification Hubs with node.js, follow these links to learn more about how you can extend these capabilities further.