

 [適用於 JavaScript 的 AWS SDK V3 API 參考指南](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/)詳細說明 第 3 版 適用於 JavaScript 的 AWS SDK (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_tw/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 透過[類別：SNS ](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/Package/-aws-sdk-client-sns/Class/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 傳送簡訊](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_tw/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 模組使用適用於 JavaScript 的 SDK 來管理使用下列`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) 匯入/匯出用戶端服務物件和命令。  
這需要 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`目錄，並建立檔案名稱為 的 Node.js 模組`snsClient.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({});
```

您可以在 [ GitHub 上找到此](https://github.com/awsdocs/aws-doc-sdk-examples/blob/main/javascriptv3/example_code/sns/libs/snsClient.js)範例程式碼。

以檔名 `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
```

您可以在 [ GitHub 上找到此](https://github.com/awsdocs/aws-doc-sdk-examples/blob/main/javascriptv3/example_code/sns/actions/create-topic.js)範例程式碼。

## 列出 主題
<a name="sns-examples-managing-topics-listtopics"></a>

在此範例中，使用 Node.js 模組列出所有 Amazon SNS 主題。

建立`libs`目錄，並建立檔案名稱為 的 Node.js 模組`snsClient.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({});
```

您可以在 [ GitHub 上找到此](https://github.com/awsdocs/aws-doc-sdk-examples/blob/main/javascriptv3/example_code/sns/libs/snsClient.js)範例程式碼。

以檔名 `list-topics.js` 建立一個 Node.js 模組。如先前所示設定 SDK，包括安裝所需的用戶端和套件。

建立空白物件，並將其傳遞至 `SNS` 用戶端類別的 `ListTopicsCommand` 方法。若要呼叫 `ListTopicsCommand`方法，請建立叫用 Amazon SNS 服務物件、傳遞參數物件的非同步函數。`data` 傳回的 包含主題 Amazon Resource Name (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
```

您可以在 [GitHub 上](https://github.com/awsdocs/aws-doc-sdk-examples/blob/main/javascriptv3/example_code/sns/actions/list-topics.js)找到這個範本程式碼。

## 刪除主題
<a name="sns-examples-managing-topics-deletetopic"></a>

在此範例中，使用 Node.js 模組來刪除 Amazon SNS 主題。

建立`libs`目錄，並建立檔案名稱為 的 Node.js 模組`snsClient.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({});
```

您可以在 [ GitHub 上找到此](https://github.com/awsdocs/aws-doc-sdk-examples/blob/main/javascriptv3/example_code/sns/libs/snsClient.js)範例程式碼。

以檔名 `delete-topic.js` 建立一個 Node.js 模組。如先前所示設定 SDK，包括安裝所需的用戶端和套件。

建立包含欲刪除主題 `TopicArn` 的物件，並將其傳遞至 `SNS` 用戶端類別的 `DeleteTopicCommand` 方法。若要呼叫 `DeleteTopicCommand`方法，請建立叫用 Amazon SNS 用戶端服務物件、傳遞參數物件的非同步函數。

**注意**  
將 *TOPIC\$1ARN* 取代為您要刪除之主題的 Amazon Resource Name (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
```

您可以在 [ GitHub 上找到此](https://github.com/awsdocs/aws-doc-sdk-examples/blob/main/javascriptv3/example_code/sns/actions/delete-topic.js)範例程式碼。

## 取得主題屬性
<a name="sns-examples-managing-topicsgettopicattributes"></a>

在此範例中，使用 Node.js 模組擷取 Amazon SNS 主題的屬性。

建立`libs`目錄，並建立檔案名稱為 的 Node.js 模組`snsClient.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({});
```

您可以在 [ GitHub 上找到此](https://github.com/awsdocs/aws-doc-sdk-examples/blob/main/javascriptv3/example_code/sns/libs/snsClient.js)範例程式碼。

以檔名 `get-topic-attributes.js` 建立一個 Node.js 模組。依前述內容設定軟體開發套件。

建立包含欲刪除主題 `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
```

您可以在 [ GitHub 上找到此](https://github.com/awsdocs/aws-doc-sdk-examples/blob/main/javascriptv3/example_code/sns/actions/get-topic-attributes.js)範例程式碼。

## 設定主題屬性
<a name="sns-examples-managing-topicssttopicattributes"></a>

在此範例中，使用 Node.js 模組來設定 Amazon SNS 主題的可變屬性。

建立`libs`目錄，並建立檔案名稱為 的 Node.js 模組`snsClient.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({});
```

您可以在 [ GitHub 上找到此](https://github.com/awsdocs/aws-doc-sdk-examples/blob/main/javascriptv3/example_code/sns/libs/snsClient.js)範例程式碼。

以檔名 `set-topic-attributes.js` 建立一個 Node.js 模組。依前述內容設定軟體開發套件。

建立一個物件，其中包含用來更新屬性的參數，包括要設定屬性的主題 `TopicArn`、要設定的屬性名稱，以及該屬性的新數值。您只能設定 `Policy`、`DisplayName` 和 `DeliveryPolicy` 屬性。接著，將參數傳遞至 `SNS` 用戶端類別的 `SetTopicAttributesCommand` 方法。若要呼叫 `SetTopicAttributesCommand`方法，請建立叫用 Amazon SNS 用戶端服務物件、傳遞參數物件的非同步函數。

**注意**  
將 *ATTRIBUTE\$1NAME* 取代為您設定的屬性名稱、將 *TOPIC\$1ARN* 取代為您要設定屬性之主題的 Amazon Resource Name (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
```

您可以在 [ GitHub 上找到此](https://github.com/awsdocs/aws-doc-sdk-examples/blob/main/javascriptv3/example_code/sns/actions/set-topic-attributes.js)範例程式碼。

# 在 Amazon SNS 中發佈訊息
<a name="sns-examples-publishing-messages"></a>

![\[JavaScript code example that applies to Node.js execution\]](http://docs.aws.amazon.com/zh_tw/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) 匯入/匯出用戶端服務物件和命令。  
這需要 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`目錄，並建立檔案名稱為 的 Node.js 模組`snsClient.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({});
```

您可以在 [ GitHub 上找到此](https://github.com/awsdocs/aws-doc-sdk-examples/blob/main/javascriptv3/example_code/sns/libs/snsClient.js)範例程式碼。

 以檔名 `publish-topic.js` 建立一個 Node.js 模組。依前述內容設定軟體開發套件。

建立包含發佈訊息參數的物件，包括訊息文字和 Amazon SNStopic 的 Amazon Resource Name (ARN)。如需可用簡訊屬性的詳細資訊，請參閱 [SetSMSAttributes](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
```

您可以在 [ GitHub 上找到此](https://github.com/awsdocs/aws-doc-sdk-examples/blob/main/javascriptv3/example_code/sns/actions/publish-topic.js)範例程式碼。

# 在 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_tw/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 模組使用適用於 JavaScript 的 SDK 來管理使用下列`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) 匯入/匯出用戶端服務物件和命令。  
這需要 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`目錄，並建立檔案名稱為 的 Node.js 模組`snsClient.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({});
```

您可以在 [ GitHub 上找到此](https://github.com/awsdocs/aws-doc-sdk-examples/blob/main/javascriptv3/example_code/sns/libs/snsClient.js)範例程式碼。

 以檔名 `list-subscriptions-by-topic.js` 建立一個 Node.js 模組。依前述內容設定軟體開發套件。

建立一個物件，其中包含要列出訂閱的主題 `TopicArn` 參數。接著，將參數傳遞至 `SNS` 用戶端類別的 `ListSubscriptionsByTopicCommand` 方法。若要呼叫 `ListSubscriptionsByTopicCommand`方法，請建立叫用 Amazon SNS 用戶端服務物件的非同步函數，並傳遞參數物件。

**注意**  
將 *TOPIC\$1ARN* 取代為您想要列出訂閱之主題的 Amazon Resource Name (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 上找到此](https://github.com/awsdocs/aws-doc-sdk-examples/blob/main/javascriptv3/example_code/sns/actions/list-subscriptions-by-topic.js)範例程式碼。

## 使用電子郵件地址訂閱主題
<a name="sns-examples-subscribing-email"></a>

在此範例中，使用 Node.js 模組來訂閱電子郵件地址，以便接收來自 Amazon SNS 主題的 SMTP 電子郵件訊息。

建立`libs`目錄，並建立檔案名稱為 的 Node.js 模組`snsClient.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({});
```

您可以在 [ GitHub 上找到此](https://github.com/awsdocs/aws-doc-sdk-examples/blob/main/javascriptv3/example_code/sns/libs/snsClient.js)範例程式碼。

以檔名 `subscribe-email.js` 建立一個 Node.js 模組。依前述內容設定軟體開發套件。

建立包含 `Protocol` 參數的物件，以便指定 `email` 通訊協定、要訂閱的主題 `TopicArn`，以及要做為訊息 `Endpoint` 的電子郵件地址。接著，將參數傳遞至 `SNS` 用戶端類別的 `SubscribeCommand` 方法。您可以使用 `subscribe`方法將數個不同的端點訂閱 Amazon SNS 主題，這取決於傳遞的參數所使用的值，因為本主題中的其他範例會顯示。

若要呼叫 `SubscribeCommand`方法，請建立叫用 Amazon SNS 用戶端服務物件的非同步函數，並傳遞參數物件。

**注意**  
將 *TOPIC\$1ARN* 取代為主題的 Amazon Resource Name (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
```

您可以在 [ GitHub 上找到此](https://github.com/awsdocs/aws-doc-sdk-examples/blob/main/javascriptv3/example_code/sns/actions/subscribe-email.js)範例程式碼。

### 確認訂閱
<a name="sns-confirm-subscription-email"></a>

在此範例中，使用 Node.js 模組驗證端點擁有者接收電子郵件的意圖，方法是驗證先前訂閱動作傳送至端點的字符。

建立`libs`目錄，並建立檔案名稱為 的 Node.js 模組`snsClient.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({});
```

您可以在 [ GitHub 上找到此](https://github.com/awsdocs/aws-doc-sdk-examples/blob/main/javascriptv3/example_code/sns/libs/snsClient.js)範例程式碼。

以檔名 `confirm-subscription.js` 建立一個 Node.js 模組。如先前所示設定 SDK，包括安裝所需的用戶端和套件。

定義參數，包括 `TOPIC_ARN`和 `TOKEN`，並為 定義 `TRUE`或 `FALSE` 的值`AuthenticateOnUnsubscribe`。

權杖是在上一個`SUBSCRIBE`動作期間傳送給端點擁有者的短期權杖。例如，對於電子郵件端點， `TOKEN` 位於傳送給電子郵件擁有者的確認訂閱電子郵件 URL 中。例如， `abc123` 是下列 URL 中的字符。

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


若要呼叫 `ConfirmSubscriptionCommand`方法，請建立叫用 Amazon SNS 用戶端服務物件、傳遞參數物件的非同步函數。

**注意**  
將 *TOPIC\$1ARN* 取代為主題的 Amazon Resource Name (ARN)，將 *TOKEN* 取代為先前`Subscribe`動作中傳送給端點擁有者的 URL 中的字符值，並將 *AuthenticateOnUnsubscribe*. 定義為 `TRUE`或 的值`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
```

您可以在 [ GitHub 上找到此](https://github.com/awsdocs/aws-doc-sdk-examples/blob/main/javascriptv3/example_code/sns/actions/confirm-subscription.js)範例程式碼。

## 使用應用程式端點訂閱主題
<a name="sns-examples-subscribing-apps"></a>

在此範例中，使用 Node.js 模組訂閱行動應用程式端點，以便接收來自 Amazon SNS 主題的通知。

建立`libs`目錄，並建立檔案名稱為 的 Node.js 模組`snsClient.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({});
```

您可以在 [ GitHub 上找到此](https://github.com/awsdocs/aws-doc-sdk-examples/blob/main/javascriptv3/example_code/sns/libs/snsClient.js)範例程式碼。

以檔名 `subscribe-app.js` 建立一個 Node.js 模組。如先前所示設定 SDK，包括安裝所需的模組和套件。

建立包含 `Protocol` 參數的物件來指定`application`通訊協定、要訂閱主題`TopicArn`的 ，以及 `Endpoint` 參數行動應用程式端點的 Amazon Resource Name (ARN)。接著，將參數傳遞至 `SNS` 用戶端類別的 `SubscribeCommand` 方法。

若要呼叫 `SubscribeCommand`方法，請建立叫用 Amazon SNS 服務物件、傳遞參數物件的非同步函數。

**注意**  
將 *TOPIC\$1ARN* 取代為主題的 Amazon Resource Name (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
```

您可以在 [ GitHub 上找到此](https://github.com/awsdocs/aws-doc-sdk-examples/blob/main/javascriptv3/example_code/sns/actions/subscribe-app.js)範例程式碼。

## 訂閱 Lambda 函數至主題
<a name="sns-examples-subscribing-lambda"></a>

在此範例中，使用 Node.js 模組來訂閱 AWS Lambda 函數，以便接收來自 Amazon SNS 主題的通知。

建立`libs`目錄，並建立檔案名稱為 的 Node.js 模組`snsClient.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({});
```

您可以在 [ GitHub 上找到此](https://github.com/awsdocs/aws-doc-sdk-examples/blob/main/javascriptv3/example_code/sns/libs/snsClient.js)範例程式碼。

以檔名 `subscribe-lambda.js` 建立一個 Node.js 模組。依前述內容設定軟體開發套件。

建立包含 `Protocol` 參數的物件，指定`lambda`通訊協定、要訂閱的主題`TopicArn`的 ，以及 AWS Lambda 函數的 Amazon Resource Name (ARN) 做為 `Endpoint` 參數。接著，將參數傳遞至 `SNS` 用戶端類別的 `SubscribeCommand` 方法。

若要呼叫 `SubscribeCommand`方法，請建立叫用 Amazon SNS 用戶端服務物件、傳遞參數物件的非同步函數。

**注意**  
將 *TOPIC\$1ARN* 取代為主題的 Amazon Resource Name (ARN)，並將 *LAMBDA\$1FUNCTION\$1ARN* 取代為 Lambda 函數的 Amazon Resource Name (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 上找到此](https://github.com/awsdocs/aws-doc-sdk-examples/blob/main/javascriptv3/example_code/sns/actions/subscribe-lambda.js)範例程式碼。

## 取消訂閱主題
<a name="sns-examples-unsubscribing"></a>

在此範例中，使用 Node.js 模組取消訂閱 Amazon SNS 主題訂閱。

建立`libs`目錄，並建立檔案名稱為 的 Node.js 模組`snsClient.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({});
```

您可以在 [ GitHub 上找到此](https://github.com/awsdocs/aws-doc-sdk-examples/blob/main/javascriptv3/example_code/sns/libs/snsClient.js)範例程式碼。

以檔名 `unsubscribe.js` 建立一個 Node.js 模組。如先前所示設定 SDK，包括安裝所需的用戶端和套件。

建立包含 `SubscriptionArn` 參數的物件，指定要取消訂閱的訂閱 Amazon Resource Name (ARN)。接著，將參數傳遞至 `SNS` 用戶端類別的 `UnsubscribeCommand` 方法。

若要呼叫 `UnsubscribeCommand`方法，請建立叫用 Amazon SNS 用戶端服務物件、傳遞參數物件的非同步函數。

**注意**  
以訂閱的 Amazon Resource Name (*ARN) 取代 TOPIC\$1SUBSCRIPTION\$1*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 上找到此](https://github.com/awsdocs/aws-doc-sdk-examples/blob/main/javascriptv3/example_code/sns/actions/unsubscribe.js)範例程式碼。

# 使用 Amazon SNS 傳送簡訊
<a name="sns-examples-sending-sms"></a>

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

**這個 Node.js 程式碼範例會說明：**
+ 如何取得和設定 Amazon SNS 的簡訊偏好設定。
+ 如何檢查電話號碼是否選擇不要接收簡訊。
+ 如何取得選擇不要接收簡訊的電話號碼清單。
+ 如何傳送簡訊。

## 使用案例
<a name="sns-examples-sending-sms-scenario"></a>

您可以使用 Amazon SNS 傳送文字訊息或簡訊至啟用簡訊功能的裝置。您可以直接傳送訊息至一組電話號碼，或一次傳送一則訊息至多組電話號碼，只要訂閱那些電話號碼到主題並且傳送您的訊息到該主題即可。

在此範例中，您會使用一系列 Node.js 模組，將 SMS 文字訊息從 Amazon SNS 發佈至啟用 SMS 的裝置。Node.js 模組使用適用於 JavaScript 的 SDK，以`SNS`用戶端類別的下列方法發佈 SMS 訊息：
+ [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) 匯入/匯出用戶端服務物件和命令。  
這需要 Node.js 13.x 版或更新版本。若要下載並安裝最新版本的 Node.js，請參閱 [Node.js 下載。](https://nodejs.org/en/download)
如果您偏好使用 CommonJS 語法，請參閱 [JavaScript ES6/CommonJS 語法](sdk-example-javascript-syntax.md)。

## 取得簡訊屬性
<a name="sending-sms-getattributes"></a>

使用 Amazon SNS 指定簡訊的偏好設定，例如如何最佳化交付 （用於成本或可靠交付）、每月花費限制、如何記錄訊息交付，以及是否訂閱每日簡訊用量報告。系統會擷取這些偏好設定，並將其設定為 Amazon SNS 的 SMS 屬性。

在此範例中，使用 Node.js 模組取得 Amazon SNS 中目前的 SMS 屬性。

建立`libs`目錄，並建立檔案名稱為 的 Node.js 模組`snsClient.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({});
```

您可以在 [ GitHub 上找到此](https://github.com/awsdocs/aws-doc-sdk-examples/blob/main/javascriptv3/example_code/sns/libs/snsClient.js)範例程式碼。

 以檔名 `get-sms-attributes.js` 建立一個 Node.js 模組。

如先前所示設定 SDK，包括下載所需的用戶端和套件。建立一個物件，其中包含用來取得簡訊屬性的參數，包括要擷取的個別屬性名稱。如需可用 SMS 屬性的詳細資訊，請參閱《Amazon Simple Notification Service API 參考》中的 [SetSMSAttributes](https://docs.aws.amazon.com/sns/latest/api/API_SetSMSAttributes.html)。

此範例會取得 `DefaultSMSType` 屬性，其可控制簡訊的傳送方式；`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
```

您可以在 [ GitHub 上找到此](https://github.com/awsdocs/aws-doc-sdk-examples/blob/main/javascriptv3/example_code/sns/actions/get-sms-attributes.js)範例程式碼。

## 設定簡訊屬性
<a name="sending-sms-setattributes"></a>

在此範例中，使用 Node.js 模組取得 Amazon SNS 中目前的 SMS 屬性。

建立`libs`目錄，並建立檔案名稱為 的 Node.js 模組`snsClient.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({});
```

您可以在 [ GitHub 上找到此](https://github.com/awsdocs/aws-doc-sdk-examples/blob/main/javascriptv3/example_code/sns/libs/snsClient.js)範例程式碼。

 以檔名 `set-sms-attribute-type.js` 建立一個 Node.js 模組。如先前所示設定 SDK，包括安裝所需的用戶端和套件。建立一個物件，其中包含用來設定簡訊屬性的參數，包括要設定的個別屬性名稱，以及要為每個屬性設定的值。如需可用 SMS 屬性的詳細資訊，請參閱《Amazon Simple Notification Service API 參考》中的 [ SetSMSAttributes](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 
```

您可以在 [ GitHub 上找到此](https://github.com/awsdocs/aws-doc-sdk-examples/blob/main/javascriptv3/example_code/sns/actions/set-sms-attribute-type.js)範例程式碼。

## 檢查電話號碼是否已停止接收
<a name="sending-sms-checkifphonenumberisoptedout"></a>

在此範例中，您可以使用 Node.js 模組來檢查電話號碼是否選擇不要接收簡訊。

建立`libs`目錄，並建立檔案名稱為 的 Node.js 模組`snsClient.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({});
```

您可以在 [ GitHub 上找到此](https://github.com/awsdocs/aws-doc-sdk-examples/blob/main/javascriptv3/example_code/sns/libs/snsClient.js)範例程式碼。

以檔名 `check-if-phone-number-is-opted-out.js` 建立一個 Node.js 模組。依前述內容設定軟體開發套件。建立一個物件，其中包含要以參數形式檢查的電話號碼。

此範例會設定 `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 
```

您可以在 [ GitHub 上找到此](https://github.com/awsdocs/aws-doc-sdk-examples/blob/main/javascriptv3/example_code/sns/actions/check-if-phone-number-is-opted-out.js)範例程式碼。

## 列出已停止接收的電話號碼
<a name="sending-sms-listphonenumbersoptedout"></a>

在此範例中，您可以使用 Node.js 模組來取得選擇不要接收簡訊的電話號碼清單。

建立`libs`目錄，並建立檔案名稱為 的 Node.js 模組`snsClient.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({});
```

您可以在 [ GitHub 上找到此](https://github.com/awsdocs/aws-doc-sdk-examples/blob/main/javascriptv3/example_code/sns/libs/snsClient.js)範例程式碼。

以檔名 `list-phone-numbers-opted-out.js` 建立一個 Node.js 模組。依前述內容設定軟體開發套件。建立空白物件做為參數。

接著，將物件傳遞至 `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 
```

您可以在 [ GitHub 上找到此](https://github.com/awsdocs/aws-doc-sdk-examples/blob/main/javascriptv3/example_code/sns/actions/list-phone-numbers-opted-out.js)範例程式碼。

## 發佈簡訊
<a name="sending-sms-publishsms"></a>

在此範例中，Node.js 模組可用來傳送簡訊至電話號碼。

建立`libs`目錄，並建立檔案名稱為 的 Node.js 模組`snsClient.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({});
```

您可以在 [ GitHub 上找到此](https://github.com/awsdocs/aws-doc-sdk-examples/blob/main/javascriptv3/example_code/sns/libs/snsClient.js)範例程式碼。

以檔名 `publish-sms.js` 建立一個 Node.js 模組。如先前所示設定 SDK，包括安裝所需的用戶端和套件。建立包含 `Message` 和 `PhoneNumber` 參數的物件。

當您傳送簡訊時，請指定使用 E.164 格式的電話號碼。E。164 是電話號碼結構的標準，用於國際電信通訊。遵照此格式的電話號碼可以有 15 位數的上限限制，前面加上加號 (\$1) 字元和國碼。例如，E.164 格式的美國電話號碼顯示為 \$11001XXX5550100。

此範例會設定 `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
```

您可以在 [ GitHub 上找到此](https://github.com/awsdocs/aws-doc-sdk-examples/blob/main/javascriptv3/example_code/sns/actions/publish-sms.js)範例程式碼。