

 [适用于 JavaScript 的 AWS SDK V3 API 参考指南](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/)详细描述了 适用于 JavaScript 的 AWS SDK 版本 3 (V3) 的所有 API 操作。

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

# 在 Amazon SNS 中管理订阅
<a name="sns-examples-subscribing-unsubscribing-topics"></a>

![\[JavaScript code example that applies to Node.js execution\]](http://docs.aws.amazon.com/zh_cn/sdk-for-javascript/v3/developer-guide/images/nodeicon.png)

**此 Node.js 代码示例演示：**
+ 如何列出对 Amazon SNS 主题的所有订阅。
+ 如何将电子邮件地址、应用程序端点或 AWS Lambda 函数订阅到 Amazon SNS 主题。
+ 如何从 Amazon SNS 主题取消订阅。

## 情景
<a name="sns-examples-subscribing-unsubscribing-topics-scenario"></a>

在本示例中，您使用一系列 Node.js 模块将通知消息发布到 Amazon SNS 主题。Node.js 模块使用的 SDK JavaScript ，通过`SNS`客户端类的以下方法来管理主题：
+ [https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/Package/-aws-sdk-client-sns/Class/ListSubscriptionsByTopicCommand/](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/Package/-aws-sdk-client-sns/Class/ListSubscriptionsByTopicCommand/)
+ [https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/Package/-aws-sdk-client-sns/Class/SubscribeCommand/](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/Package/-aws-sdk-client-sns/Class/SubscribeCommand/)
+ [https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/Package/-aws-sdk-client-sns/Class/ConfirmSubscriptionCommand/](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/Package/-aws-sdk-client-sns/Class/ConfirmSubscriptionCommand/)
+ [https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/Package/-aws-sdk-client-sns/Class/UnsubscribeCommand/](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/Package/-aws-sdk-client-sns/Class/UnsubscribeCommand/)

## 先决条件任务
<a name="sns-examples-subscribing-unsubscribing-topics-prerequisites"></a>

要设置和运行此示例，您必须先完成以下任务：
+ 设置项目环境以运行这些 Node TypeScript 示例，并安装所需的模块 适用于 JavaScript 的 AWS SDK 和第三方模块。按照上的说明进行操作[ GitHub](https://github.com/awsdocs/aws-doc-sdk-examples/blob/main/javascriptv3/example_code/sns/README.md)。
+ 使用用户凭证创建共享配置文件。有关提供共享凭据文件的更多信息，请参阅[和*工具参考指南中的共享配置AWS SDKs 和*凭据文件](https://docs.aws.amazon.com/sdkref/latest/guide/file-format.html)。

**重要**  
这些示例演示了如何使用 ECMAScript6 (ES6) 来 import/export 客户端服务对象和命令。  
这需要使用 Node.js 版本 13.x 或更高版本。要下载并安装最新版本的 Node.js，请参阅 [Node.js 下载](https://nodejs.org/en/download)。
如果您更喜欢使用 CommonJS 语法，请参阅 [JavaScript ES6/CommonJS 语法](sdk-example-javascript-syntax.md)。

## 列出对主题的订阅
<a name="sns-examples-list-subscriptions-email"></a>

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

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

```
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({});
```

可以在此[处找到此](https://github.com/awsdocs/aws-doc-sdk-examples/blob/main/javascriptv3/example_code/sns/libs/snsClient.js)示例代码 GitHub。

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

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

**注意**  
*TOPIC\$1ARN*替换为您要列出其订阅的主题的 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
```

可以在此[处找到此](https://github.com/awsdocs/aws-doc-sdk-examples/blob/main/javascriptv3/example_code/sns/actions/list-subscriptions-by-topic.js)示例代码 GitHub。

## 将电子邮件地址订阅到主题
<a name="sns-examples-subscribing-email"></a>

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

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

```
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({});
```

可以在此[处找到此](https://github.com/awsdocs/aws-doc-sdk-examples/blob/main/javascriptv3/example_code/sns/libs/snsClient.js)示例代码 GitHub。

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

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

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

**注意**  
*TOPIC\$1ARN*替换为主题的 Amazon 资源名称 (ARN)，并*EMAIL\$1ADDRESS*替换为要订阅的电子邮件地址。

```
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
```

可以在此[处找到此](https://github.com/awsdocs/aws-doc-sdk-examples/blob/main/javascriptv3/example_code/sns/actions/subscribe-email.js)示例代码 GitHub。

### 确认订阅
<a name="sns-confirm-subscription-email"></a>

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

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

```
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({});
```

可以在此[处找到此](https://github.com/awsdocs/aws-doc-sdk-examples/blob/main/javascriptv3/example_code/sns/libs/snsClient.js)示例代码 GitHub。

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

定义参数，包括 `TOPIC_ARN` 和 `TOKEN`，然后为 `AuthenticateOnUnsubscribe` 定义值 `TRUE` 或 `FALSE`。

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

![\[Amazon Web Services Simple Notification Service subscription confirmation page.\]](http://docs.aws.amazon.com/zh_cn/sdk-for-javascript/v3/developer-guide/images/token.png)


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

**注意**  
将主题的 *TOPIC\$1ARN* Amazon 资源名称 (ARN) 替换为之前`Subscribe`操作中发送给终端节点所有者的 URL 中的令牌值，然后定义*AuthenticateOnUnsubscribe*. 的`TRUE`值为或。*TOKEN* `FALSE`

```
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
```

可以在此[处找到此](https://github.com/awsdocs/aws-doc-sdk-examples/blob/main/javascriptv3/example_code/sns/actions/confirm-subscription.js)示例代码 GitHub。

## 将应用程序端点订阅到主题
<a name="sns-examples-subscribing-apps"></a>

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

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

```
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({});
```

可以在此[处找到此](https://github.com/awsdocs/aws-doc-sdk-examples/blob/main/javascriptv3/example_code/sns/libs/snsClient.js)示例代码 GitHub。

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

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

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

**注意**  
*TOPIC\$1ARN*替换为主题的 Amazon 资源名称 (ARN)，以及*MOBILE\$1ENDPOINT\$1ARN*您订阅该主题的终端节点。

```
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
```

可以在此[处找到此](https://github.com/awsdocs/aws-doc-sdk-examples/blob/main/javascriptv3/example_code/sns/actions/subscribe-app.js)示例代码 GitHub。

## 将 Lambda 函数订阅到主题
<a name="sns-examples-subscribing-lambda"></a>

在此示例中，使用 Node.js 模块订阅 AWS Lambda 函数，使其接收来自亚马逊 SNS 主题的通知。

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

```
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({});
```

可以在此[处找到此](https://github.com/awsdocs/aws-doc-sdk-examples/blob/main/javascriptv3/example_code/sns/libs/snsClient.js)示例代码 GitHub。

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

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

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

**注意**  
*TOPIC\$1ARN*替换为主题的亚马逊资源名称 (ARN)，并*LAMBDA\$1FUNCTION\$1ARN*替换为 Lambda 函数的亚马逊资源名称 (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
```

可以在此[处找到此](https://github.com/awsdocs/aws-doc-sdk-examples/blob/main/javascriptv3/example_code/sns/actions/subscribe-lambda.js)示例代码 GitHub。

## 从主题取消订阅
<a name="sns-examples-unsubscribing"></a>

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

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

```
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({});
```

可以在此[处找到此](https://github.com/awsdocs/aws-doc-sdk-examples/blob/main/javascriptv3/example_code/sns/libs/snsClient.js)示例代码 GitHub。

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

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

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

**注意**  
*TOPIC\$1SUBSCRIPTION\$1ARN*替换为订阅的 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
```

可以在此[处找到此](https://github.com/awsdocs/aws-doc-sdk-examples/blob/main/javascriptv3/example_code/sns/actions/unsubscribe.js)示例代码 GitHub。