

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

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

# Amazon Simple Notification Service 示例
<a name="sns-examples"></a>

Amazon Simple Notification Service (Amazon SNS) 是一项 Web 服务，用于协调和管理向订阅端点或客户端交付或发送消息的过程。

在 Amazon SNS 中有两种类型的客户端：发布者和订阅者，也称为生产者和消费者。

![\[JavaScript 环境、软件开发工具包和 Amazon SNS 之间的关系\]](http://docs.aws.amazon.com/zh_cn/sdk-for-javascript/v3/developer-guide/images/code-samples-sns.png)


发布者通过创建消息并将消息发送至主题与订阅者进行异步交流，主题是一个逻辑访问点和通信渠道。订阅者（网络服务器、电子邮件地址、Amazon SQS 队列、 AWS Lambda 函数）在订阅主题时，通过支持的协议之一（Amazon SQS、HTTP/S、电子邮件 AWS Lambda、短信）使用或接收消息或通知。

Amazon SNS 的 JavaScript API 通过[类别：](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/Package/-aws-sdk-client-sns/Class/SNS/)SNS 公开。

**Topics**
+ [在 Amazon SNS 中管理主题](sns-examples-managing-topics.md)
+ [在 Amazon SNS 中发布消息](sns-examples-publishing-messages.md)
+ [在 Amazon SNS 中管理订阅](sns-examples-subscribing-unsubscribing-topics.md)
+ [使用 Amazon SNS 发送 SMS 消息](sns-examples-sending-sms.md)

# 在 Amazon SNS 中管理主题
<a name="sns-examples-managing-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 中创建可以将通知发布到的主题。
+ 如何删除在 Amazon SNS 中创建的主题。
+ 如何获取可用主题的列表。
+ 如何获取和设置主题属性。

## 情景
<a name="sns-examples-managing-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/CreateTopicCommand/](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/Package/-aws-sdk-client-sns/Class/CreateTopicCommand/)
+ [https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/Package/-aws-sdk-client-sns/Class/ListTopicsCommand/](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/Package/-aws-sdk-client-sns/Class/ListTopicsCommand/)
+ [https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/Package/-aws-sdk-client-sns/Class/DeleteTopicCommand/](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/Package/-aws-sdk-client-sns/Class/DeleteTopicCommand/)
+ [https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/Package/-aws-sdk-client-sns/Class/GetTopicAttributesCommand/](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/Package/-aws-sdk-client-sns/Class/GetTopicAttributesCommand/)
+ [https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/Package/-aws-sdk-client-sns/Class/SetTopicAttributesCommand/](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/Package/-aws-sdk-client-sns/Class/SetTopicAttributesCommand/)

## 先决条件任务
<a name="sns-examples-managing-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-managing-topics-createtopic"></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。

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

创建对象，将新主题的 `Name` 传递到 `SNS` 客户端类的 `CreateTopicCommand` 方法。要调用 `CreateTopicCommand` 方法，请创建一个用于调用 Amazon SNS 服务对象的异步函数并传递参数对象。返回的 `data` 包含主题的 ARN。

**注意**  
*TOPIC\$1NAME*替换为主题的名称。

```
import { CreateTopicCommand } from "@aws-sdk/client-sns";
import { snsClient } from "../libs/snsClient.js";

/**
 * @param {string} topicName - The name of the topic to create.
 */
export const createTopic = async (topicName = "TOPIC_NAME") => {
  const response = await snsClient.send(
    new CreateTopicCommand({ Name: topicName }),
  );
  console.log(response);
  // {
  //   '$metadata': {
  //     httpStatusCode: 200,
  //     requestId: '087b8ad2-4593-50c4-a496-d7e90b82cf3e',
  //     extendedRequestId: undefined,
  //     cfId: undefined,
  //     attempts: 1,
  //     totalRetryDelay: 0
  //   },
  //   TopicArn: 'arn:aws:sns:us-east-1:xxxxxxxxxxxx:TOPIC_NAME'
  // }
  return response;
};
```

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

```
node create-topic.js
```

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

## 列出主题
<a name="sns-examples-managing-topics-listtopics"></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-topics.js` 的 Node.js 模块。如前所示配置 SDK，包括安装所需的客户端和软件包。

创建一个空对象以传递到 `SNS` 客户端类的 `ListTopicsCommand` 方法。要调用 `ListTopicsCommand` 方法，请创建一个用于调用 Amazon SNS 服务对象的异步函数并传递参数对象。`data`返回的内容包含您的主题 Amazon 资源名称 (ARNs) 的数组。

```
import { ListTopicsCommand } from "@aws-sdk/client-sns";
import { snsClient } from "../libs/snsClient.js";

export const listTopics = async () => {
  const response = await snsClient.send(new ListTopicsCommand({}));
  console.log(response);
  // {
  //   '$metadata': {
  //     httpStatusCode: 200,
  //     requestId: '936bc5ad-83ca-53c2-b0b7-9891167b909e',
  //     extendedRequestId: undefined,
  //     cfId: undefined,
  //     attempts: 1,
  //     totalRetryDelay: 0
  //   },
  //   Topics: [ { TopicArn: 'arn:aws:sns:us-east-1:xxxxxxxxxxxx:mytopic' } ]
  // }
  return response;
};
```

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

```
node list-topics.js
```

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

## 删除主题
<a name="sns-examples-managing-topics-deletetopic"></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。

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

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

**注意**  
*TOPIC\$1ARN*替换为您要删除的主题的 Amazon 资源名称 (ARN)。

```
import { DeleteTopicCommand } from "@aws-sdk/client-sns";
import { snsClient } from "../libs/snsClient.js";

/**
 * @param {string} topicArn - The ARN of the topic to delete.
 */
export const deleteTopic = async (topicArn = "TOPIC_ARN") => {
  const response = await snsClient.send(
    new DeleteTopicCommand({ TopicArn: topicArn }),
  );
  console.log(response);
  // {
  //   '$metadata': {
  //     httpStatusCode: 200,
  //     requestId: 'a10e2886-5a8f-5114-af36-75bd39498332',
  //     extendedRequestId: undefined,
  //     cfId: undefined,
  //     attempts: 1,
  //     totalRetryDelay: 0
  //   }
  // }
};
```

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

```
node delete-topic.js
```

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

## 获取主题属性
<a name="sns-examples-managing-topicsgettopicattributes"></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。

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

创建包含要删除主题的 `TopicArn` 的对象，将其传递到 `SNS` 客户端类的 `GetTopicAttributesCommand` 方法。要调用 `GetTopicAttributesCommand` 方法，请调用一个 Amazon SNS 客户端服务对象来传递参数对象。

**注意**  
*TOPIC\$1ARN*替换为主题的 ARN。

```
import { GetTopicAttributesCommand } from "@aws-sdk/client-sns";
import { snsClient } from "../libs/snsClient.js";

/**
 * @param {string} topicArn - The ARN of the topic to retrieve attributes for.
 */
export const getTopicAttributes = async (topicArn = "TOPIC_ARN") => {
  const response = await snsClient.send(
    new GetTopicAttributesCommand({
      TopicArn: topicArn,
    }),
  );
  console.log(response);
  // {
  //   '$metadata': {
  //     httpStatusCode: 200,
  //     requestId: '36b6a24e-5473-5d4e-ac32-ff72d9a73d94',
  //     extendedRequestId: undefined,
  //     cfId: undefined,
  //     attempts: 1,
  //     totalRetryDelay: 0
  //   },
  //   Attributes: {
  //     Policy: '{...}',
  //     Owner: 'xxxxxxxxxxxx',
  //     SubscriptionsPending: '1',
  //     TopicArn: 'arn:aws:sns:us-east-1:xxxxxxxxxxxx:mytopic',
  //     TracingConfig: 'PassThrough',
  //     EffectiveDeliveryPolicy: '{"http":{"defaultHealthyRetryPolicy":{"minDelayTarget":20,"maxDelayTarget":20,"numRetries":3,"numMaxDelayRetries":0,"numNoDelayRetries":0,"numMinDelayRetries":0,"backoffFunction":"linear"},"disableSubscriptionOverrides":false,"defaultRequestPolicy":{"headerContentType":"text/plain; charset=UTF-8"}}}',
  //     SubscriptionsConfirmed: '0',
  //     DisplayName: '',
  //     SubscriptionsDeleted: '1'
  //   }
  // }
  return response;
};
```

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

```
node get-topic-attributes.js
```

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

## 设置主题属性
<a name="sns-examples-managing-topicssttopicattributes"></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。

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

创建包含用于属性更新参数的对象，这包括要设置其属性的主题的 `TopicArn`、要设置的属性的名称以及该属性的新值。您只能设置 `Policy`、`DisplayName` 和 `DeliveryPolicy` 属性。将参数传递到 `SNS` 客户端类的 `SetTopicAttributesCommand` 方法。要调用 `SetTopicAttributesCommand`方法，请创建一个异步函数，调用 Amazon SNS 客户端服务对象并传递参数对象。

**注意**  
*ATTRIBUTE\$1NAME*替换为您正在设置的属性名称、*TOPIC\$1ARN*要设置其属性的主题的 Amazon 资源名称 (ARN) 以及该属*NEW\$1ATTRIBUTE\$1VALUE*性的新值。

```
import { SetTopicAttributesCommand } from "@aws-sdk/client-sns";
import { snsClient } from "../libs/snsClient.js";

export const setTopicAttributes = async (
  topicArn = "TOPIC_ARN",
  attributeName = "DisplayName",
  attributeValue = "Test Topic",
) => {
  const response = await snsClient.send(
    new SetTopicAttributesCommand({
      AttributeName: attributeName,
      AttributeValue: attributeValue,
      TopicArn: topicArn,
    }),
  );
  console.log(response);
  // {
  //   '$metadata': {
  //     httpStatusCode: 200,
  //     requestId: 'd1b08d0e-e9a4-54c3-b8b1-d03238d2b935',
  //     extendedRequestId: undefined,
  //     cfId: undefined,
  //     attempts: 1,
  //     totalRetryDelay: 0
  //   }
  // }
  return response;
};
```

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

```
node set-topic-attributes.js
```

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

# 在 Amazon SNS 中发布消息
<a name="sns-examples-publishing-messages"></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 主题。

## 情景
<a name="sns-examples-publishing-messages-scenario"></a>

在本示例中，您使用一系列 Node.js 模块，将消息从 Amazon SNS 发布到主题端点、电子邮件或电话号码。Node.js 模块使用的 JavaScript SDK 通过`SNS`客户端类的以下方法发送消息：
+ [https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/Package/-aws-sdk-client-sns/Class/PublishCommand/](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/Package/-aws-sdk-client-sns/Class/PublishCommand/)

## 先决条件任务
<a name="sns-examples-publishing-messages-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)。

## 将消息发布到 SNS 主题
<a name="sns-examples-publishing-text-messages"></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。

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

创建一个对象，其中包含用于发布消息的参数，包括消息文本和亚马逊的亚马逊资源名称 (ARN)。 SNStopic有关可用短信属性的详细信息，请参阅[设置SMSAttributes](https://docs.aws.amazon.com/AWSJavaScriptSDK/latest/AWS/SNS.html#setSMSAttributes-property)。

将参数传递到 `SNS` 客户端类的 `PublishCommand` 方法。创建一个异步函数，调用 Amazon SNS 客户端服务对象并传递参数对象。

**注意**  
*MESSAGE\$1TEXT*替换为消息文本和 *TOPIC\$1ARN* SNS 主题的 ARN。

```
import { PublishCommand } from "@aws-sdk/client-sns";
import { snsClient } from "../libs/snsClient.js";

/**
 * @param {string | Record<string, any>} message - The message to send. Can be a plain string or an object
 *                                                 if you are using the `json` `MessageStructure`.
 * @param {string} topicArn - The ARN of the topic to which you would like to publish.
 */
export const publish = async (
  message = "Hello from SNS!",
  topicArn = "TOPIC_ARN",
) => {
  const response = await snsClient.send(
    new PublishCommand({
      Message: message,
      TopicArn: topicArn,
    }),
  );
  console.log(response);
  // {
  //   '$metadata': {
  //     httpStatusCode: 200,
  //     requestId: 'e7f77526-e295-5325-9ee4-281a43ad1f05',
  //     extendedRequestId: undefined,
  //     cfId: undefined,
  //     attempts: 1,
  //     totalRetryDelay: 0
  //   },
  //   MessageId: 'xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx'
  // }
  return response;
};
```

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

```
node publish-topic.js
```

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

# 在 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。

# 使用 Amazon SNS 发送 SMS 消息
<a name="sns-examples-sending-sms"></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 的 SMS 消息发送首选项。
+ 如何检查电话号码以确定是否选择退出接收 SMS 消息。
+ 如何获取已选择退出接收 SMS 消息的电话号码列表。
+ 如何发送 SMS 消息。

## 情景
<a name="sns-examples-sending-sms-scenario"></a>

您可以使用 Amazon SNS 将文本消息或 SMS 消息发送到支持 SMS 的设备上。您可以直接向电话号码发送消息，也可以使用多个电话号码订阅主题，然后通过向该主题发送消息来一次向这些电话号码发送消息。

在本示例中，您使用一系列 Node.js 模块将 SMS 文本消息从 Amazon SNS 发送到支持 SMS 的设备。Node.js 模块使用的 SDK 使用以下`SNS`客户端类的方法发布 SMS 消息： JavaScript 
+ [https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/Package/-aws-sdk-client-sns/Class/GetSMSAttributesCommand/](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/Package/-aws-sdk-client-sns/Class/GetSMSAttributesCommand/)
+ [https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/Package/-aws-sdk-client-sns/Class/SetSMSAttributesCommand/](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/Package/-aws-sdk-client-sns/Class/SetSMSAttributesCommand/)
+ [https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/Package/-aws-sdk-client-sns/Class/CheckIfPhoneNumberIsOptedOutCommand/](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/Package/-aws-sdk-client-sns/Class/CheckIfPhoneNumberIsOptedOutCommand/)
+ [https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/Package/-aws-sdk-client-sns/Class/ListPhoneNumbersOptedOutCommand/](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/Package/-aws-sdk-client-sns/Class/ListPhoneNumbersOptedOutCommand/)
+ [https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/Package/-aws-sdk-client-sns/Class/PublishCommand/](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/Package/-aws-sdk-client-sns/Class/PublishCommand/)

## 先决条件任务
<a name="sns-examples-sending-sms-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)。

## 获取 SMS 属性
<a name="sending-sms-getattributes"></a>

使用 Amazon SNS 来指定发送 SMS 消息的首选项，例如如何优化消息传输（在成本或可靠传输方面）、您的每月支出限额、如何记录消息传输以及是否要订阅每日 SMS 使用率报告。这些首选项通过检索得到，并设置为 Amazon SNS 的 SMS 属性。

在本示例中，使用 Node.js 模块获取 Amazon SNS 中的当前 SMS 属性。

创建一个 `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。

 创建文件名为 `get-sms-attributes.js` 的 Node.js 模块。

如前所示配置 SDK，包括下载所需的客户端和软件包。创建包含用于获取 SMS 属性的参数的对象，包括要获取的单个属性的名称。有关可用短信属性的详细信息，请参阅《亚马逊简单通知服务 API 参考》SMSAttributes中的 “[设置](https://docs.aws.amazon.com/sns/latest/api/API_SetSMSAttributes.html)”。

此示例获取 `DefaultSMSType` 属性，该属性控制 SMS 消息是作为 `Promotional` 发送（这将优化消息传送以尽可能降低成本）还是作为 `Transactional` 发送（这将优化消息传送以实现最高的可靠性）。将参数传递到 `SNS` 客户端类的 `SetTopicAttributesCommand` 方法。要调用 `SetSMSAttributesCommand`方法，请创建一个异步函数，调用 Amazon SNS 客户端服务对象并传递参数对象。

**注意**  
*ATTRIBUTE\$1NAME*替换为属性的名称。

```
import { GetSMSAttributesCommand } from "@aws-sdk/client-sns";
import { snsClient } from "../libs/snsClient.js";

export const getSmsAttributes = async () => {
  const response = await snsClient.send(
    // If you have not modified the account-level mobile settings of SNS,
    // the DefaultSMSType is undefined. For this example, it was set to
    // Transactional.
    new GetSMSAttributesCommand({ attributes: ["DefaultSMSType"] }),
  );

  console.log(response);
  // {
  //   '$metadata': {
  //     httpStatusCode: 200,
  //     requestId: '67ad8386-4169-58f1-bdb9-debd281d48d5',
  //     extendedRequestId: undefined,
  //     cfId: undefined,
  //     attempts: 1,
  //     totalRetryDelay: 0
  //   },
  //   attributes: { DefaultSMSType: 'Transactional' }
  // }
  return response;
};
```

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

```
node get-sms-attributes.js
```

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

## 设置 SMS 属性
<a name="sending-sms-setattributes"></a>

在本示例中，使用 Node.js 模块获取 Amazon SNS 中的当前 SMS 属性。

创建一个 `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。

 创建文件名为 `set-sms-attribute-type.js` 的 Node.js 模块。如前所示配置 SDK，包括安装所需的客户端和软件包。创建包含用于设置 SMS 属性的参数的对象，其中包括要设置的单个属性的名称以及为各个属性设置的值。有关可用短信属性的详细信息，请参阅《亚马逊简单通知服务 API 参考》SMSAttributes中的 “[设置](https://docs.aws.amazon.com/sns/latest/api/API_SetSMSAttributes.html)”。

此示例将 `DefaultSMSType` 属性设置为 `Transactional`，这会优化消息传送以实现最高的可靠性。将参数传递到 `SNS` 客户端类的 `SetTopicAttributesCommand` 方法。要调用 `SetSMSAttributesCommand`方法，请创建一个异步函数，调用 Amazon SNS 客户端服务对象并传递参数对象。

```
import { SetSMSAttributesCommand } from "@aws-sdk/client-sns";
import { snsClient } from "../libs/snsClient.js";

/**
 * @param {"Transactional" | "Promotional"} defaultSmsType
 */
export const setSmsType = async (defaultSmsType = "Transactional") => {
  const response = await snsClient.send(
    new SetSMSAttributesCommand({
      attributes: {
        // Promotional – (Default) Noncritical messages, such as marketing messages.
        // Transactional – Critical messages that support customer transactions,
        // such as one-time passcodes for multi-factor authentication.
        DefaultSMSType: defaultSmsType,
      },
    }),
  );
  console.log(response);
  // {
  //   '$metadata': {
  //     httpStatusCode: 200,
  //     requestId: '1885b977-2d7e-535e-8214-e44be727e265',
  //     extendedRequestId: undefined,
  //     cfId: undefined,
  //     attempts: 1,
  //     totalRetryDelay: 0
  //   }
  // }
  return response;
};
```

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

```
node set-sms-attribute-type.js 
```

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

## 检查电话号码是否已选择不接收消息
<a name="sending-sms-checkifphonenumberisoptedout"></a>

在本示例中，使用 Node.js 模块检查电话号码，确定该号码是否已退出接收 SMS 消息。

创建一个 `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。

创建文件名为 `check-if-phone-number-is-opted-out.js` 的 Node.js 模块。按前面所示配置 SDK。创建一个对象，其中将要检查的电话号码包含作为参数。

此示例设置 `PhoneNumber` 参数以指定要检查的电话号码。将对象发布到 `SNS` 客户端类的 `CheckIfPhoneNumberIsOptedOutCommand` 方法。要调用 `CheckIfPhoneNumberIsOptedOutCommand`方法，请创建一个异步函数，调用 Amazon SNS 客户端服务对象并传递参数对象。

**注意**  

*PHONE\$1NUMBER*替换为电话号码。

```
import { CheckIfPhoneNumberIsOptedOutCommand } from "@aws-sdk/client-sns";

import { snsClient } from "../libs/snsClient.js";

export const checkIfPhoneNumberIsOptedOut = async (
  phoneNumber = "5555555555",
) => {
  const command = new CheckIfPhoneNumberIsOptedOutCommand({
    phoneNumber,
  });

  const response = await snsClient.send(command);
  console.log(response);
  // {
  //   '$metadata': {
  //     httpStatusCode: 200,
  //     requestId: '3341c28a-cdc8-5b39-a3ee-9fb0ee125732',
  //     extendedRequestId: undefined,
  //     cfId: undefined,
  //     attempts: 1,
  //     totalRetryDelay: 0
  //   },
  //   isOptedOut: false
  // }
  return response;
};
```

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

```
node check-if-phone-number-is-opted-out.js 
```

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

## 列出已退出的电话号码
<a name="sending-sms-listphonenumbersoptedout"></a>

在本示例中，使用 Node.js 模块获取已退出接收 SMS 消息的电话号码列表。

创建一个 `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-phone-numbers-opted-out.js` 的 Node.js 模块。按前面所示配置 SDK。创建一个空对象作为参数。

将对象发布到 `SNS` 客户端类的 `ListPhoneNumbersOptedOutCommand` 方法。要调用 `ListPhoneNumbersOptedOutCommand`方法，请创建一个异步函数，调用 Amazon SNS 客户端服务对象并传递参数对象。

```
import { ListPhoneNumbersOptedOutCommand } from "@aws-sdk/client-sns";
import { snsClient } from "../libs/snsClient.js";

export const listPhoneNumbersOptedOut = async () => {
  const response = await snsClient.send(
    new ListPhoneNumbersOptedOutCommand({}),
  );
  console.log(response);
  // {
  //   '$metadata': {
  //     httpStatusCode: 200,
  //     requestId: '44ff72fd-1037-5042-ad96-2fc16601df42',
  //     extendedRequestId: undefined,
  //     cfId: undefined,
  //     attempts: 1,
  //     totalRetryDelay: 0
  //   },
  //   phoneNumbers: ['+15555550100']
  // }
  return response;
};
```

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

```
node list-phone-numbers-opted-out.js 
```

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

## 发布 SMS 消息
<a name="sending-sms-publishsms"></a>

在本示例中，使用 Node.js 模块将 SMS 消息发布到电话号码。

创建一个 `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。

创建文件名为 `publish-sms.js` 的 Node.js 模块。如前所示配置 SDK，包括安装所需的客户端和软件包。创建一个包含 `Message` 和 `PhoneNumber` 参数的对象。

在发送 SMS 消息时，请使用 E.164 格式指定电话号码。E.164 是用于国际电信的电话号码结构标准。遵循此格式的电话号码最多可包含 15 位，并以加号 (\$1) 和国家/地区代码作为前缀。例如，E.164 格式的美国电话号码将显示为 \$1 XXX5550100 1001。

此示例设置 `PhoneNumber` 参数以指定将消息发送到的电话号码。将对象发布到 `SNS` 客户端类的 `PublishCommand` 方法。要调用 `PublishCommand` 方法，请创建一个用于调用 Amazon SNS 服务对象的异步函数并传递参数对象。

**注意**  
*TEXT\$1MESSAGE*替换为*PHONE\$1NUMBER*短信和电话号码。

```
import { PublishCommand } from "@aws-sdk/client-sns";
import { snsClient } from "../libs/snsClient.js";

/**
 * @param {string | Record<string, any>} message - The message to send. Can be a plain string or an object
 *                                                 if you are using the `json` `MessageStructure`.
 * @param {*} phoneNumber - The phone number to send the message to.
 */
export const publish = async (
  message = "Hello from SNS!",
  phoneNumber = "+15555555555",
) => {
  const response = await snsClient.send(
    new PublishCommand({
      Message: message,
      // One of PhoneNumber, TopicArn, or TargetArn must be specified.
      PhoneNumber: phoneNumber,
    }),
  );
  console.log(response);
  // {
  //   '$metadata': {
  //     httpStatusCode: 200,
  //     requestId: '7410094f-efc7-5f52-af03-54737569ab77',
  //     extendedRequestId: undefined,
  //     cfId: undefined,
  //     attempts: 1,
  //     totalRetryDelay: 0
  //   },
  //   MessageId: 'xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx'
  // }
  return response;
};
```

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

```
node publish-sms.js
```

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