

 [適用於 JavaScript 的 AWS SDK V3 API 參考指南](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/)詳細說明 第 3 版 適用於 JavaScript 的 AWS SDK (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_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\_ARN}} 取代為您想要列出訂閱之主題的 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\_ARN}} 取代為主題的 Amazon Resource Name (ARN)，並將 {{EMAIL\_ADDRESS}} 取代為要訂閱的電子郵件地址。

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

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

若要執行範例，請在命令提示中輸入以下內容。

```
node subscribe-email.js
```

您可以在 [ GitHub 上找到](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 中的字符。

![訂閱確認訊息，顯示訂閱 SNS 主題的電子郵件地址。](http://docs.aws.amazon.com/zh_tw/sdk-for-javascript/v3/developer-guide/images/token.png)


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

**注意**  
將 {{TOPIC\_ARN}} 取代為主題的 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\_ARN}} 取代為主題的 Amazon Resource Name (ARN)，並將 {{MOBILE\_ENDPOINT\_ARN}} 取代為您訂閱主題的端點。

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

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

若要執行範例，請在命令提示中輸入以下內容。

```
node subscribe-app.js
```

您可以在 [ GitHub 上找到此](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\_ARN}} 取代為主題的 Amazon Resource Name (ARN)，並將 {{LAMBDA\_FUNCTION\_ARN}} 取代為 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\_SUBSCRIPTION\_}}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)範例程式碼。