

 [適用於 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-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)範例程式碼。