在 Amazon SNS 中管理订阅 - Amazon SDK for JavaScript
Amazon Web Services 文档中描述的 Amazon Web Services 服务或功能可能因区域而异。要查看适用于中国区域的差异,请参阅 中国的 Amazon Web Services 服务入门 (PDF)

Amazon SDK for JavaScript V3 API 参考指南详细描述了 Amazon SDK for JavaScript 版本 3 (V3) 的所有 API 操作。

本文属于机器翻译版本。若本译文内容与英语原文存在差异,则一律以英文原文为准。

在 Amazon SNS 中管理订阅

JavaScript code example that applies to Node.js execution

此 Node.js 代码示例演示:

  • 如何列出对 Amazon SNS 主题的所有订阅。

  • 如何将电子邮件地址、应用程序端点或 Amazon Lambda 函数订阅到 Amazon SNS 主题。

  • 如何从 Amazon SNS 主题取消订阅。

情景

在本示例中,您使用一系列 Node.js 模块将通知消息发布到 Amazon SNS 主题。Node.js 模块使用 SDK for JavaScript,通过 SNS 客户端类的以下方法管理主题:

先决条件任务

要设置和运行此示例,您必须先完成以下任务:

  • 设置项目环境以运行这些 Node TypeScript 示例,并安装所需的 Amazon SDK for JavaScript 和第三方模块。请按照 GitHub 上的说明进行操作。

  • 使用用户凭证创建共享配置文件。有关提供共享凭证文件的更多信息,请参阅《Amazon SDK 和工具参考指南》 中的共享配置和凭证文件

重要

这些示例演示了如何使用 ECMAScript6 (ES6) 导入/导出客户端服务对象和命令。

列出对主题的订阅

在本示例中,使用 Node.js 模块以列出对 Amazon SNS 主题的所有订阅。

创建一个 libs 目录,然后使用文件名 snsClient.js 创建一个 Node.js 模块。将以下代码复制并粘贴到其中,这将创建 Amazon SNS 客户端对象。将 REGION 替换为您的 Amazon 区域。

import { SNSClient } from "@aws-sdk/client-sns"; // The AWS Region can be provided here using the `region` property. If you leave it blank // the SDK will default to the region set in your AWS config. export const snsClient = new SNSClient({});

此示例代码可在 GitHub 上的此处找到。

创建文件名为 list-subscriptions-by-topic.js 的 Node.js 模块。按前面所示配置 SDK。

创建一个对象,其中包含您要列出其订阅的主题的 TopicArn 参数。将参数传递到 SNS 客户端类的 ListSubscriptionsByTopicCommand 方法。要调用 ListSubscriptionsByTopicCommand方法,请创建一个异步函数,调用 Amazon SNS 客户端服务对象并传递参数对象。

注意

TOPIC_ARN 替换为您要列出其订阅的主题的 Amazon 资源名称 (ARN)。

import { ListSubscriptionsByTopicCommand } from "@aws-sdk/client-sns"; import { snsClient } from "../libs/snsClient.js"; /** * @param {string} topicArn - The ARN of the topic for which you wish to list subscriptions. */ export const listSubscriptionsByTopic = async (topicArn = "TOPIC_ARN") => { const response = await snsClient.send( new ListSubscriptionsByTopicCommand({ TopicArn: topicArn }), ); console.log(response); // { // '$metadata': { // httpStatusCode: 200, // requestId: '0934fedf-0c4b-572e-9ed2-a3e38fadb0c8', // extendedRequestId: undefined, // cfId: undefined, // attempts: 1, // totalRetryDelay: 0 // }, // Subscriptions: [ // { // SubscriptionArn: 'PendingConfirmation', // Owner: '901487484989', // Protocol: 'email', // Endpoint: 'corepyle@amazon.com', // TopicArn: 'arn:aws:sns:us-east-1:901487484989:mytopic' // } // ] // } return response; };

要运行示例,请在命令提示符中键入以下内容。

node list-subscriptions-by-topic.js

此示例代码可在 GitHub 上的此处找到。

将电子邮件地址订阅到主题

在本示例中,使用 Node.js 模块来订阅电子邮件地址,使其从 Amazon SNS 主题接收 SMTP 电子邮件。

创建一个 libs 目录,然后使用文件名 snsClient.js 创建一个 Node.js 模块。将以下代码复制并粘贴到其中,这将创建 Amazon SNS 客户端对象。将 REGION 替换为您的 Amazon 区域。

import { SNSClient } from "@aws-sdk/client-sns"; // The AWS Region can be provided here using the `region` property. If you leave it blank // the SDK will default to the region set in your AWS config. export const snsClient = new SNSClient({});

此示例代码可在 GitHub 上的此处找到。

创建文件名为 subscribe-email.js 的 Node.js 模块。按前面所示配置 SDK。

创建包含 Protocol 参数的对象,用于指定 email 协议、要订阅到的主题的 TopicArn 以及作为邮件 Endpoint 的电子邮件地址。将参数传递到 SNS 客户端类的 SubscribeCommand 方法。您可以使用 subscribe 方法,根据在所传递参数中使用的值,将多种不同的端点订阅到某个 Amazon SNS 主题,如本主题中的其他示例所示。

要调用 SubscribeCommand方法,请创建一个异步函数,调用 Amazon SNS 客户端服务对象并传递参数对象。

注意

TOPIC_ARN 替换为该主题的 Amazon 资源名称 (ARN),将 EMAIL_ADDRESS 替换为用于订阅的电子邮件地址。

import { SubscribeCommand } from "@aws-sdk/client-sns"; import { snsClient } from "../libs/snsClient.js"; /** * @param {string} topicArn - The ARN of the topic for which you wish to confirm a subscription. * @param {string} emailAddress - The email address that is subscribed to the topic. */ export const subscribeEmail = async ( topicArn = "TOPIC_ARN", emailAddress = "usern@me.com", ) => { const response = await snsClient.send( new SubscribeCommand({ Protocol: "email", TopicArn: topicArn, Endpoint: emailAddress, }), ); console.log(response); // { // '$metadata': { // httpStatusCode: 200, // requestId: 'c8e35bcd-b3c0-5940-9f66-06f6fcc108f0', // extendedRequestId: undefined, // cfId: undefined, // attempts: 1, // totalRetryDelay: 0 // }, // SubscriptionArn: 'pending confirmation' // } };

要运行示例,请在命令提示符中键入以下内容。

node subscribe-email.js

此示例代码可在 GitHub 上的此处找到。

确认订阅

在本示例中,使用 Node.js 模块,通过验证之前的 SUBSCRIBE 操作发送到端点的令牌来验证端点所有者接收消息的意图。

创建一个 libs 目录,然后使用文件名 snsClient.js 创建一个 Node.js 模块。将以下代码复制并粘贴到其中,这将创建 Amazon SNS 客户端对象。将 REGION 替换为您的 Amazon 区域。

import { SNSClient } from "@aws-sdk/client-sns"; // The AWS Region can be provided here using the `region` property. If you leave it blank // the SDK will default to the region set in your AWS config. export const snsClient = new SNSClient({});

此示例代码可在 GitHub 上的此处找到。

创建文件名为 confirm-subscription.js 的 Node.js 模块。如前所示配置 SDK,包括安装所需的客户端和软件包。

定义参数,包括 TOPIC_ARNTOKEN,然后为 AuthenticateOnUnsubscribe 定义值 TRUEFALSE

令牌是在之前的 SUBSCRIBE 操作中发送给端点所有者的短期令牌。例如,对于电子邮件端点,TOKEN 可在发送给电子邮件所有者的确认订阅电子邮件的 URL 中找到。例如,在以下 URL 中,abc123 是令牌。

要调用 ConfirmSubscriptionCommand方法,请创建一个异步函数,调用 Amazon SNS 客户端服务对象并传递参数对象。

注意

TOPIC_ARN 替换为主题的 Amazon 资源名称 (ARN),将 TOKEN 替换为之前 Subscribe 操作中发送给端点所有者的 URL 中的令牌值,然后将 AuthenticateOnUnsubscribe 定义为值 TRUEFALSE

import { ConfirmSubscriptionCommand } from "@aws-sdk/client-sns"; import { snsClient } from "../libs/snsClient.js"; /** * @param {string} token - This token is sent the subscriber. Only subscribers * that are not AWS services (HTTP/S, email) need to be confirmed. * @param {string} topicArn - The ARN of the topic for which you wish to confirm a subscription. */ export const confirmSubscription = async ( token = "TOKEN", topicArn = "TOPIC_ARN", ) => { const response = await snsClient.send( // A subscription only needs to be confirmed if the endpoint type is // HTTP/S, email, or in another AWS account. new ConfirmSubscriptionCommand({ Token: token, TopicArn: topicArn, // If this is true, the subscriber cannot unsubscribe while unauthenticated. AuthenticateOnUnsubscribe: "false", }), ); console.log(response); // { // '$metadata': { // httpStatusCode: 200, // requestId: '4bb5bce9-805a-5517-8333-e1d2cface90b', // extendedRequestId: undefined, // cfId: undefined, // attempts: 1, // totalRetryDelay: 0 // }, // SubscriptionArn: 'arn:aws:sns:us-east-1:xxxxxxxxxxxx:TOPIC_NAME:xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx' // } return response; };

要运行示例,请在命令提示符中键入以下内容。

node confirm-subscription.js

此示例代码可在 GitHub 上的此处找到。

将应用程序端点订阅到主题

在本示例中,使用 Node.js 模块来订阅移动应用程序端点,使其从 Amazon SNS 主题接收通知。

创建一个 libs 目录,然后使用文件名 snsClient.js 创建一个 Node.js 模块。将以下代码复制并粘贴到其中,这将创建 Amazon SNS 客户端对象。将 REGION 替换为您的 Amazon 区域。

import { SNSClient } from "@aws-sdk/client-sns"; // The AWS Region can be provided here using the `region` property. If you leave it blank // the SDK will default to the region set in your AWS config. export const snsClient = new SNSClient({});

此示例代码可在 GitHub 上的此处找到。

创建文件名为 subscribe-app.js 的 Node.js 模块。如前所示配置 SDK,包括安装所需的模块和软件包。

创建一个包含 Protocol 参数的对象,用于指定 application 协议、要订阅到的主题的 TopicArn 以及 Endpoint 参数的移动应用程序端点的 Amazon 资源名称 (ARN)。将参数传递到 SNS 客户端类的 SubscribeCommand 方法。

要调用 SubscribeCommand 方法,请创建一个用于调用 Amazon SNS 服务对象的异步函数并传递参数对象。

注意

TOPIC_ARN 替换为主题的 Amazon 资源名称 (ARN),将 MOBILE_ENDPOINT_ARN 替换为您订阅主题的端点。

import { SubscribeCommand } from "@aws-sdk/client-sns"; import { snsClient } from "../libs/snsClient.js"; /** * @param {string} topicArn - The ARN of the topic the subscriber is subscribing to. * @param {string} endpoint - The Endpoint ARN of an application. This endpoint is created * when an application registers for notifications. */ export const subscribeApp = async ( topicArn = "TOPIC_ARN", endpoint = "ENDPOINT", ) => { const response = await snsClient.send( new SubscribeCommand({ Protocol: "application", TopicArn: topicArn, Endpoint: endpoint, }), ); console.log(response); // { // '$metadata': { // httpStatusCode: 200, // requestId: 'c8e35bcd-b3c0-5940-9f66-06f6fcc108f0', // extendedRequestId: undefined, // cfId: undefined, // attempts: 1, // totalRetryDelay: 0 // }, // SubscriptionArn: 'pending confirmation' // } return response; };

要运行示例,请在命令提示符中键入以下内容。

node subscribe-app.js

此示例代码可在 GitHub 上的此处找到。

将 Lambda 函数订阅到主题

在本示例中,使用 Node.js 模块来订阅 Amazon Lambda 函数,使其从 Amazon SNS 主题接收通知。

创建一个 libs 目录,然后使用文件名 snsClient.js 创建一个 Node.js 模块。将以下代码复制并粘贴到其中,这将创建 Amazon SNS 客户端对象。将 REGION 替换为您的 Amazon 区域。

import { SNSClient } from "@aws-sdk/client-sns"; // The AWS Region can be provided here using the `region` property. If you leave it blank // the SDK will default to the region set in your AWS config. export const snsClient = new SNSClient({});

此示例代码可在 GitHub 上的此处找到。

创建文件名为 subscribe-lambda.js 的 Node.js 模块。按前面所示配置 SDK。

创建一个包含 Protocol 参数的对象,指定 lambda 协议、要订阅到的主题的 TopicArn 以及作为 Endpoint 参数的 Amazon Lambda 函数的 Amazon 资源名称 (ARN)。将参数传递到 SNS 客户端类的 SubscribeCommand 方法。

要调用 SubscribeCommand方法,请创建一个异步函数,调用 Amazon SNS 客户端服务对象并传递参数对象。

注意

TOPIC_ARN 替换为主题的 Amazon 资源名称 (ARN),将 LAMBDA_FUNCTION_ARN 替换为 Lambda 函数的 Amazon 资源名称 (ARN)。

import { SubscribeCommand } from "@aws-sdk/client-sns"; import { snsClient } from "../libs/snsClient.js"; /** * @param {string} topicArn - The ARN of the topic the subscriber is subscribing to. * @param {string} endpoint - The Endpoint ARN of and AWS Lambda function. */ export const subscribeLambda = async ( topicArn = "TOPIC_ARN", endpoint = "ENDPOINT", ) => { const response = await snsClient.send( new SubscribeCommand({ Protocol: "lambda", TopicArn: topicArn, Endpoint: endpoint, }), ); console.log(response); // { // '$metadata': { // httpStatusCode: 200, // requestId: 'c8e35bcd-b3c0-5940-9f66-06f6fcc108f0', // extendedRequestId: undefined, // cfId: undefined, // attempts: 1, // totalRetryDelay: 0 // }, // SubscriptionArn: 'pending confirmation' // } return response; };

要运行示例,请在命令提示符中键入以下内容。

node subscribe-lambda.js

此示例代码可在 GitHub 上的此处找到。

从主题取消订阅

在本示例中,使用 Node.js 模块取消订阅 Amazon SNS 主题订阅。

创建一个 libs 目录,然后使用文件名 snsClient.js 创建一个 Node.js 模块。将以下代码复制并粘贴到其中,这将创建 Amazon SNS 客户端对象。将 REGION 替换为您的 Amazon 区域。

import { SNSClient } from "@aws-sdk/client-sns"; // The AWS Region can be provided here using the `region` property. If you leave it blank // the SDK will default to the region set in your AWS config. export const snsClient = new SNSClient({});

此示例代码可在 GitHub 上的此处找到。

创建文件名为 unsubscribe.js 的 Node.js 模块。如前所示配置 SDK,包括安装所需的客户端和软件包。

创建一个包含 SubscriptionArn 参数的对象,指定要取消订阅的订阅的 Amazon 资源名称 (ARN)。将参数传递到 SNS 客户端类的 UnsubscribeCommand 方法。

要调用 UnsubscribeCommand方法,请创建一个异步函数,调用 Amazon SNS 客户端服务对象并传递参数对象。

注意

TOPIC_SUBSCRIPTION_ARN 替换为要取消订阅的订阅的 Amazon 资源名称 (ARN)。

import { UnsubscribeCommand } from "@aws-sdk/client-sns"; import { snsClient } from "../libs/snsClient.js"; /** * @param {string} subscriptionArn - The ARN of the subscription to cancel. */ const unsubscribe = async ( subscriptionArn = "arn:aws:sns:us-east-1:xxxxxxxxxxxx:mytopic:xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx", ) => { const response = await snsClient.send( new UnsubscribeCommand({ SubscriptionArn: subscriptionArn, }), ); console.log(response); // { // '$metadata': { // httpStatusCode: 200, // requestId: '0178259a-9204-507c-b620-78a7570a44c6', // extendedRequestId: undefined, // cfId: undefined, // attempts: 1, // totalRetryDelay: 0 // } // } return response; };

要运行示例,请在命令提示符中键入以下内容。

node unsubscribe.js

此示例代码可在 GitHub 上的此处找到。